Search in sources :

Example 1 with BookInfo

use of com.github.hmdev.info.BookInfo in project AozoraEpub3 by hmdev.

the class AozoraEpub3Converter method getBookInfo.

/** タイトルと著作者を取得. 行番号も保存して出力時に変換出力
	 * 章洗濯用に見出しの行もここで取得
	 * @param src 青空テキストファイルのReader
	 * @param imageInfoReader テキスト内の画像ファイル名を格納して返却
	 * @param titleType 表題種別
	 * @param coverFileName 表紙ファイル名 nullなら表紙無し ""は先頭ファイル "*"は同じファイル名 */
public BookInfo getBookInfo(File srcFile, BufferedReader src, ImageInfoReader imageInfoReader, TitleType titleType, boolean pubFirst) throws Exception {
    try {
        BookInfo bookInfo = new BookInfo(srcFile);
        String line;
        this.lineNum = -1;
        //前の行のバッファ [1行前, 2行前]
        String[] preLines = new String[] { null, null };
        //コメントブロック内
        boolean inComment = false;
        //コメントが始まったらtrue
        boolean firstCommentStarted = false;
        //最初のコメント開始行
        int firstCommentLineNum = -1;
        //先頭行
        String[] firstLines = new String[10];
        //先頭行の開始行番号
        int firstLineStart = -1;
        //タイトルページ開始行 画像等がなければ-1 タイトルなしは-2
        //int preTitlePageBreak = titleType==TitleType.NONE ? -2 : -1;
        //コメント内の行数
        int commentLineNum = 0;
        //コメント開始行
        int commentLineStart = -1;
        //直線の空行
        int lastEmptyLine = -1;
        //目次用見出し自動抽出
        boolean autoChapter = this.autoChapterName || this.autoChapterNumTitle || this.autoChapterNumOnly || this.autoChapterNumParen || this.autoChapterNumParenTitle || this.chapterPattern != null;
        //改ページ後の目次を追加するならtrue
        boolean addSectionChapter = true;
        //見出し注記の後の文字を追加
        boolean addChapterName = false;
        //見出しの次の行を繋げるときに見出しの次の行番号を設定
        int addNextChapterName = -1;
        //ブロック見出し注記、次の行を繋げる場合に設定
        ChapterLineInfo preChapterLineInfo = null;
        //最後まで回す
        while ((line = src.readLine()) != null) {
            this.lineNum++;
            //見出し等の取得のため前方参照注記は変換 外字文字は置換
            line = CharUtils.removeSpace(this.replaceChukiSufTag(this.convertGaijiChuki(line, true, false)));
            //注記と画像のチェックなので先にルビ除去
            String noRubyLine = CharUtils.removeRuby(line);
            //コメント除外 50文字以上をコメントにする
            if (noRubyLine.startsWith("--------------------------------")) {
                if (!noRubyLine.startsWith("--------------------------------------------------")) {
                    LogAppender.warn(lineNum, "コメント行の文字数が足りません");
                } else {
                    if (firstCommentLineNum == -1)
                        firstCommentLineNum = this.lineNum;
                    //コメントブロックに入ったらタイトル著者終了
                    firstCommentStarted = true;
                    if (inComment) {
                        //コメント行終了
                        if (commentLineNum > 20)
                            LogAppender.warn(lineNum, "コメントが " + commentLineNum + " 行 (" + (commentLineStart + 1) + ") -");
                        commentLineNum = 0;
                        inComment = false;
                        continue;
                    } else {
                        if (lineNum > 10 && !(commentPrint && commentConvert))
                            LogAppender.warn(lineNum, "コメント開始行が10行目以降にあります");
                        //コメント行開始
                        commentLineStart = this.lineNum;
                        inComment = true;
                        continue;
                    }
                }
                if (inComment)
                    commentLineNum++;
            }
            //空行チェック
            if (noRubyLine.equals("") || noRubyLine.equals(" ") || noRubyLine.equals(" ")) {
                lastEmptyLine = lineNum;
                //空行なので次の行へ
                continue;
            }
            if (inComment && !this.commentPrint)
                continue;
            //2行前が改ページと画像の行かをチェックして行番号をbookInfoに保存
            if (!noIllust)
                this.checkImageOnly(bookInfo, preLines, noRubyLine, this.lineNum);
            //見出しのChapter追加
            if (addChapterName) {
                if (//前の見出しがなければ中止
                preChapterLineInfo == null)
                    //前の見出しがなければ中止
                    addChapterName = false;
                else {
                    String name = this.getChapterName(noRubyLine);
                    //字下げ注記等は飛ばして次の行を見る
                    if (name.length() > 0) {
                        preChapterLineInfo.setChapterName(name);
                        preChapterLineInfo.lineNum = lineNum;
                        addChapterName = false;
                        //次の行を繋げる設定
                        if (this.useNextLineChapterName)
                            addNextChapterName = lineNum + 1;
                        //改ページ後のChapter出力を抑止
                        addSectionChapter = false;
                    }
                    //必ず文字が入る
                    preChapterLineInfo = null;
                }
            }
            //画像のファイル名の順にimageInfoReaderにファイル名を追加
            Matcher m = chukiPattern.matcher(noRubyLine);
            while (m.find()) {
                String chukiTag = m.group();
                String chukiName = chukiTag.substring(2, chukiTag.length() - 1);
                if (chukiFlagPageBreak.contains(chukiName)) {
                    //改ページ注記ならフラグON
                    addSectionChapter = true;
                } else if (chapterChukiMap.containsKey(chukiName)) {
                    //見出し注記
                    //注記の後に文字がなければブロックなので次の行 (次の行にブロック注記はこない?)
                    int chapterType = chapterChukiMap.get(chukiName);
                    if (noRubyLine.length() == m.start() + chukiTag.length()) {
                        preChapterLineInfo = new ChapterLineInfo(lineNum + 1, chapterType, addSectionChapter, ChapterLineInfo.getLevel(chapterType), lastEmptyLine == lineNum - 1);
                        bookInfo.addChapterLineInfo(preChapterLineInfo);
                        //次の行を見出しとして利用
                        addChapterName = true;
                        addNextChapterName = -1;
                    } else {
                        bookInfo.addChapterLineInfo(new ChapterLineInfo(lineNum, chapterType, addSectionChapter, ChapterLineInfo.getLevel(chapterType), lastEmptyLine == lineNum - 1, this.getChapterName(noRubyLine.substring(m.end()))));
                        //次の行を連結
                        if (this.useNextLineChapterName)
                            addNextChapterName = lineNum + 1;
                        //次の行を見出しとして利用しない
                        addChapterName = false;
                    }
                    //改ページ後のChapter出力を抑止
                    addSectionChapter = false;
                }
                String lowerChukiTag = chukiTag.toLowerCase();
                int imageStartIdx = chukiTag.lastIndexOf('(');
                if (imageStartIdx > -1) {
                    int imageEndIdx = chukiTag.indexOf(")", imageStartIdx);
                    int imageDotIdx = chukiTag.indexOf('.', imageStartIdx);
                    //訓点送り仮名チェック #の次が(で.を含まない
                    if (imageDotIdx > -1 && imageDotIdx < imageEndIdx) {
                        //画像ファイル名を取得し画像情報を格納
                        String imageFileName = this.getImageChukiFileName(chukiTag, imageStartIdx);
                        if (imageFileName != null) {
                            imageInfoReader.addImageFileName(imageFileName);
                            if (bookInfo.firstImageLineNum == -1) {
                                //小さい画像は無視
                                ImageInfo imageInfo = imageInfoReader.getImageInfo(imageInfoReader.correctExt(imageFileName));
                                if (imageInfo != null && imageInfo.getWidth() > 64 && imageInfo.getHeight() > 64) {
                                    bookInfo.firstImageLineNum = lineNum;
                                    bookInfo.firstImageIdx = imageInfoReader.countImageFileNames() - 1;
                                }
                            }
                        }
                    }
                } else if (lowerChukiTag.startsWith("<img")) {
                    //src=の値抽出
                    String imageFileName = this.getTagAttr(chukiTag, "src");
                    if (imageFileName != null) {
                        //画像がなければそのまま追加
                        imageInfoReader.addImageFileName(imageFileName);
                        if (bookInfo.firstImageLineNum == -1) {
                            //小さい画像は無視
                            ImageInfo imageInfo = imageInfoReader.getImageInfo(imageInfoReader.correctExt(imageFileName));
                            if (imageInfo != null && imageInfo.getWidth() > 64 && imageInfo.getHeight() > 64) {
                                bookInfo.firstImageLineNum = lineNum;
                                bookInfo.firstImageIdx = imageInfoReader.countImageFileNames() - 1;
                            }
                        }
                    }
                }
            }
            //TODO パターンと目次レベルは設定可能にする 空行指定の場合はpreLines利用
            if (autoChapter && bookInfo.getChapterLevel(lineNum) == 0) {
                //文字列から注記と前の空白を除去
                String noChukiLine = CharUtils.removeSpace(CharUtils.removeTag(noRubyLine));
                //その他パターン
                if (this.chapterPattern != null) {
                    if (this.chapterPattern.matcher(noChukiLine).find()) {
                        bookInfo.addChapterLineInfo(new ChapterLineInfo(lineNum, ChapterLineInfo.TYPE_PATTERN, addSectionChapter, ChapterLineInfo.getLevel(ChapterLineInfo.TYPE_PATTERN), lastEmptyLine == lineNum - 1, this.getChapterName(noRubyLine)));
                        //次の行を連結
                        if (this.useNextLineChapterName)
                            addNextChapterName = lineNum + 1;
                        //改ページ後のChapter出力を抑止
                        addSectionChapter = false;
                    }
                }
                int noChukiLineLength = noChukiLine.length();
                if (this.autoChapterName) {
                    boolean isChapter = false;
                    //数字を含まない章名
                    for (int i = 0; i < this.chapterName.length; i++) {
                        String prefix = this.chapterName[i];
                        if (noChukiLine.startsWith(prefix)) {
                            if (noChukiLine.length() == prefix.length()) {
                                isChapter = true;
                                break;
                            } else if (isChapterSeparator(noChukiLine.charAt(prefix.length()))) {
                                isChapter = true;
                                break;
                            }
                        }
                    }
                    //数字を含む章名
                    if (!isChapter) {
                        for (int i = 0; i < this.chapterNumPrefix.length; i++) {
                            String prefix = this.chapterNumPrefix[i];
                            if (noChukiLine.startsWith(prefix)) {
                                int idx = prefix.length();
                                //次が数字かチェック
                                while (noChukiLineLength > idx && isChapterNum(noChukiLine.charAt(idx))) idx++;
                                //数字がなければ抽出しない
                                if (idx <= prefix.length())
                                    break;
                                //後ろをチェック prefixに対応するsuffixで回す
                                for (String suffix : this.chapterNumSuffix[i]) {
                                    if (!"".equals(suffix)) {
                                        if (noChukiLine.substring(idx).startsWith(suffix)) {
                                            idx += suffix.length();
                                            if (noChukiLine.length() == idx) {
                                                isChapter = true;
                                                break;
                                            } else if (isChapterSeparator(noChukiLine.charAt(idx))) {
                                                isChapter = true;
                                                break;
                                            }
                                        }
                                    } else {
                                        if (noChukiLine.length() == idx) {
                                            isChapter = true;
                                            break;
                                        } else if (isChapterSeparator(noChukiLine.charAt(idx))) {
                                            isChapter = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (isChapter) {
                        bookInfo.addChapterLineInfo(new ChapterLineInfo(lineNum, ChapterLineInfo.TYPE_CHAPTER_NAME, addSectionChapter, ChapterLineInfo.getLevel(ChapterLineInfo.TYPE_CHAPTER_NAME), lastEmptyLine == lineNum - 1, this.getChapterName(noRubyLine)));
                        //次の行を連結
                        if (this.useNextLineChapterName)
                            addNextChapterName = lineNum + 1;
                        //次の行を見出しとして利用
                        addChapterName = false;
                        //改ページ後のChapter出力を抑止
                        addSectionChapter = false;
                    }
                }
                if (this.autoChapterNumOnly || this.autoChapterNumTitle) {
                    //数字
                    int idx = 0;
                    while (noChukiLineLength > idx && isChapterNum(noChukiLine.charAt(idx))) idx++;
                    if (idx > 0) {
                        if (this.autoChapterNumOnly && noChukiLine.length() == idx || this.autoChapterNumTitle && noChukiLine.length() > idx && isChapterSeparator(noChukiLine.charAt(idx))) {
                            bookInfo.addChapterLineInfo(new ChapterLineInfo(lineNum, ChapterLineInfo.TYPE_CHAPTER_NUM, addSectionChapter, ChapterLineInfo.getLevel(ChapterLineInfo.TYPE_CHAPTER_NUM), lastEmptyLine == lineNum - 1, this.getChapterName(noRubyLine)));
                            //次の行を連結
                            if (this.useNextLineChapterName)
                                addNextChapterName = lineNum + 1;
                            //次の行を見出しとして利用しない
                            addChapterName = false;
                            //改ページ後のChapter出力を抑止
                            addSectionChapter = false;
                        }
                    }
                }
                if (this.autoChapterNumParen || this.autoChapterNumParenTitle) {
                    //括弧内数字のみ
                    for (int i = 0; i < this.chapterNumParenPrefix.length; i++) {
                        String prefix = this.chapterNumParenPrefix[i];
                        if (noChukiLine.startsWith(prefix)) {
                            int idx = prefix.length();
                            //次が数字かチェック
                            while (noChukiLineLength > idx && isChapterNum(noChukiLine.charAt(idx))) idx++;
                            //数字がなければ抽出しない
                            if (idx <= prefix.length())
                                break;
                            //後ろをチェック
                            String suffix = this.chapterNumParenSuffix[i];
                            if (noChukiLine.substring(idx).startsWith(suffix)) {
                                idx += suffix.length();
                                if (this.autoChapterNumParen && noChukiLine.length() == idx || this.autoChapterNumParenTitle && noChukiLine.length() > idx && isChapterSeparator(noChukiLine.charAt(idx))) {
                                    bookInfo.addChapterLineInfo(new ChapterLineInfo(lineNum, ChapterLineInfo.TYPE_CHAPTER_NUM, addSectionChapter, 13, lastEmptyLine == lineNum - 1, this.getChapterName(noRubyLine)));
                                    //次の行を連結
                                    if (this.useNextLineChapterName)
                                        addNextChapterName = lineNum + 1;
                                    //次の行を見出しとして利用しない
                                    addChapterName = false;
                                    //改ページ後のChapter出力を抑止
                                    addSectionChapter = false;
                                }
                            }
                        }
                    }
                }
            }
            //改ページ後の注記以外の本文を追加
            if (this.chapterSection && addSectionChapter) {
                //底本:は目次に出さない
                if (noRubyLine.length() > 2 && noRubyLine.charAt(0) == '底' && noRubyLine.charAt(1) == '本' && noRubyLine.charAt(2) == ':') {
                    //改ページ後のChapter出力を抑止
                    addSectionChapter = false;
                } else {
                    //記号のみの行は無視して次の行へ
                    String name = this.getChapterName(noRubyLine);
                    if (name.replaceAll("◇|◆|□|■|▽|▼|☆|★|*|+|×|†| ", "").length() > 0) {
                        bookInfo.addChapterLineInfo(new ChapterLineInfo(lineNum, ChapterLineInfo.TYPE_PAGEBREAK, true, 1, lastEmptyLine == lineNum - 1, name));
                        if (this.useNextLineChapterName)
                            addNextChapterName = lineNum + 1;
                        //改ページ後のChapter出力を抑止
                        addSectionChapter = false;
                    }
                }
            }
            //見出しの次の行&見出しでない
            if (addNextChapterName == lineNum && bookInfo.getChapterLineInfo(lineNum) == null) {
                //見出しの次の行を繋げる
                String name = this.getChapterName(noRubyLine);
                if (name.length() > 0) {
                    ChapterLineInfo info = bookInfo.getChapterLineInfo(lineNum - 1);
                    if (info != null)
                        info.joinChapterName(name);
                }
                addNextChapterName = -1;
            }
            //コメント行の後はタイトル取得はしない
            if (!firstCommentStarted) {
                String replaced = CharUtils.getChapterName(noRubyLine, 0);
                if (firstLineStart == -1) {
                    //文字の行が来たら先頭行開始
                    if (replaced.length() > 0) {
                        firstLineStart = this.lineNum;
                        firstLines[0] = line;
                    }
                } else {
                    //改ページで終了
                    if (isPageBreakLine(noRubyLine))
                        firstCommentStarted = true;
                    if (this.lineNum - firstLineStart > firstLines.length - 1) {
                        firstCommentStarted = true;
                    } else if (replaced.length() > 0) {
                        firstLines[this.lineNum - firstLineStart] = line;
                    }
                }
            }
            //前の2行を保存
            preLines[1] = preLines[0];
            preLines[0] = noRubyLine;
        }
        //行数設定
        bookInfo.totalLineNum = lineNum;
        if (inComment) {
            LogAppender.error(commentLineStart, "コメントが閉じていません");
        }
        //表題と著者を先頭行から設定
        bookInfo.setMetaInfo(titleType, pubFirst, firstLines, firstLineStart, firstCommentLineNum);
        //タイトルのChapter追加
        if (bookInfo.titleLine > -1) {
            String name = this.getChapterName(bookInfo.title);
            ChapterLineInfo chapterLineInfo = bookInfo.getChapterLineInfo(bookInfo.titleLine);
            if (chapterLineInfo == null)
                bookInfo.addChapterLineInfo(new ChapterLineInfo(bookInfo.titleLine, ChapterLineInfo.TYPE_TITLE, true, 0, false, name));
            else {
                chapterLineInfo.type = ChapterLineInfo.TYPE_TITLE;
                chapterLineInfo.level = 0;
            }
            //1行目がタイトルでなければ除外
            if (bookInfo.titleLine > 0) {
                for (int i = bookInfo.titleLine - 1; i >= 0; i--) bookInfo.removeChapterLineInfo(i);
            }
        }
        if (bookInfo.orgTitleLine > 0)
            bookInfo.removeChapterLineInfo(bookInfo.orgTitleLine);
        if (bookInfo.subTitleLine > 0)
            bookInfo.removeChapterLineInfo(bookInfo.subTitleLine);
        if (bookInfo.subOrgTitleLine > 0)
            bookInfo.removeChapterLineInfo(bookInfo.subOrgTitleLine);
        //前後2行前と2行後に3つ以上に抽出した見出しがある場合連続する見出しを除去
        if (this.excludeSeqencialChapter)
            bookInfo.excludeTocChapter();
        return bookInfo;
    } catch (Exception e) {
        e.printStackTrace();
        LogAppender.error(lineNum, "");
        throw e;
    }
}
Also used : Matcher(java.util.regex.Matcher) BookInfo(com.github.hmdev.info.BookInfo) ChapterLineInfo(com.github.hmdev.info.ChapterLineInfo) ImageInfo(com.github.hmdev.info.ImageInfo) IOException(java.io.IOException)

Example 2 with BookInfo

use of com.github.hmdev.info.BookInfo in project AozoraEpub3 by hmdev.

the class AozoraEpub3Applet method convertFile.

/** 内部用変換関数 Appletの設定を引数に渡す
	 * @param srcFile 変換するファイル txt,zip,cbz,(rar,cbr)
	 * @param dstPath 出力先パス
	 * @param txtIdx Zip内テキストファイルの位置
	 */
private void convertFile(File srcFile, File dstPath, String ext, int txtIdx, boolean imageOnly) {
    //パラメータ設定
    if (!"txt".equals(ext) && !"txtz".equals(ext) && !"zip".equals(ext) && !"cbz".equals(ext) && !"rar".equals(ext)) {
        if (!"png".equals(ext) && !"jpg".equals(ext) && !"jpeg".equals(ext) && !"gif".equals(ext)) {
            LogAppender.println("txt, txtz, zip, cbz rar 以外は変換できません");
        }
        return;
    }
    //表紙にする挿絵の位置-1なら挿絵は使わない
    int coverImageIndex = -1;
    //表紙情報追加
    String coverFileName = this.jComboCover.getEditor().getItem().toString();
    if (coverFileName.equals(this.jComboCover.getItemAt(0).toString())) {
        //先頭の挿絵
        coverFileName = "";
        coverImageIndex = 0;
    } else if (coverFileName.equals(this.jComboCover.getItemAt(1).toString())) {
        //入力ファイルと同じ名前+.jpg/.png
        coverFileName = AozoraEpub3.getSameCoverFileName(srcFile);
    } else if (coverFileName.equals(this.jComboCover.getItemAt(2).toString())) {
        //表紙無し
        coverFileName = null;
    }
    boolean isFile = "txt".equals(ext);
    ImageInfoReader imageInfoReader = new ImageInfoReader(isFile, srcFile);
    //zip内の画像をロード
    try {
        if (!isFile) {
            if ("rar".equals(ext)) {
                //Rar内の画像情報読み込み 画像のみならファイル順も格納
                imageInfoReader.loadRarImageInfos(srcFile, imageOnly);
            } else {
                //Zip内の画像情報読み込み 画像のみならファイル順も格納
                imageInfoReader.loadZipImageInfos(srcFile, imageOnly);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogAppender.error(e.getMessage());
    }
    //BookInfo取得
    BookInfo bookInfo = null;
    try {
        if (!imageOnly) {
            //テキストファイルからメタ情報や画像単独ページ情報を取得
            bookInfo = AozoraEpub3.getBookInfo(srcFile, ext, txtIdx, imageInfoReader, this.aozoraConverter, this.jComboEncType.getSelectedItem().toString(), BookInfo.TitleType.indexOf(this.jComboTitle.getSelectedIndex()), jCheckPubFirst.isSelected());
        }
    } catch (Exception e) {
        LogAppender.error("ファイルが読み込めませんでした : " + srcFile.getPath());
        return;
    }
    if (this.convertCanceled) {
        LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
        return;
    }
    Epub3Writer writer = this.epub3Writer;
    try {
        if (!isFile) {
            //Zip内の画像情報をbookInfoに設定
            if (imageOnly) {
                LogAppender.println("画像のみのePubファイルを生成します");
                //画像出力用のBookInfo生成
                bookInfo = new BookInfo(srcFile);
                bookInfo.imageOnly = true;
                //Writerを画像出力用派生クラスに入れ替え
                writer = this.epub3ImageWriter;
                if (imageInfoReader.countImageFileInfos() == 0) {
                    LogAppender.error("画像がありませんでした");
                    return;
                }
                //名前順で並び替え
                imageInfoReader.sortImageFileNames();
                //先頭画像をbookInfoに設定しておく
                //if (coverImageIndex == 0) {
                //	bookInfo.coverImage = imageInfoReader.getImage(0);
                //}
                //画像数をプログレスバーに設定 xhtml出力で+1 画像出力で+10
                this.jProgressBar.setMaximum(imageInfoReader.countImageFileInfos() * 11);
                jProgressBar.setValue(0);
                jProgressBar.setStringPainted(true);
            } else {
                //画像がなければプレビュー表示しないようにindexを-1に
                if (imageInfoReader.countImageFileNames() == 0)
                    coverImageIndex = -1;
                //zipテキストならzip内の注記以外の画像も追加
                imageInfoReader.addNoNameImageFileName();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogAppender.error(e.getMessage());
    }
    if (bookInfo == null) {
        LogAppender.error("書籍の情報が取得できませんでした");
        return;
    }
    //テキストなら行数/100と画像数をプログレスバーに設定
    if (bookInfo.totalLineNum > 0) {
        if (isFile)
            this.jProgressBar.setMaximum(bookInfo.totalLineNum / 10 + imageInfoReader.countImageFileNames() * 10);
        else
            this.jProgressBar.setMaximum(bookInfo.totalLineNum / 10 + imageInfoReader.countImageFileInfos() * 10);
        jProgressBar.setValue(0);
        jProgressBar.setStringPainted(true);
    }
    //表紙目次ページ出力設定
    bookInfo.insertCoverPage = this.jCheckCoverPage.isSelected();
    bookInfo.insertTocPage = this.jCheckTocPage.isSelected();
    bookInfo.insertCoverPageToc = this.jCheckCoverPageToc.isSelected();
    bookInfo.insertTitleToc = this.jCheckTitleToc.isSelected();
    //表題の見出しが非表示で行が追加されていたら削除
    if (!bookInfo.insertTitleToc && bookInfo.titleLine >= 0) {
        bookInfo.removeChapterLineInfo(bookInfo.titleLine);
    }
    //目次縦書き
    bookInfo.setTocVertical(this.jRadioTocV.isSelected());
    //縦書き横書き設定追加
    bookInfo.vertical = this.jRadioVertical.isSelected();
    this.aozoraConverter.vertical = bookInfo.vertical;
    //表題左右中央
    if (!this.jCheckTitlePage.isSelected()) {
        bookInfo.titlePageType = BookInfo.TITLE_NONE;
    } else if (this.jRadioTitleNormal.isSelected()) {
        bookInfo.titlePageType = BookInfo.TITLE_NORMAL;
    } else if (this.jRadioTitleMiddle.isSelected()) {
        bookInfo.titlePageType = BookInfo.TITLE_MIDDLE;
    } else if (this.jRadioTitleHorizontal.isSelected()) {
        bookInfo.titlePageType = BookInfo.TITLE_HORIZONTAL;
    }
    //先頭からの場合で指定行数以降なら表紙無し
    if ("".equals(coverFileName) && !imageOnly) {
        try {
            int maxCoverLine = Integer.parseInt(this.jTextMaxCoverLine.getText());
            if (maxCoverLine > 0 && (bookInfo.firstImageLineNum == -1 || bookInfo.firstImageLineNum >= maxCoverLine)) {
                coverImageIndex = -1;
                coverFileName = null;
            } else {
                coverImageIndex = bookInfo.firstImageIdx;
            }
        } catch (Exception e) {
        }
    }
    //表紙ページの情報をbookInfoに設定
    bookInfo.coverFileName = coverFileName;
    bookInfo.coverImageIndex = coverImageIndex;
    String[] titleCreator = BookInfo.getFileTitleCreator(srcFile.getName());
    if (jCheckUseFileName.isSelected()) {
        //ファイル名優先ならテキスト側の情報は不要
        bookInfo.title = "";
        bookInfo.creator = "";
        if (titleCreator[0] != null)
            bookInfo.title = titleCreator[0];
        if (titleCreator[1] != null)
            bookInfo.creator = titleCreator[1];
    } else {
        //テキストから取得できなければファイル名を利用
        if (bookInfo.title == null || bookInfo.title.length() == 0) {
            bookInfo.title = titleCreator[0] == null ? "" : titleCreator[0];
            if (bookInfo.creator == null || bookInfo.creator.length() == 0)
                bookInfo.creator = titleCreator[1] == null ? "" : titleCreator[1];
        }
    }
    if (this.convertCanceled) {
        LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
        return;
    }
    //前回の変換設定を反映
    BookInfoHistory history = this.getBookInfoHistory(bookInfo);
    if (history != null) {
        if (bookInfo.title.length() == 0)
            bookInfo.title = history.title;
        bookInfo.titleAs = history.titleAs;
        if (bookInfo.creator.length() == 0)
            bookInfo.creator = history.creator;
        bookInfo.creatorAs = history.creatorAs;
        if (bookInfo.publisher == null)
            bookInfo.publisher = history.publisher;
        //表紙設定
        if (jCheckCoverHistory.isSelected()) {
            bookInfo.coverEditInfo = history.coverEditInfo;
            bookInfo.coverFileName = history.coverFileName;
            bookInfo.coverExt = history.coverExt;
            bookInfo.coverImageIndex = history.coverImageIndex;
            //確認ダイアログ表示しない場合はイメージを生成
            if (!this.jCheckConfirm.isSelected() && bookInfo.coverEditInfo != null) {
                try {
                    this.jConfirmDialog.jCoverImagePanel.setBookInfo(bookInfo);
                    if (bookInfo.coverImageIndex >= 0 && bookInfo.coverImageIndex < imageInfoReader.countImageFileNames()) {
                        bookInfo.coverImage = imageInfoReader.getImage(bookInfo.coverImageIndex);
                    } else if (bookInfo.coverImage == null && bookInfo.coverFileName != null) {
                        bookInfo.loadCoverImage(bookInfo.coverFileName);
                    }
                    bookInfo.coverImage = this.jConfirmDialog.jCoverImagePanel.getModifiedImage(this.coverW, this.coverH);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    String outExt = this.jComboExt.getEditor().getItem().toString().trim();
    ////////////////////////////////
    //Kindleチェック
    File kindlegen = null;
    writer.setIsKindle(false);
    if (outExt.startsWith(".mobi")) {
        kindlegen = new File(this.jarPath + "kindlegen.exe");
        if (!kindlegen.isFile()) {
            kindlegen = new File(this.jarPath + "kindlegen");
            if (!kindlegen.isFile()) {
                kindlegen = null;
            }
        }
        if (kindlegen == null) {
            JOptionPane.showMessageDialog(this, "kindlegenがありません\nkindlegen.exeをjarファイルの場所にコピーしてください", "kindlegenエラー", JOptionPane.WARNING_MESSAGE);
            LogAppender.println("変換処理をキャンセルしました");
            return;
        }
        writer.setIsKindle(true);
    }
    //確認ダイアログ 変換ボタン押下時にbookInfo更新
    if (this.jCheckConfirm.isSelected()) {
        //表題と著者設定 ファイル名から設定
        String title = "";
        String creator = "";
        if (bookInfo.title != null)
            title = bookInfo.title;
        if (bookInfo.creator != null)
            creator = bookInfo.creator;
        this.jConfirmDialog.setChapterCheck(jCheckChapterSection.isSelected(), jCheckChapterH.isSelected(), jCheckChapterH1.isSelected(), jCheckChapterH2.isSelected(), jCheckChapterH3.isSelected(), jCheckChapterName.isSelected(), jCheckChapterNumOnly.isSelected() || jCheckChapterNumTitle.isSelected() || jCheckChapterNumParen.isSelected() || jCheckChapterNumParenTitle.isSelected(), jCheckChapterPattern.isSelected());
        this.jConfirmDialog.showDialog(srcFile, (dstPath != null ? dstPath.getAbsolutePath() : srcFile.getParentFile().getAbsolutePath()) + File.separator, title, creator, this.jComboTitle.getSelectedIndex(), jCheckPubFirst.isSelected(), bookInfo, imageInfoReader, this.jFrameParent.getLocation(), coverW, coverH);
        //ダイアログが閉じた後に再開
        if (this.jConfirmDialog.canceled) {
            this.convertCanceled = true;
            LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
            return;
        }
        if (this.jConfirmDialog.skipped) {
            this.setBookInfoHistory(bookInfo);
            LogAppender.println("変換をスキップしました : " + srcFile.getAbsolutePath());
            return;
        }
        //変換前確認のチェックを反映
        if (!this.jConfirmDialog.jCheckConfirm2.isSelected())
            jCheckConfirm.setSelected(false);
        //確認ダイアログの値をBookInfoに設定
        bookInfo.title = this.jConfirmDialog.getMetaTitle();
        bookInfo.creator = this.jConfirmDialog.getMetaCreator();
        bookInfo.titleAs = this.jConfirmDialog.getMetaTitleAs();
        bookInfo.creatorAs = this.jConfirmDialog.getMetaCreatorAs();
        bookInfo.publisher = this.jConfirmDialog.getMetaPublisher();
        //著者が空欄なら著者行もクリア
        if (bookInfo.creator.length() == 0)
            bookInfo.creatorLine = -1;
        //プレビューでトリミングされていたらbookInfo.coverImageにBufferedImageを設定 それ以外はnullにする
        BufferedImage coverImage = this.jConfirmDialog.jCoverImagePanel.getModifiedImage(this.coverW, this.coverH);
        if (coverImage != null) {
            //Epub3Writerでイメージを出力
            bookInfo.coverImage = coverImage;
            //元の表紙は残す
            if (this.jConfirmDialog.jCheckReplaceCover.isSelected())
                bookInfo.coverImageIndex = -1;
        } else {
            bookInfo.coverImage = null;
        }
        this.setBookInfoHistory(bookInfo);
    } else {
        //表題の見出しが非表示で行が追加されていたら削除
        if (!bookInfo.insertTitleToc && bookInfo.titleLine >= 0) {
            bookInfo.removeChapterLineInfo(bookInfo.titleLine);
        }
    }
    boolean autoFileName = this.jCheckAutoFileName.isSelected();
    boolean overWrite = this.jCheckOverWrite.isSelected();
    //出力ファイル
    File outFile = null;
    //Kindleは一旦tmpファイルに出力
    File outFileOrg = null;
    if (kindlegen != null) {
        outFile = AozoraEpub3.getOutFile(srcFile, dstPath, bookInfo, autoFileName, ".epub");
        File mobiFile = new File(outFile.getAbsolutePath().substring(0, outFile.getAbsolutePath().length() - 4) + "mobi");
        if (!overWrite && (mobiFile.exists() || (outExt.endsWith(".epub") && outFile.exists()))) {
            LogAppender.println("変換中止: " + srcFile.getAbsolutePath());
            if (mobiFile.exists())
                LogAppender.println("ファイルが存在します: " + mobiFile.getAbsolutePath());
            else
                LogAppender.println("ファイルが存在します: " + outFile.getAbsolutePath());
            return;
        }
        outFileOrg = outFile;
        try {
            outFile = File.createTempFile("kindle", ".epub", outFile.getParentFile());
            if (!outExt.endsWith(".epub"))
                outFile.deleteOnExit();
        } catch (IOException e) {
            outFile = outFileOrg;
            outFileOrg = null;
        }
    } else {
        outFile = AozoraEpub3.getOutFile(srcFile, dstPath, bookInfo, autoFileName, outExt);
        //上書き確認
        if (!overWrite && outFile.exists()) {
            LogAppender.println("変換中止: " + srcFile.getAbsolutePath());
            LogAppender.println("ファイルが存在します: " + outFile.getAbsolutePath());
            return;
        }
    }
    /*
		if (overWrite &&  outFile.exists()) {
			int ret = JOptionPane.showConfirmDialog(this, "ファイルが存在します\n上書きしますか?\n(取り消しで変換キャンセル)", "上書き確認", JOptionPane.YES_NO_CANCEL_OPTION);
			if (ret == JOptionPane.NO_OPTION) {
				LogAppender.println("変換中止: "+srcFile.getAbsolutePath());
				return;
			} else if (ret == JOptionPane.CANCEL_OPTION) {
				LogAppender.println("変換中止: "+srcFile.getAbsolutePath());
				convertCanceled = true;
				LogAppender.println("変換処理をキャンセルしました");
				return;
			}
		}*/
    ////////////////////////////////
    //変換実行
    AozoraEpub3.convertFile(srcFile, ext, outFile, this.aozoraConverter, writer, this.jComboEncType.getSelectedItem().toString(), bookInfo, imageInfoReader, txtIdx);
    imageInfoReader = null;
    //画像は除去
    bookInfo.coverImage = null;
    //変換中にキャンセルされた場合
    if (this.convertCanceled) {
        LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
        return;
    }
    //kindlegen.exeがあれば実行
    try {
        if (kindlegen != null) {
            long time = System.currentTimeMillis();
            String outFileName = outFile.getAbsolutePath();
            LogAppender.println("kindlegenを実行します : " + kindlegen.getName() + " \"" + outFileName + "\"");
            ProcessBuilder pb = new ProcessBuilder(kindlegen.getAbsolutePath(), "-locale", "en", "-verbose", outFileName);
            this.kindleProcess = pb.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(this.kindleProcess.getInputStream()));
            String line;
            int idx = 0;
            int cnt = 0;
            String msg = "";
            while ((line = br.readLine()) != null) {
                if (line.length() > 0) {
                    System.out.println(line);
                    if (msg.startsWith("Error"))
                        msg += line;
                    else
                        msg = line;
                    if (idx++ % 2 == 0) {
                        if (cnt++ > 100) {
                            cnt = 1;
                            LogAppender.println();
                        }
                        LogAppender.append(".");
                    }
                }
            }
            br.close();
            if (convertCanceled) {
                LogAppender.println("\n" + msg + "\nkindlegenの変換を中断しました");
            } else {
                if (outFileOrg != null) {
                    //mobiリネーム
                    File mobiTmpFile = new File(outFile.getAbsolutePath().substring(0, outFile.getAbsolutePath().length() - 4) + "mobi");
                    File mobiFile = new File(outFileOrg.getAbsolutePath().substring(0, outFileOrg.getAbsolutePath().length() - 4) + "mobi");
                    if (mobiFile.exists())
                        mobiFile.delete();
                    mobiTmpFile.renameTo(mobiFile);
                    if (outExt.endsWith(".epub")) {
                        //epubリネーム
                        if (outFileOrg.exists())
                            outFileOrg.delete();
                        outFile.renameTo(outFileOrg);
                    } else {
                        outFile.delete();
                    }
                    LogAppender.println("\n" + msg + "\nkindlegen変換完了 [" + (((System.currentTimeMillis() - time) / 100) / 10f) + "s] -> " + mobiFile.getName());
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (this.kindleProcess != null)
            this.kindleProcess.destroy();
        this.kindleProcess = null;
    }
}
Also used : ImageInfoReader(com.github.hmdev.image.ImageInfoReader) Epub3Writer(com.github.hmdev.writer.Epub3Writer) InputStreamReader(java.io.InputStreamReader) BookInfo(com.github.hmdev.info.BookInfo) IOException(java.io.IOException) BookInfoHistory(com.github.hmdev.info.BookInfoHistory) Point(java.awt.Point) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BufferedImage(java.awt.image.BufferedImage) BufferedReader(java.io.BufferedReader) File(java.io.File)

Example 3 with BookInfo

use of com.github.hmdev.info.BookInfo in project AozoraEpub3 by hmdev.

the class AozoraEpub3 method getBookInfo.

/** 前処理で一度読み込んでタイトル等の情報を取得 */
public static BookInfo getBookInfo(File srcFile, String ext, int txtIdx, ImageInfoReader imageInfoReader, AozoraEpub3Converter aozoraConverter, String encType, BookInfo.TitleType titleType, boolean pubFirst) {
    try {
        String[] textEntryName = new String[1];
        InputStream is = AozoraEpub3.getTextInputStream(srcFile, ext, imageInfoReader, textEntryName, txtIdx);
        if (is == null)
            return null;
        //タイトル、画像注記、左右中央注記、目次取得
        BufferedReader src = new BufferedReader(new InputStreamReader(is, (String) encType));
        BookInfo bookInfo = aozoraConverter.getBookInfo(srcFile, src, imageInfoReader, titleType, pubFirst);
        is.close();
        bookInfo.textEntryName = textEntryName[0];
        return bookInfo;
    } catch (Exception e) {
        e.printStackTrace();
        LogAppender.append("エラーが発生しました : ");
        LogAppender.println(e.getMessage());
    }
    return null;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) InputStream(java.io.InputStream) BookInfo(com.github.hmdev.info.BookInfo) BufferedReader(java.io.BufferedReader) RarException(com.github.junrar.exception.RarException) IOException(java.io.IOException) ParseException(org.apache.commons.cli.ParseException)

Example 4 with BookInfo

use of com.github.hmdev.info.BookInfo in project AozoraEpub3 by hmdev.

the class AozoraEpub3 method main.

/** コマンドライン実行用 */
public static void main(String[] args) {
    String jarPath = System.getProperty("java.class.path");
    int idx = jarPath.indexOf(";");
    if (idx > 0)
        jarPath = jarPath.substring(0, idx);
    if (!jarPath.endsWith(".jar"))
        jarPath = "";
    else
        jarPath = jarPath.substring(0, jarPath.lastIndexOf(File.separator) + 1);
    //this.cachePath = new File(jarPath+".cache");
    //this.webConfigPath = new File(jarPath+"web");
    /** ePub3出力クラス */
    Epub3Writer epub3Writer;
    /** ePub3画像出力クラス */
    Epub3ImageWriter epub3ImageWriter;
    /** 設定ファイル */
    Properties props;
    /** 設定ファイル名 */
    String propFileName = "AozoraEpub3.ini";
    /** 出力先パス */
    File dstPath = null;
    String helpMsg = "AozoraEpub3 [-options] input_files(txt,zip,cbz)\nversion : " + VERSION;
    try {
        //コマンドライン オプション設定
        Options options = new Options();
        options.addOption("h", "help", false, "show usage");
        options.addOption("i", "ini", true, "指定したiniファイルから設定を読み込みます (コマンドラインオプション以外の設定)");
        options.addOption("t", true, "本文内の表題種別\n[0:表題→著者名] (default)\n[1:著者名→表題]\n[2:表題→著者名(副題優先)]\n[3:表題のみ]\n[4:なし]");
        options.addOption("tf", false, "入力ファイル名を表題に利用");
        options.addOption("c", "cover", true, "表紙画像\n[0:先頭の挿絵]\n[1:ファイル名と同じ画像]\n[ファイル名 or URL]");
        options.addOption("ext", true, "出力ファイル拡張子\n[.epub] (default)\n[.kepub.epub]");
        options.addOption("of", false, "出力ファイル名を入力ファイル名に合せる");
        options.addOption("d", "dst", true, "出力先パス");
        options.addOption("enc", true, "入力ファイルエンコード\n[MS932] (default)\n[UTF-8]");
        //options.addOption("id", false, "栞用ID出力 (for Kobo)");
        //options.addOption("tcy", false, "自動縦中横有効");
        //options.addOption("g4", false, "4バイト文字変換");
        //options.addOption("tm", false, "表題を左右中央");
        //options.addOption("cp", false, "表紙画像ページ追加");
        options.addOption("hor", false, "横書き (指定がなければ縦書き)");
        options.addOption("device", true, "端末種別(指定した端末向けの例外処理を行う)\n[kindle]");
        CommandLine commandLine;
        try {
            commandLine = new BasicParser().parse(options, args, true);
        } catch (ParseException e) {
            new HelpFormatter().printHelp(helpMsg, options);
            return;
        }
        //オプションの後ろをファイル名に設定
        String[] fileNames = commandLine.getArgs();
        if (fileNames.length == 0) {
            new HelpFormatter().printHelp(helpMsg, options);
            return;
        }
        //ヘルプ出力
        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp(helpMsg, options);
            return;
        }
        //iniファイル確認
        if (commandLine.hasOption("i")) {
            propFileName = commandLine.getOptionValue("i");
            File file = new File(propFileName);
            if (file == null || !file.isFile()) {
                LogAppender.error("-i : ini file not exist. " + file.getAbsolutePath());
                return;
            }
        }
        //出力パス確認
        if (commandLine.hasOption("d")) {
            dstPath = new File(commandLine.getOptionValue("d"));
            if (dstPath == null || !dstPath.isDirectory()) {
                LogAppender.error("-d : dst path not exist. " + dstPath.getAbsolutePath());
                return;
            }
        }
        //ePub出力クラス初期化
        epub3Writer = new Epub3Writer(jarPath + "template/");
        epub3ImageWriter = new Epub3ImageWriter(jarPath + "template/");
        //propsから読み込み
        props = new Properties();
        try {
            props.load(new FileInputStream(propFileName));
        } catch (Exception e) {
        }
        //try { titleIndex = Integer.parseInt(props.getProperty("TitleType")); } catch (Exception e) {}//表題
        int titleIndex = 0;
        //コマンドラインオプション以外
        //表紙追加
        boolean coverPage = "1".equals(props.getProperty("CoverPage"));
        int titlePage = BookInfo.TITLE_NONE;
        if ("1".equals(props.getProperty("TitlePageWrite"))) {
            try {
                titlePage = Integer.parseInt(props.getProperty("TitlePage"));
            } catch (Exception e) {
            }
        }
        boolean withMarkId = "1".equals(props.getProperty("MarkId"));
        //boolean gaiji32 = "1".equals(props.getProperty("Gaiji32"));
        boolean commentPrint = "1".equals(props.getProperty("CommentPrint"));
        boolean commentConvert = "1".equals(props.getProperty("CommentConvert"));
        boolean autoYoko = "1".equals(props.getProperty("AutoYoko"));
        boolean autoYokoNum1 = "1".equals(props.getProperty("AutoYokoNum1"));
        boolean autoYokoNum3 = "1".equals(props.getProperty("AutoYokoNum3"));
        boolean autoYokoEQ1 = "1".equals(props.getProperty("AutoYokoEQ1"));
        int spaceHyp = 0;
        try {
            spaceHyp = Integer.parseInt(props.getProperty("SpaceHyphenation"));
        } catch (Exception e) {
        }
        //目次追加
        boolean tocPage = "1".equals(props.getProperty("TocPage"));
        //目次縦書き
        boolean tocVertical = "1".equals(props.getProperty("TocVertical"));
        boolean coverPageToc = "1".equals(props.getProperty("CoverPageToc"));
        int removeEmptyLine = 0;
        try {
            removeEmptyLine = Integer.parseInt(props.getProperty("RemoveEmptyLine"));
        } catch (Exception e) {
        }
        int maxEmptyLine = 0;
        try {
            maxEmptyLine = Integer.parseInt(props.getProperty("MaxEmptyLine"));
        } catch (Exception e) {
        }
        //画面サイズと画像リサイズ
        int dispW = 600;
        try {
            dispW = Integer.parseInt(props.getProperty("DispW"));
        } catch (Exception e) {
        }
        int dispH = 800;
        try {
            dispH = Integer.parseInt(props.getProperty("DispH"));
        } catch (Exception e) {
        }
        int coverW = 600;
        try {
            coverW = Integer.parseInt(props.getProperty("CoverW"));
        } catch (Exception e) {
        }
        int coverH = 800;
        try {
            coverH = Integer.parseInt(props.getProperty("CoverH"));
        } catch (Exception e) {
        }
        int resizeW = 0;
        if ("1".equals(props.getProperty("ResizeW")))
            try {
                resizeW = Integer.parseInt(props.getProperty("ResizeNumW"));
            } catch (Exception e) {
            }
        int resizeH = 0;
        if ("1".equals(props.getProperty("ResizeH")))
            try {
                resizeH = Integer.parseInt(props.getProperty("ResizeNumH"));
            } catch (Exception e) {
            }
        int singlePageSizeW = 480;
        try {
            singlePageSizeW = Integer.parseInt(props.getProperty("SinglePageSizeW"));
        } catch (Exception e) {
        }
        int singlePageSizeH = 640;
        try {
            singlePageSizeH = Integer.parseInt(props.getProperty("SinglePageSizeH"));
        } catch (Exception e) {
        }
        int singlePageWidth = 600;
        try {
            singlePageWidth = Integer.parseInt(props.getProperty("SinglePageWidth"));
        } catch (Exception e) {
        }
        float imageScale = 1;
        try {
            imageScale = Float.parseFloat(props.getProperty("ImageScale"));
        } catch (Exception e) {
        }
        int imageFloatType = 0;
        try {
            imageFloatType = Integer.parseInt(props.getProperty("ImageFloatType"));
        } catch (Exception e) {
        }
        int imageFloatW = 0;
        try {
            imageFloatW = Integer.parseInt(props.getProperty("ImageFloatW"));
        } catch (Exception e) {
        }
        int imageFloatH = 0;
        try {
            imageFloatH = Integer.parseInt(props.getProperty("ImageFloatH"));
        } catch (Exception e) {
        }
        int imageSizeType = SectionInfo.IMAGE_SIZE_TYPE_HEIGHT;
        try {
            imageSizeType = Integer.parseInt(props.getProperty("ImageSizeType"));
        } catch (Exception e) {
        }
        boolean fitImage = "1".equals(props.getProperty("FitImage"));
        boolean svgImage = "1".equals(props.getProperty("SvgImage"));
        int rotateImage = 0;
        if ("1".equals(props.getProperty("RotateImage")))
            rotateImage = 90;
        else if ("2".equals(props.getProperty("RotateImage")))
            rotateImage = -90;
        float jpegQualty = 0.8f;
        try {
            jpegQualty = Integer.parseInt(props.getProperty("JpegQuality")) / 100f;
        } catch (Exception e) {
        }
        float gamma = 1.0f;
        if ("1".equals(props.getProperty("Gamma")))
            try {
                gamma = Float.parseFloat(props.getProperty("GammaValue"));
            } catch (Exception e) {
            }
        int autoMarginLimitH = 0;
        int autoMarginLimitV = 0;
        int autoMarginWhiteLevel = 80;
        float autoMarginPadding = 0;
        int autoMarginNombre = 0;
        float nobreSize = 0.03f;
        if ("1".equals(props.getProperty("AutoMargin"))) {
            try {
                autoMarginLimitH = Integer.parseInt(props.getProperty("AutoMarginLimitH"));
            } catch (Exception e) {
            }
            try {
                autoMarginLimitV = Integer.parseInt(props.getProperty("AutoMarginLimitV"));
            } catch (Exception e) {
            }
            try {
                autoMarginWhiteLevel = Integer.parseInt(props.getProperty("AutoMarginWhiteLevel"));
            } catch (Exception e) {
            }
            try {
                autoMarginPadding = Float.parseFloat(props.getProperty("AutoMarginPadding"));
            } catch (Exception e) {
            }
            try {
                autoMarginNombre = Integer.parseInt(props.getProperty("AutoMarginNombre"));
            } catch (Exception e) {
            }
            try {
                autoMarginPadding = Float.parseFloat(props.getProperty("AutoMarginNombreSize"));
            } catch (Exception e) {
            }
        }
        epub3Writer.setImageParam(dispW, dispH, coverW, coverH, resizeW, resizeH, singlePageSizeW, singlePageSizeH, singlePageWidth, imageSizeType, fitImage, svgImage, rotateImage, imageScale, imageFloatType, imageFloatW, imageFloatH, jpegQualty, gamma, autoMarginLimitH, autoMarginLimitV, autoMarginWhiteLevel, autoMarginPadding, autoMarginNombre, nobreSize);
        epub3ImageWriter.setImageParam(dispW, dispH, coverW, coverH, resizeW, resizeH, singlePageSizeW, singlePageSizeH, singlePageWidth, imageSizeType, fitImage, svgImage, rotateImage, imageScale, imageFloatType, imageFloatW, imageFloatH, jpegQualty, gamma, autoMarginLimitH, autoMarginLimitV, autoMarginWhiteLevel, autoMarginPadding, autoMarginNombre, nobreSize);
        //目次階層化設定
        epub3Writer.setTocParam("1".equals(props.getProperty("NavNest")), "1".equals(props.getProperty("NcxNest")));
        //スタイル設定
        String[] pageMargin = {};
        try {
            pageMargin = props.getProperty("PageMargin").split(",");
        } catch (Exception e) {
        }
        if (pageMargin.length != 4)
            pageMargin = new String[] { "0", "0", "0", "0" };
        else {
            String pageMarginUnit = props.getProperty("PageMarginUnit");
            for (int i = 0; i < 4; i++) {
                pageMargin[i] += pageMarginUnit;
            }
        }
        String[] bodyMargin = {};
        try {
            bodyMargin = props.getProperty("BodyMargin").split(",");
        } catch (Exception e) {
        }
        if (bodyMargin.length != 4)
            bodyMargin = new String[] { "0", "0", "0", "0" };
        else {
            String bodyMarginUnit = props.getProperty("BodyMarginUnit");
            for (int i = 0; i < 4; i++) {
                bodyMargin[i] += bodyMarginUnit;
            }
        }
        float lineHeight = 1.8f;
        try {
            lineHeight = Float.parseFloat(props.getProperty("LineHeight"));
        } catch (Exception e) {
        }
        int fontSize = 100;
        try {
            fontSize = Integer.parseInt(props.getProperty("FontSize"));
        } catch (Exception e) {
        }
        boolean boldUseGothic = "1".equals(props.getProperty("BoldUseGothic"));
        boolean gothicUseBold = "1".equals(props.getProperty("gothicUseBold"));
        epub3Writer.setStyles(pageMargin, bodyMargin, lineHeight, fontSize, boldUseGothic, gothicUseBold);
        //自動改ページ
        int forcePageBreakSize = 0;
        int forcePageBreakEmpty = 0;
        int forcePageBreakEmptySize = 0;
        int forcePageBreakChapter = 0;
        int forcePageBreakChapterSize = 0;
        if ("1".equals(props.getProperty("PageBreak"))) {
            try {
                try {
                    forcePageBreakSize = Integer.parseInt(props.getProperty("PageBreakSize")) * 1024;
                } catch (Exception e) {
                }
                if ("1".equals(props.getProperty("PageBreakEmpty"))) {
                    try {
                        forcePageBreakEmpty = Integer.parseInt(props.getProperty("PageBreakEmptyLine"));
                    } catch (Exception e) {
                    }
                    try {
                        forcePageBreakEmptySize = Integer.parseInt(props.getProperty("PageBreakEmptySize")) * 1024;
                    } catch (Exception e) {
                    }
                }
                if ("1".equals(props.getProperty("PageBreakChapter"))) {
                    forcePageBreakChapter = 1;
                    try {
                        forcePageBreakChapterSize = Integer.parseInt(props.getProperty("PageBreakChapterSize")) * 1024;
                    } catch (Exception e) {
                    }
                }
            } catch (Exception e) {
            }
        }
        int maxLength = 64;
        try {
            maxLength = Integer.parseInt((props.getProperty("ChapterNameLength")));
        } catch (Exception e) {
        }
        boolean insertTitleToc = "1".equals(props.getProperty("TitleToc"));
        boolean chapterExclude = "1".equals(props.getProperty("ChapterExclude"));
        boolean chapterUseNextLine = "1".equals(props.getProperty("ChapterUseNextLine"));
        boolean chapterSection = !props.containsKey("ChapterSection") || "1".equals(props.getProperty("ChapterSection"));
        boolean chapterH = "1".equals(props.getProperty("ChapterH"));
        boolean chapterH1 = "1".equals(props.getProperty("ChapterH1"));
        boolean chapterH2 = "1".equals(props.getProperty("ChapterH2"));
        boolean chapterH3 = "1".equals(props.getProperty("ChapterH3"));
        boolean sameLineChapter = "1".equals(props.getProperty("SameLineChapter"));
        boolean chapterName = "1".equals(props.getProperty("ChapterName"));
        boolean chapterNumOnly = "1".equals(props.getProperty("ChapterNumOnly"));
        boolean chapterNumTitle = "1".equals(props.getProperty("ChapterNumTitle"));
        boolean chapterNumParen = "1".equals(props.getProperty("ChapterNumParen"));
        boolean chapterNumParenTitle = "1".equals(props.getProperty("hapterNumParenTitle"));
        String chapterPattern = "";
        if ("1".equals(props.getProperty("ChapterPattern")))
            chapterPattern = props.getProperty("ChapterPatternText");
        //オプション指定を反映
        //表題に入力ファイル名利用
        boolean useFileName = false;
        String coverFileName = null;
        String encType = "MS932";
        String outExt = ".epub";
        //ファイル名を表題に利用
        boolean autoFileName = true;
        boolean vertical = true;
        String targetDevice = null;
        //表題
        if (commandLine.hasOption("t"))
            try {
                titleIndex = Integer.parseInt(commandLine.getOptionValue("t"));
            } catch (Exception e) {
            }
        if (commandLine.hasOption("tf"))
            useFileName = true;
        if (commandLine.hasOption("c"))
            coverFileName = commandLine.getOptionValue("c");
        if (commandLine.hasOption("enc"))
            encType = commandLine.getOptionValue("enc");
        if (commandLine.hasOption("ext"))
            outExt = commandLine.getOptionValue("ext");
        if (commandLine.hasOption("of"))
            autoFileName = false;
        //if(commandLine.hasOption("cp")) coverPage = true;
        if (commandLine.hasOption("hor"))
            vertical = false;
        if (commandLine.hasOption("device")) {
            targetDevice = commandLine.getOptionValue("device");
            if (targetDevice.equalsIgnoreCase("kindle")) {
                epub3Writer.setIsKindle(true);
            }
        }
        //変換クラス生成とパラメータ設定
        AozoraEpub3Converter aozoraConverter = new AozoraEpub3Converter(epub3Writer, jarPath);
        //挿絵なし
        aozoraConverter.setNoIllust("1".equals(props.getProperty("NoIllust")));
        //栞用span出力
        aozoraConverter.setWithMarkId(withMarkId);
        //変換オプション設定
        aozoraConverter.setAutoYoko(autoYoko, autoYokoNum1, autoYokoNum3, autoYokoEQ1);
        //文字出力設定
        int dakutenType = 0;
        try {
            dakutenType = Integer.parseInt(props.getProperty("DakutenType"));
        } catch (Exception e) {
        }
        boolean printIvsBMP = "1".equals(props.getProperty("IvsBMP"));
        boolean printIvsSSP = "1".equals(props.getProperty("IvsSSP"));
        aozoraConverter.setCharOutput(dakutenType, printIvsBMP, printIvsSSP);
        //全角スペースの禁則
        aozoraConverter.setSpaceHyphenation(spaceHyp);
        //コメント
        aozoraConverter.setCommentPrint(commentPrint, commentConvert);
        aozoraConverter.setRemoveEmptyLine(removeEmptyLine, maxEmptyLine);
        //強制改ページ
        aozoraConverter.setForcePageBreak(forcePageBreakSize, forcePageBreakEmpty, forcePageBreakEmptySize, forcePageBreakChapter, forcePageBreakChapterSize);
        //目次設定
        aozoraConverter.setChapterLevel(maxLength, chapterExclude, chapterUseNextLine, chapterSection, chapterH, chapterH1, chapterH2, chapterH3, sameLineChapter, chapterName, chapterNumOnly, chapterNumTitle, chapterNumParen, chapterNumParenTitle, chapterPattern);
        ////////////////////////////////
        for (String fileName : fileNames) {
            LogAppender.println("--------");
            File srcFile = new File(fileName);
            if (srcFile == null || !srcFile.isFile()) {
                LogAppender.error("file not exist. " + srcFile.getAbsolutePath());
                continue;
            }
            String ext = srcFile.getName();
            ext = ext.substring(ext.lastIndexOf('.') + 1).toLowerCase();
            int coverImageIndex = -1;
            if (coverFileName != null) {
                if ("0".equals(coverFileName)) {
                    coverImageIndex = 0;
                    coverFileName = "";
                } else if ("1".equals(coverFileName)) {
                    //入力ファイルと同じ名前+.jpg/.png
                    coverFileName = AozoraEpub3.getSameCoverFileName(srcFile);
                }
            }
            //zipならzip内のテキストを検索
            int txtCount = 1;
            boolean imageOnly = false;
            boolean isFile = "txt".equals(ext);
            if ("zip".equals(ext) || "txtz".equals(ext)) {
                try {
                    txtCount = AozoraEpub3.countZipText(srcFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (txtCount == 0) {
                    txtCount = 1;
                    imageOnly = true;
                }
            } else if ("rar".equals(ext)) {
                try {
                    txtCount = AozoraEpub3.countRarText(srcFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (txtCount == 0) {
                    txtCount = 1;
                    imageOnly = true;
                }
            } else if ("cbz".equals(ext)) {
                imageOnly = true;
            }
            for (int txtIdx = 0; txtIdx < txtCount; txtIdx++) {
                ImageInfoReader imageInfoReader = new ImageInfoReader(isFile, srcFile);
                BookInfo bookInfo = null;
                if (!imageOnly) {
                    bookInfo = AozoraEpub3.getBookInfo(srcFile, ext, txtIdx, imageInfoReader, aozoraConverter, encType, BookInfo.TitleType.indexOf(titleIndex), false);
                    bookInfo.vertical = vertical;
                    bookInfo.insertTocPage = tocPage;
                    bookInfo.setTocVertical(tocVertical);
                    bookInfo.insertTitleToc = insertTitleToc;
                    aozoraConverter.vertical = vertical;
                    //表題ページ
                    bookInfo.titlePageType = titlePage;
                }
                //表題の見出しが非表示で行が追加されていたら削除
                if (!bookInfo.insertTitleToc && bookInfo.titleLine >= 0) {
                    bookInfo.removeChapterLineInfo(bookInfo.titleLine);
                }
                Epub3Writer writer = epub3Writer;
                if (!isFile) {
                    if ("rar".equals(ext)) {
                        imageInfoReader.loadRarImageInfos(srcFile, imageOnly);
                    } else {
                        imageInfoReader.loadZipImageInfos(srcFile, imageOnly);
                    }
                    if (imageOnly) {
                        LogAppender.println("画像のみのePubファイルを生成します");
                        //画像出力用のBookInfo生成
                        bookInfo = new BookInfo(srcFile);
                        bookInfo.imageOnly = true;
                        //Writerを画像出力用派生クラスに入れ替え
                        writer = epub3ImageWriter;
                        if (imageInfoReader.countImageFileInfos() == 0) {
                            LogAppender.error("画像がありませんでした");
                            return;
                        }
                        //名前順で並び替え
                        imageInfoReader.sortImageFileNames();
                    }
                }
                //先頭からの場合で指定行数以降なら表紙無し
                if ("".equals(coverFileName)) {
                    try {
                        int maxCoverLine = Integer.parseInt(props.getProperty("MaxCoverLine"));
                        if (maxCoverLine > 0 && bookInfo.firstImageLineNum >= maxCoverLine) {
                            coverImageIndex = -1;
                            coverFileName = null;
                        }
                    } catch (Exception e) {
                    }
                }
                //表紙設定
                bookInfo.insertCoverPageToc = coverPageToc;
                bookInfo.insertCoverPage = coverPage;
                bookInfo.coverImageIndex = coverImageIndex;
                if (coverFileName != null && !coverFileName.startsWith("http")) {
                    File coverFile = new File(coverFileName);
                    if (!coverFile.exists()) {
                        coverFileName = srcFile.getParent() + "/" + coverFileName;
                        if (!new File(coverFileName).exists()) {
                            coverFileName = null;
                            LogAppender.println("[WARN] 表紙画像ファイルが見つかりません : " + coverFile.getAbsolutePath());
                        }
                    }
                }
                bookInfo.coverFileName = coverFileName;
                String[] titleCreator = BookInfo.getFileTitleCreator(srcFile.getName());
                if (titleCreator != null) {
                    if (useFileName) {
                        if (titleCreator[0] != null && titleCreator[0].trim().length() > 0)
                            bookInfo.title = titleCreator[0];
                        if (titleCreator[1] != null && titleCreator[1].trim().length() > 0)
                            bookInfo.creator = titleCreator[1];
                    } else {
                        //テキストから取得できていない場合
                        if (bookInfo.title == null || bookInfo.title.length() == 0)
                            bookInfo.title = titleCreator[0] == null ? "" : titleCreator[0];
                        if (bookInfo.creator == null || bookInfo.creator.length() == 0)
                            bookInfo.creator = titleCreator[1] == null ? "" : titleCreator[1];
                    }
                }
                File outFile = getOutFile(srcFile, dstPath, bookInfo, autoFileName, outExt);
                AozoraEpub3.convertFile(srcFile, ext, outFile, aozoraConverter, writer, encType, bookInfo, imageInfoReader, txtIdx);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Options(org.apache.commons.cli.Options) Epub3Writer(com.github.hmdev.writer.Epub3Writer) ImageInfoReader(com.github.hmdev.image.ImageInfoReader) BookInfo(com.github.hmdev.info.BookInfo) IOException(java.io.IOException) Epub3ImageWriter(com.github.hmdev.writer.Epub3ImageWriter) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) RarException(com.github.junrar.exception.RarException) IOException(java.io.IOException) ParseException(org.apache.commons.cli.ParseException) HelpFormatter(org.apache.commons.cli.HelpFormatter) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) AozoraEpub3Converter(com.github.hmdev.converter.AozoraEpub3Converter) ParseException(org.apache.commons.cli.ParseException) File(java.io.File)

Example 5 with BookInfo

use of com.github.hmdev.info.BookInfo in project AozoraEpub3 by hmdev.

the class AozoraEpub3ConverterTest method test.

@Test
public void test() {
    Epub3Writer writer = new Epub3Writer("");
    try {
        converter = new AozoraEpub3Converter(writer, "");
        converter.writer = new TestEpub3Writer("");
        converter.bookInfo = new BookInfo(null);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : Epub3Writer(com.github.hmdev.writer.Epub3Writer) BookInfo(com.github.hmdev.info.BookInfo) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

BookInfo (com.github.hmdev.info.BookInfo)5 IOException (java.io.IOException)5 Epub3Writer (com.github.hmdev.writer.Epub3Writer)3 ImageInfoReader (com.github.hmdev.image.ImageInfoReader)2 RarException (com.github.junrar.exception.RarException)2 BufferedReader (java.io.BufferedReader)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 InputStreamReader (java.io.InputStreamReader)2 ParseException (org.apache.commons.cli.ParseException)2 AozoraEpub3Converter (com.github.hmdev.converter.AozoraEpub3Converter)1 BookInfoHistory (com.github.hmdev.info.BookInfoHistory)1 ChapterLineInfo (com.github.hmdev.info.ChapterLineInfo)1 ImageInfo (com.github.hmdev.info.ImageInfo)1 Epub3ImageWriter (com.github.hmdev.writer.Epub3ImageWriter)1 Point (java.awt.Point)1 BufferedImage (java.awt.image.BufferedImage)1 BufferedInputStream (java.io.BufferedInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1