From: Andrey K. <an...@se...> - 2006-01-23 20:02:20
|
Добрый день. Временно выпадал в офф-лайн - были проблемы с доступом в и-нет... Ну вот... Добро пожаловать мне. Кидаю копию последнего письма. Продолжаем дискуссию и пора ее дробить на отдельные куски. Также, раз уж появился CVS, хочу в него доступ как разработчика. Предлагаю поставить такие права, чтобы релизы могли выпускать только Вы, а я буду по мере сил дописывать код. Я так понял, что наша переписка в мэил-листе публикуется на SF. Это очень хорошо - могут придти новые разработчики и/или просто "генераторы идей". Очень полезно максимально показывать активность вокруг проекта. Пока все... Вместе с обсуждением настраиваю недостающее окружение для начала работ. После начну разбираться, что да как в коде. С уважением, Андрей. mailto:an...@se... ---------- Пересылаемое письмо --------------------------------------------------- От: Andrey Khrolenok <an...@se...> Время создания: Fri, 20 Jan 2006 00:10:57 +0300 Тема: Fwd: rtf2html ---------------------------------------------------------------------------------- Валентин, добрый день. Ранее Вы писали 19 января 2006 г., 12:53:41: >> Думаю, выбор шрифта можно переложить на плечи HTML, выдавая через стили наборы >> альтернатив: "font-family: Arial, Verdana, sans-serif;" Т.е. держать файл с >> альтернативами для наиболее употребимых шрифтов: Arial => Verdana, sans-serif, Times New >> Roman =>> Times, serif и т.п. А для всех прочих, если >> Roman =>> знать тип гарнитуры шрифта, можно >> выбирать альтернативы аналогичные какому-либо из известных шрифтов. L> Да, но этот файл должен быть именно файлом, а не жестко прошитыми в L> коде отображниями. Дабы юзер мог прописывать туда что-то свое - мало L> ли, какой ему фонт вздумается использовать... Без проблем. Даже будет грамотнее, если в конвертере будет зашит минимальный набор альтернатив, а через внешний файл пользователь сможет его дополнять и/или переопределять. Вот вариант формата файла: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- <исходный шрифт> ":" [ <альтернативный шрифт> "," ]* <тип шрифта> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Примеры: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Arial: Verdana, sans-serif Lazursky: Times New Roman, Times, serif Times: serif -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- >> ИМХО, OLE лесом!.. В комплекте с OLE объектом в файле всегда идет уже сгенеренная >> картинка. В принципе, ее нам достаточно. И нефиг заморачиваться. L> Насчет идущей в комплекте картинки - не знал. Хотя мог бы и L> догадаться: видимо, как раз когда с ними начинаются проблемы, Ворд L> показывает большие кресты св. Патрика на месте формул и прочего :) Ну про проблемы не знаю, знаю, что они идут для того, чтобы документ можно было бы смотреть и печатать даже на компе, где нет соответствующего OLE-сервера. Не уверен про RTF, но в DOC-файлах такие дублирующие картинки точно есть. >> Формат картинок можно оставлять как в RTF-файле - WMF. Желающие потом могут >> сконвертировать его в любой другой отдельными прогами. L> Там совсем не обязательно WMF. Смотрим "Word 2002 RTF Specification Final.doc": [...] L> html, помнится, никакие векторные картинки показывать не умеет, L> поэтому можно было бы конвертить все это дело в png/jpeg. Или L> складывать как есть, и пускай пользователь сам разбирается - но тогда L> возникнет проблема с <img src=???>. Мы конвертируем текст, не графику... Не надо пытаться делать все на свете. Картинка кладется в каталог в том формате, в каком она шла внутри RTF-документа. Картинке присваивается соответствующие имя и расширение, которые и указываются внутри выходного файла в теге <img>. Дальше не наши проблемы. Все желающие могут самостоятельно сконвертировать картинку в любой другой формат и подправить ее имя в HTML-файле. Это легко делается в автоматическом режиме. >> Рассказывайте. Хуже точно не будет :) L> Как хотелось бы сделать: есть там такая переменная в rtf2html.cpp, L> называется std::string par_html. Вот для нее неплохо было бы сделать L> собственный класс, у которого будут функции для установки различных L> параметров текста (все эти кегли, цвета, гарнитуры...), и который бы L> теги для изменения этих параметров выдавал только тогда, когда пойдет L> реальный текст, к которому новые параметры надо применять. Я уже тоже заморачивался на тему оптимизации HTML-кода. Идеал, когда каждый блок (абзац) накапливается в памяти и выдается на выход только после полной оптимизации внутри находящегося текста. Только тогда достигается полная оптимизация. Пример: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- <p><b>text1 <i>text2 <u>text3</b> text4</i> text5</u></p> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- В Вашем случае (как я понял алгоритм) на выходе получается: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- <p><b>text1 <i>text2 <u>text3</u></i></b><i><u> text4</u></i><u> text5</u></p> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- В случае полной оптимизации абзаца должно получиться: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- <p><b>text1 <i>text2 <u>text3</u></i></b><u><i> text4</i> text5</u></p> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- L> Как, возможно, было бы совсем неплохо сделать: если документ L> достаточно большой, то различных вариантов форматирования отдельно L> взятого симсола в нем относительно немного (если его, конечно, писал L> не полный извращенец). Можно было бы не писать каждый раз для L> смены кегля и гарнитуры, к примеру, </font><font ...>, или там L> </span><span style=...>, а сразу </span><span class=...>. Для L> параграфов, опять же, <p class=...>. И запихнуть в заголовок табличку L> стилей. Это очень ценная штука. Но для нее нужно сначала реализовать оптимизацию атрибутов текста, что мы обсуждали в предыдущем абзаце. И второе - не знаю как счес, но в этом случае конвертер должен до последнего хранить документ в памяти, чтобы сформировать полностью всю таблицу стилей и уже потом выдать готовый HTML-документ на выход. >> А на счет патчевания... На SF есть возможность пользовать CVS. Очень удобная штука для >> синхронизации усилий нескольких разработчиков. L> Знаю, что есть. Проблема в том, что я на работе сижу за прокси, L> который меня к CVS точно не пустит. А дома... в общем, тоже не все так L> просто. Так что пока, наверное, стоит остаться в рамках патчей. Тем L> более, что при слиянии CVS помнится, примерно теми же diff/patch и L> пользуется :) L> Насчет CompileFarm - на ней, соответственно, протестироваться я смогу L> только тогда, когда доберусь до нормального инета, а это случается не L> так часто :( Использование возможностей SF для нас выгодно тем, что видна активность вокруг проекта. Сторонние люди могут подкинуть какие-то новые идеи, могут появиться новые разработчики... Кстати, даже наше обсуждения есть смысл перенести из почты в тамошний форум. Тем более, что письма становятся все длинее и длинее :) >> Ну вот я и буду на FreeBSD тестировать. Ибо... >> 1) у меня нет компиляторов Си под винды; >> 2) пользовать конвертер я, все равно, буду под FreeBSD. L> Насчет 1) - это не проблема :) Borland C++ 5.5 - глюкалово то еще, L> зато шаровой, качается с борландовского сайта. Я под ним виндовую L> версию и собираю. Хе-хе... А вот тут у меня проблемы - по определенным причинам нет возможности ставить на виндячий комп такие проги. Да и до юниксового сервера проще добраться - всего-то полметра от виндячего компа :) >> На FreeBSD STLport ставится в заранее определенные каталоги: /usr/local/includes и >> /usr/local/libs. Заголовки в первом находятся без проблем, а вот файл бибилотеки - нет. >> Лог в приложении. >> Кстати, при компиляции прога хочет Automake 1.8, которого нет в поставке FreeBSD. Есть >> 1.7 и 1.9, пробовал компилить с 1.9, но выскакивает ошибка. L> Хмм... Дело в том, что stlport.m4, который там используется, я взял из L> какого-то совершенно левого места. У меня он заработал. Почему не L> работает у Вас - надо смотреть в configure.log, наверное. У меня у L> самого этот проект (точнее, его версия 0.1.0) - первый опыт работы с L> aclocal/autoconf/automake, так что я не уверен, что быстро разберусь. L> Но если Вас с этим вдруг еще хуже - высылайте тт лог тоже, буду L> смотреть. Ну... Я под юникс проги еще не писал. :) Когда я писал на Си, основной операционкой был ДОС... ;) И очень удобным был Turbo C, из которого впоследствии и вырос Borland C. Потому у меня также лишь поверхностные знания даже таких программ, как make. Но, ничего, разберемся постепенно... L>>> Сделаю, это совсем не проблема. Что бы такого в <title> написать? >> Ничего. Но этот тег должен быть по стандарту. Просто сделать его пустым. L> По стандарту там еще DTD должен быть указан, насколько я помню. И кто L> его указывает? Предлагаю использовать нижеследующий шаблон. При этом, т.к. там идет XHTML, а не простой HTML, есть допольнительные требования: 1) все теги и их параметры пишутся только прописными буквами; 2) все блочные теги (<p>, <div> и т.п.) должны иметь закрывающий тег; 3) вложенность тегов должна быть корректной (т.е. вот такое недопустимо: <i><b>...</i></b>); 4) все теги, без закрывающих должны иметь "слешик" в конце тега. Пример: <img src="..." /> XHTML удобен тем, что он нормально понимается всеми браузерами (даже если не исполнять указанные требования), но при этом является, по сути, XML-документом - т.е. его нормально понимают и XML-приложения (но только при неукоснительном исполнении всех требований к стандарту). Думаю, такая гибридность может в будущем только пригодиться. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" /> <style type="text/css"> [тут стили, если нужны] </style> </head><body> [тут текст документа] </body></html> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- С уважением, Андрей. mailto:an...@se... ---------- Конец пересылаемого письма -------------------------------------------- |