Skip to content

Enhance: add text transcoding#969

Merged
SlySven merged 19 commits intoMudlet:developmentfrom
SlySven:Enhance_addTextTranscoding
May 22, 2017
Merged

Enhance: add text transcoding#969
SlySven merged 19 commits intoMudlet:developmentfrom
SlySven:Enhance_addTextTranscoding

Conversation

@SlySven
Copy link
Copy Markdown
Member

@SlySven SlySven commented Apr 27, 2017

This should start us on the road to I18n as it mean Mudlet can now at least display UTF-8 encoded MUD Server data and additionally adds support for a number of other encodings that make use of the upper character numbers as simple "Extended ASCII".

By default this will expect to be processing pure ASCII and will put in a "replacement character" for any byte with it's most significant bit set for those that makes it's way through the Telnet protocol decoding to head towards the screen.

This might help with #505 and #702 and another Issue that I cannot find that wanted "unprintable" characters to be marked on the screen...

The selected text encoding (controllable both via a saved per profile setting AND lua commands) is also used for outgoing text data - though the behaviour should the wanted outgoing text contain characters that cannot be encoded in the selected manner might not be exactly clear at the moment.

Note that text that contains non-ASCII characters cannot yet be detected by the trigger system as that needs a good going over.

SlySven added 2 commits April 27, 2017 05:20
Found during testing on the Spanish Realms of Legends MUD that we did not
support ISO-8859-1 (Latin-1) encoding but could if we made a small change
to the way we process the incoming text bytes in the
TBuffer::translateToPlainText(...) method.  Instead of appending each byte
as a char onto TBuffer::mMudline - which works for (7-bit) ASCII characters
we can convert the upper 128 code characters to the "correct" QChars by
going via a QChar::fromLatin1(...) intermediate step.

It was then found possible to extend this process for other simple encoding
tables by recording the differences between the ISO 8859-1 and various
other encodings.  Included in this commit is support for:
* ISO 8859-1
* ISO 8859-2
* ISO 8859-3
* ISO 8859-4
* ISO 8859-10
* ISO 8859-15
* ISO 8859-16
* WINDOWS-1250
* WINDOWS-1251
* WINDOWS-1252

The above (and UTF-8) can be selected from the profile preferences and will
be saved on a per profile basis once set and used when the profile is used
again. UTF-8 is manually decoded by examining the first byte to determine
how many more bytes are expected for it and then checking all of the
indicated bytes for validity.  Checks are included to guard against invalid
code points (beyond U+10FFFF) and "overlong" sequences.  During testing
against some data from a real MUD it was found that the UTF-8 BOM sequence
although not required or recommended for this encoding was being converted
to no QChars at all, technically the position in a stream where it occurs
could replace it with some form of joiner or it could actually be discarded
however a script or trigger might be interested in it so the equivalent
QChar is manually reinserted into the decoded stream - this is also useful
as the code structure wants to insert a TChar instance into the
corresponding data storage every time around the parsing loop for a single
byte (for all but UTF-8) encoding or Utf-8 byte sequence for a codepoint
(for UTF-8).

NOTE THAT THE DECODER WILL HANDLE NON-BMP BYTE SEQUENCES AND DECODES THEM
TO TWO QChars (a High surrogate followed by a Low one) AS QT DOES (It is
based on QStrings that are Utf-16). To allow code that follows this stage
to keep a one-to-one match between QChars in the text data and TChars that
record the rendering aspects (colour, font styling) a duplicate TChar is
added after the normal one for non-BMP codepoints.  I feel this will help
to port the existing code over to support such non-BMP codepoints...!

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
Found missing braces was allowing some code to execute when the item it
was trying to reference did not exist.

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
@SlySven SlySven added this to the 3.1 milestone Apr 27, 2017
@SlySven SlySven self-assigned this Apr 27, 2017
@SlySven SlySven requested review from ahmedcharles and vadi2 April 27, 2017 04:47
@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 27, 2017

Something broke on encoding for me, but just once... when I turned on replay logging and read through the help file again, it was fine.

Broken - boxes and Asian characters are obviously not part of Cyrillic:

25H 84M 2499о Зауч:0 Вых:СВЮЗ> СПРАВКА НОВИЧОК
НОВИЧОК НОВИЧКУ НЬЮБ NEWBIE
+------------------------------------------------------------------------------+
| Приветствуем Вас в сказочной стране, построенной на основе русских былин и   |
| взявшей лучшее из того, что существует в сотнях других МПМ. Для игры нужен   |
| MUD-клиент. Другими словами, для того, чтобы отдавать игре команды, вам      |
| необходима специальная программка. Теоретически можно играть с помощью       |
| программы Telnet, который входит в стандартную поставку Windows, но крайне   |
| рекомендуем этого не делать. Если сравнивать Telnet с ниже перечисленными    |
| программами, на ум приходит аналогия Lexicon - Word. Наиболее популярными    |
| клиентами являются JMC, MMC и ZMUD.                                          |
+------------------------------------------------------------------------------+
| Если Вы скачали себе JMC, после запуска наберите "#connect bylins.su 4000".  |
| Чтобы каждый раз не набирать эту строку, рекомендуем назначить клавишу       |
| (Options->Hotkeys). После заставки Вам будет предложен выбор кодировки, а    |
| затем предложение ввести имя Вашего героя. Выбирайте имя (желательно         |
| соответствующее древней Руси) и далее следуйте подсказкам сервера.           |
| Главное ничего не пугаться, ведь Вы ничего не сломаете... (думается).        |
+------------------------------------------------------------------------------+
| На Вашем пути встретятся не только компьютерные персонажи (так называемые    |
| мобы), но и персонажи, управляемые другими людьми. Если Вы ранее не играли в |
| подобные игры (ролевые игры с компьютером не в счет), рекомендуем выбирать   |
| профессию Богатырь. Он имеет обычно большое количество очков жизни (хитов),  |
| что позволяет￑убежать￐из￑сражения￐без￐печальных￐последствий ￐а￑так￐же￐большую
| ￑силу ￐позволяющую￐на￐начальных￑уровнях￐играть￐одному ￐В￐дальнейшем ￐после   |
| ￐периода￐акклиматизации ￐вы￑сможете￑сделать￑себе￐кого￐захотите               |
+------------------------------------------------------------------------------+
| ￐После￑создания￐персонажа￐Вы￐оказываетесь￐в￐гостинице ￐где￐будете￑уходить￐на |
| ￐постой ￐То￐есть ￐записывать￑своего￐игрока ￑чтоб￐он￐не￐валялся￐бесхозно ￐А￑то|
| ￐злые ￐дядьки￐могут￑с￐ним￑что￐нибудь￐нехорошее￑сотворить ￐В￑строке￐ввода     |
| ￑указано￐количество￐жизни ￐количество￑ходов ￑сколько￑у￐Вас￐монет￐на￑руках￐и  |

￐Листать: <RETURN>, Q<￐К￐онец R<￐П￐овтор B<￐Н￐азад ￐или￐номер￑страницы(1/7).
| возможные выходы. Передвижение по миру осуществляется командами (без кавычек)|
| "север", "юг", "запад", "восток", "вверх", "вниз". Также возможно вводить не |
| полное слово, а только его начало: с, ю, в, з, вв, вн.                       |
+------------------------------------------------------------------------------+
| Для  отображения сообщений цветом введите команду "режим цвет полный". Чтобы |
| посмотреть, что на Вас надето используйте команду "экипировка" сокр. "э".    |
| Для осмотра вещей, которые Вы несете - команда "инвентарь" сокр. "ин".       |
| Хорошие вещи - одна из самых больших ценностей в игре. Но поначалу Вы можете |
| не беспокоится - хорошие к Вам с неба не упадут.                             |
+------------------------------------------------------------------------------+
| С другими игроками можно общаться командой "говорить <фраза>". Например,     |
| набрав "г привет!" все, кто находятся с Вами в одной комнате увидят, что вы  |
| сказали привет! Можно обратиться непосредственно к игроку командой "сказать".|
| Например, "ск кагор как дела". После этого, если персонаж Кагор в данное     |
| время находится в игре и видим для Вас, он увидит фразу "как дела". Кто      |
| сейчас играет можно узнать по команде "кто". Ну, тут можно сказать, что      |
| общаться Вы уже научились. Ведь, как говорит пословица: "Язык до Киева       |
| доведет".                                                                    |
+------------------------------------------------------------------------------+
| Прежде,  чем  выйдете  из  гостиницы,  установите режим трусости "трус 8".   |
| Тогда Вы будете убегать из боя, если уровень жизни станет меньше 8. Первым   |
| делом вам необходимо набрать 1-2 уровня (всего их 30). Для этого походите по |
| городу и найдите  мышь или паука. Это компьютерные игроки и вашему Богатырю  |
| не составит труда их убить. Если Вы послушали совет насчет цветов, то все    |
| живые существа будут выделяться кроваво-красным цветом, для упрощения их     |
| обнаружения и дальнейшего полного уничтожения. Нападайте на них командой     |
| "убить мышь" (убить паук) или  сокр. "у мыш", "у пау". При этом посмотрите,  |
| чтобы в комнате с вами никого не было, возможно кому-то из городских жителей |
| не понравится, что вы сражаетесь в городе и вступятся за мышь. Ну, вдруг     |
| попадутся активисты ГринПиса или страшно сердобольная крестьянка пожалеет    |

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (2/7).
| маленькую мышку. Если все же кто-то зашел в комнату и вступился, убегайте    |
| (команда "бежать" сокр. "б"), Вам еще рано вступать в бой с более сильным    |
| противником. Запросто могут и вставить за мышь. Советуем не применять        |
| сокращений при указании цели, например Вы наберете "у м" (что трактуется     |
| "убить мышь"). Но если в это время с вами в комнате стоял моб по имени       |
| Мордоворот, то есть достаточно высокая вероятность, что Вы начнете драться   |
| не с маленькой серой мышкой, а с более опытным противником, что для Вас      |
| естественно кончится печально, если только Вы не успеете нажать кнопочку "б" |
| см. выше.                                                                    |
+------------------------------------------------------------------------------+
| Итак, первый  бой проведен, и Вы обратили внимание, что часто промахиваетесь.|
| Это поправимо и вполне естественно. В дальнейшем в результате тренировок Вы  |
| будете все более совершенно владеть умениями. То есть от долгой практики     |
| махания мечом махать им Вы будете намного лучше. Каждая строчка, выделяемая  |
| голубым цветом, будет вызывать у Вас обоснованное чувство восторга и слезы   |
| радости за своего персонажа. Пока у Вас из умений только "атака левой рукой",|
| проверяемое командой "умения" сокр. "ум". Походите по деревне, почитайте     |
| внимательно описания, увидев компьютерных игроков наберите рядом с ними      |
| команду "учить". Конечно, не надо пробовать эту команду на мышах, лошадях и  |
| других неразумных зверюшках. Если ваша профессия совпадает с профессией      |
| моба, то он вам сообщит, чему Вас научит. Например, Вам скажут, что смогут   |
| научить "кулачному бою", наберите на клавиатуре "учить кулач", и проверьте   |
| командой "умен" количество ваших умений. Сразу хотим дать Вам совет, не учите|
| все подряд, выбирайте только то, что Вам будет нужно в данный момент. Пока   |
| Вы не экипированы, то есть почти голые, выучите умение "кулачного боя" и     |
**| "удар левой рукой". Богатырь, в силу своейチспецифики￐ᄏлучшеᄇвсегоᄡдерется  |
| ￐ᄈголымиタрукамиᄌиナхужеᄇвсего￐ᄎкороткимиᄏлезвиями ￐ᄀСпрашивайтеチсоветаテуチсоседей| 
￐ᄌиᄡдрузей￐ᄆбудьтеᄇвежливыᄌиメВам﾿помогут￐ンНикогдаᄑнеチстоитᄎкачать﾿права      |
| ￑タругатьсяᄌиᄎканючить￐ンНекоторымᄏлюдямヘэтоチсовсемᄑнеᄑнравится￐ミАヘэтоᄐможет   |
| ￐ᄡдляメВас﾿плохоᄎкончиться￐ヤДалее￑チсᄑнаборомテуровнейᄆбудет﾿появляться         |

￐ロЛистать <RETURN>, Q<￐レКᄒонецR<￐゚ПᄒовторB<￐ンНᄚазад￐ᄌилиᄑномерチстраницы3/7).**
| возможность тренироваться в других умениях.                                  |
+------------------------------------------------------------------------------+
| После  расправы над несколькими мышами Вы поймете, что заблудились :). И я   |
| рекомендую Вам нарисовать карту города, что очень скоро пригодится. Особое   |
| внимание обратите на колодец и магазины. Вы можете напиться воды из колодца  |
| (команда  "пить колодец" сокр. "пит кол"), а также наполнить флягу из него   |
| (команда "наполнить фляга колодец" сокр. "нап фл кол").                      |
+------------------------------------------------------------------------------+
| Зайдя  в  магазин, Вы можете посмотреть, что там продается командой "список" |
| сокр. "спи". Отмечайте на карте, где еда, а где одежда. Пока у Вас денег нет,|
| но Вы их скоро заработаете. Если не рисовать карту, это натренирует вашу     |
| память и наблюдательность, но сначала заставит Вас провести несколько        |
| неприятных минут, когда Вы будете бегать с криками: "А где же тут все?", и   |
| "А я здесь уже был!".                                                        |
+------------------------------------------------------------------------------+
| Для зарабатывания денег надо трупы убитых вами животных приносить к скорняку |
| Чем меньше ваши уровень и ваша сила, тем меньше трупов можно одновременно    |
| поднять. Позже деньги будут браться из трупов убитых мобов. Выходите из      |
| деревни и пробуйте свои силы. Приблизительно уровень моба можно узнать       |
| командой "сравнить <имя моба>". Но это ОЧЕНЬ приблизительная оценка, так как |
| не учитывается сила моба и его уровень владения умениями. Если Вам говорят,  |
| что это равный бой, то вы сильно рискуете. Если Вас убили, Вы теряете все    |
| вещи и часть опыта, можете даже уровень. Если Вас убил моб, быстро вступайте |
| в игру и бегите за вещами со своего трупа, пока не забрал кто-то другой      |
| (команда "взять все труп"). Главное в таких случаях - не впадать в отчаяние, |
| ведь все только начинается. Я, например, не знаю ни одного человека, который |
| бы за свою долгую игровую карьеру ни разу не умер.                           |
+------------------------------------------------------------------------------+
| После боя необходимо восстановить единицы жизни. Они быстрее восстановятся,  |
| если ваш герой присел отдохнуть или поспать. Ни в коем случае￐не￑спите￐в    |

￐Листать: <RETURN>, Q<￐К￐онец R<￐П￐овтор B<￐Н￐азад ￐или￐номер￑страницы(4/7).
| комнатах, где на Вас могут напасть. Спите только в мирных комнатах, одна из  |
| них у постоя.                                                                |
+------------------------------------------------------------------------------+
| Вы можете объединится в группу с другими игроками. Группа позволяет быстрее  |
| набирать уровни, зарабатывать деньги, а главное найти себе друзей, которые   |
| всегда помогут. В группе всегда имеется лидер. Обычно это человек, который   |
| хорошо знает зоны. Если Вы договорились, что кто-то возьмет Вас в группу     |
| набирайте команду "следовать <имя>". Не рассчитывайте, что Вас возьмет первый|
| встречный. Для того, чтобы найти группу по интересам (то есть с примерно     |
| равными уровнями +-5) Вам придется как следует поорать, команда "орать".     |
| Орать можно много всего, но когда ищется группа ор следующий: "Богатырь (или |
| какая там ваша профессия) такого-то уровня хочет вступить в группу". Если    |
| вас сразу не завалят предложениями - не беда. Через несколько минут поорите  |
| еще. В конце концов Вас или вежливо попросят: "ЗАТКНИСЬ!! Надоел уже!", или  |
| предложат присоединиться к какой-нибудь группе или человеку. После того, как |
| лидер наберет команду "гр все", Вам будет сообщено о вступлении в группу.    |
| Команды в группе: "гг <текст>" - ваше сообщение увидят все члены группы      |
| "доложить" - вы сообщите группе ваше количество жизни и количество ходов,    |
| сокращенно "дол"; "гр" - сообщение, кто в группе и их состояние. "разделить  |
| <кол-во> монет" - будут разделены монеты между всеми членами группы. Обычно  |
| в группе выбирается "танк", который всегда будет принимать первый удар на    |
| себя. Танк должен подчиняться приказу лидера группы и первым заходить в      |
| комнату с агрессивными мобами. Подбирать монеты с трупов должен лидер, или   |
| кто-то по согласованию группы. Если Вы хватаете все без разрешения, то самое |
| маленькое - Вас исключат из группы, и Вы будете пробираться по незнакомой    |
| местности в поисках дороги в деревню.                                        |
| Слушайтесь лидера во всем, не проявляйте инициативу, никогда не садитесь     |
| отдыхать без команды лидера, если у Вас кончаются очки бодрости, сообщите    |
| это группе командой "дол".                                                   |
+------------------------------------------------------------------------------+

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (5/7).
| Когда у Вас собралась сумма монет, которая Вам в данный момент не нужна,     |
| отнесите и сдайте ее в лежню (команды "вложить", "получить", "баланс").      |
| В случае вашей смерти Вы всегда можете снять ваши монеты на начальную        |
| экипировку и еду.                                                            |
+------------------------------------------------------------------------------+
| Если у Вас возникли вопросы, обращайтесь к справке. Команда "справка" или    |
| "справка <умение>". В случае, если справки по данной теме нет, попробуйте    |
| обратиться к другим игрокам. Если они не заняты, Вам помогут. К богам        |
| обращайтесь только по серьезным вопросам.                                    |
+------------------------------------------------------------------------------+
| Пробуйте и экспериментируйте, в игре много возможностей, будьте вежливы и    |
| любознательны, и через некоторое время Вы будете жить в игре: ненавидеть     |
| злых мобов, точнее знать насколько они опасны и чего хорошего остается в них |
| после смерти, уважать друзей, уметь мгновенно выбирать лучшее игровое        |
| решение, то есть умело пользоваться свитками возврата и быстро находить на   |
| клавиатуре великую кнопку "б" и многое другое. Текстовые компьютерные игры   |
| отличаются от графических как небо от земли. Там даже свои эмоции нельзя     |
| никак выразить. А тут - кто-нибудь сказал тебе что-нибудь нехорошее, а ты на |
| него без слов страшную морду скорчил, да еще и зарычал. Самые уверенные в    |
| себе игроки могут даже плюнуть в обидчика. Глядишь, он тебя зауважает и      |
| разговор завяжется. Короче, ни пуха тебе, ни пера. Если из всего выше        |
| сказанного ты понял немного, или совсем ничего - не печалься. На твоем месте |
| я бы тоже ничего не понял. Только войди в игру, а дальше всегда найдутся     |
| хорошие люди, которые помогут и объяснят. Мы все надеемся, что ты скоро      |
| станешь истинным ценителем таких игр. А чтобы ты не бегал, как многие, по    |
| разным MUD'ам и не искал лучший, я советую тебе начать с этого. Скорее всего,|
| тебе уже и не захочется искать ничего другого.                               |
+------------------------------------------------------------------------------+
| До встречи на гостеприимных землях Древней Руси!                             |
+------------------------------------------------------------------------------+

Not changing anything and just reading the help file again was fine, so it was a transient error...

25H 84M 2499о Зауч:0 Вых:СВЮЗ> СПРАВКА НОВИЧОК
НОВИЧОК НОВИЧКУ НЬЮБ NEWBIE
+------------------------------------------------------------------------------+
| Приветствуем Вас в сказочной стране, построенной на основе русских былин и   |
| взявшей лучшее из того, что существует в сотнях других МПМ. Для игры нужен   |
| MUD-клиент. Другими словами, для того, чтобы отдавать игре команды, вам      |
| необходима специальная программка. Теоретически можно играть с помощью       |
| программы Telnet, который входит в стандартную поставку Windows, но крайне   |
| рекомендуем этого не делать. Если сравнивать Telnet с ниже перечисленными    |
| программами, на ум приходит аналогия Lexicon - Word. Наиболее популярными    |
| клиентами являются JMC, MMC и ZMUD.                                          |
+------------------------------------------------------------------------------+
| Если Вы скачали себе JMC, после запуска наберите "#connect bylins.su 4000".  |
| Чтобы каждый раз не набирать эту строку, рекомендуем назначить клавишу       |
| (Options->Hotkeys). После заставки Вам будет предложен выбор кодировки, а    |
| затем предложение ввести имя Вашего героя. Выбирайте имя (желательно         |
| соответствующее древней Руси) и далее следуйте подсказкам сервера.           |
| Главное ничего не пугаться, ведь Вы ничего не сломаете... (думается).        |
+------------------------------------------------------------------------------+
| На Вашем пути встретятся не только компьютерные персонажи (так называемые    |
| мобы), но и персонажи, управляемые другими людьми. Если Вы ранее не играли в |
| подобные игры (ролевые игры с компьютером не в счет), рекомендуем выбирать   |
| профессию Богатырь. Он имеет обычно большое количество очков жизни (хитов),  |
| что позволяет убежать из сражения без печальных последствий, а так же большую|
| силу, позволяющую на начальных уровнях играть одному. В дальнейшем, после    |
| периода акклиматизации, вы сможете сделать себе кого захотите.               |
+------------------------------------------------------------------------------+
| После создания персонажа Вы оказываетесь в гостинице, где будете уходить на  |
| постой. То есть, записывать своего игрока, чтоб он не валялся бесхозно. А то |
| злые  дядьки могут с ним что-нибудь нехорошее сотворить. В строке ввода      |
| указано количество жизни, количество ходов, сколько у Вас монет на руках и   |

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (1/7).
| возможные выходы. Передвижение по миру осуществляется командами (без кавычек)|
| "север", "юг", "запад", "восток", "вверх", "вниз". Также возможно вводить не |
| полное слово, а только его начало: с, ю, в, з, вв, вн.                       |
+------------------------------------------------------------------------------+
| Для  отображения сообщений цветом введите команду "режим цвет полный". Чтобы |
| посмотреть, что на Вас надето используйте команду "экипировка" сокр. "э".    |
| Для осмотра вещей, которые Вы несете - команда "инвентарь" сокр. "ин".       |
| Хорошие вещи - одна из самых больших ценностей в игре. Но поначалу Вы можете |
| не беспокоится - хорошие к Вам с неба не упадут.                             |
+------------------------------------------------------------------------------+
| С другими игроками можно общаться командой "говорить <фраза>". Например,     |
| набрав "г привет!" все, кто находятся с Вами в одной комнате увидят, что вы  |
| сказали привет! Можно обратиться непосредственно к игроку командой "сказать".|
| Например, "ск кагор как дела". После этого, если персонаж Кагор в данное     |
| время находится в игре и видим для Вас, он увидит фразу "как дела". Кто      |
| сейчас играет можно узнать по команде "кто". Ну, тут можно сказать, что      |
| общаться Вы уже научились. Ведь, как говорит пословица: "Язык до Киева       |
| доведет".                                                                    |
+------------------------------------------------------------------------------+
| Прежде,  чем  выйдете  из  гостиницы,  установите режим трусости "трус 8".   |
| Тогда Вы будете убегать из боя, если уровень жизни станет меньше 8. Первым   |
| делом вам необходимо набрать 1-2 уровня (всего их 30). Для этого походите по |
| городу и найдите  мышь или паука. Это компьютерные игроки и вашему Богатырю  |
| не составит труда их убить. Если Вы послушали совет насчет цветов, то все    |
| живые существа будут выделяться кроваво-красным цветом, для упрощения их     |
| обнаружения и дальнейшего полного уничтожения. Нападайте на них командой     |
| "убить мышь" (убить паук) или  сокр. "у мыш", "у пау". При этом посмотрите,  |
| чтобы в комнате с вами никого не было, возможно кому-то из городских жителей |
| не понравится, что вы сражаетесь в городе и вступятся за мышь. Ну, вдруг     |
| попадутся активисты ГринПиса или страшно сердобольная крестьянка пожалеет    |

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (2/7).
| маленькую мышку. Если все же кто-то зашел в комнату и вступился, убегайте    |
| (команда "бежать" сокр. "б"), Вам еще рано вступать в бой с более сильным    |
| противником. Запросто могут и вставить за мышь. Советуем не применять        |
| сокращений при указании цели, например Вы наберете "у м" (что трактуется     |
| "убить мышь"). Но если в это время с вами в комнате стоял моб по имени       |
| Мордоворот, то есть достаточно высокая вероятность, что Вы начнете драться   |
| не с маленькой серой мышкой, а с более опытным противником, что для Вас      |
| естественно кончится печально, если только Вы не успеете нажать кнопочку "б" |
| см. выше.                                                                    |
+------------------------------------------------------------------------------+
| Итак, первый  бой проведен, и Вы обратили внимание, что часто промахиваетесь.|
| Это поправимо и вполне естественно. В дальнейшем в результате тренировок Вы  |
| будете все более совершенно владеть умениями. То есть от долгой практики     |
| махания мечом махать им Вы будете намного лучше. Каждая строчка, выделяемая  |
| голубым цветом, будет вызывать у Вас обоснованное чувство восторга и слезы   |
| радости за своего персонажа. Пока у Вас из умений только "атака левой рукой",|
| проверяемое командой "умения" сокр. "ум". Походите по деревне, почитайте     |
| внимательно описания, увидев компьютерных игроков наберите рядом с ними      |
| команду "учить". Конечно, не надо пробовать эту команду на мышах, лошадях и  |
| других неразумных зверюшках. Если ваша профессия совпадает с профессией      |
| моба, то он вам сообщит, чему Вас научит. Например, Вам скажут, что смогут   |
| научить "кулачному бою", наберите на клавиатуре "учить кулач", и проверьте   |
| командой "умен" количество ваших умений. Сразу хотим дать Вам совет, не учите|
| все подряд, выбирайте только то, что Вам будет нужно в данный момент. Пока   |
| Вы не экипированы, то есть почти голые, выучите умение "кулачного боя" и     |
| "удар левой рукой". Богатырь, в силу своей специфики, лучше всего дерется    |
| голыми руками и хуже всего "короткими лезвиями". Спрашивайте совета у соседей|
| и друзей, будьте вежливы и Вам помогут. Никогда не стоит качать права,       |
| ругаться и канючить. Некоторым людям это совсем не нравится. А это может     |
| для Вас плохо кончиться. Далее, с набором уровней будет появляться           |

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (3/7).
| возможность тренироваться в других умениях.                                  |
+------------------------------------------------------------------------------+
| После  расправы над несколькими мышами Вы поймете, что заблудились :). И я   |
| рекомендую Вам нарисовать карту города, что очень скоро пригодится. Особое   |
| внимание обратите на колодец и магазины. Вы можете напиться воды из колодца  |
| (команда  "пить колодец" сокр. "пит кол"), а также наполнить флягу из него   |
| (команда "наполнить фляга колодец" сокр. "нап фл кол").                      |
+------------------------------------------------------------------------------+
| Зайдя  в  магазин, Вы можете посмотреть, что там продается командой "список" |
| сокр. "спи". Отмечайте на карте, где еда, а где одежда. Пока у Вас денег нет,|
| но Вы их скоро заработаете. Если не рисовать карту, это натренирует вашу     |
| память и наблюдательность, но сначала заставит Вас провести несколько        |
| неприятных минут, когда Вы будете бегать с криками: "А где же тут все?", и   |
| "А я здесь уже был!".                                                        |
+------------------------------------------------------------------------------+
| Для зарабатывания денег надо трупы убитых вами животных приносить к скорняку |
| Чем меньше ваши уровень и ваша сила, тем меньше трупов можно одновременно    |
| поднять. Позже деньги будут браться из трупов убитых мобов. Выходите из      |
| деревни и пробуйте свои силы. Приблизительно уровень моба можно узнать       |
| командой "сравнить <имя моба>". Но это ОЧЕНЬ приблизительная оценка, так как |
| не учитывается сила моба и его уровень владения умениями. Если Вам говорят,  |
| что это равный бой, то вы сильно рискуете. Если Вас убили, Вы теряете все    |
| вещи и часть опыта, можете даже уровень. Если Вас убил моб, быстро вступайте |
| в игру и бегите за вещами со своего трупа, пока не забрал кто-то другой      |
| (команда "взять все труп"). Главное в таких случаях - не впадать в отчаяние, |
| ведь все только начинается. Я, например, не знаю ни одного человека, который |
| бы за свою долгую игровую карьеру ни разу не умер.                           |
+------------------------------------------------------------------------------+
| После боя необходимо восстановить единицы жизни. Они быстрее восстановятся,  |
| если ваш герой присел отдохнуть или поспать. Ни в коем случае не спите в     |

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (4/7).
| комнатах, где на Вас могут напасть. Спите только в мирных комнатах, одна из  |
| них у постоя.                                                                |
+------------------------------------------------------------------------------+
| Вы можете объединится в группу с другими игроками. Группа позволяет быстрее  |
| набирать уровни, зарабатывать деньги, а главное найти себе друзей, которые   |
| всегда помогут. В группе всегда имеется лидер. Обычно это человек, который   |
| хорошо знает зоны. Если Вы договорились, что кто-то возьмет Вас в группу     |
| набирайте команду "следовать <имя>". Не рассчитывайте, что Вас возьмет первый|
| встречный. Для того, чтобы найти группу по интересам (то есть с примерно     |
| равными уровнями +-5) Вам придется как следует поорать, команда "орать".     |
| Орать можно много всего, но когда ищется группа ор следующий: "Богатырь (или |
| какая там ваша профессия) такого-то уровня хочет вступить в группу". Если    |
| вас сразу не завалят предложениями - не беда. Через несколько минут поорите  |
| еще. В конце концов Вас или вежливо попросят: "ЗАТКНИСЬ!! Надоел уже!", или  |
| предложат присоединиться к какой-нибудь группе или человеку. После того, как |
| лидер наберет команду "гр все", Вам будет сообщено о вступлении в группу.    |
| Команды в группе: "гг <текст>" - ваше сообщение увидят все члены группы      |
| "доложить" - вы сообщите группе ваше количество жизни и количество ходов,    |
| сокращенно "дол"; "гр" - сообщение, кто в группе и их состояние. "разделить  |
| <кол-во> монет" - будут разделены монеты между всеми членами группы. Обычно  |
| в группе выбирается "танк", который всегда будет принимать первый удар на    |
| себя. Танк должен подчиняться приказу лидера группы и первым заходить в      |
| комнату с агрессивными мобами. Подбирать монеты с трупов должен лидер, или   |
| кто-то по согласованию группы. Если Вы хватаете все без разрешения, то самое |
| маленькое - Вас исключат из группы, и Вы будете пробираться по незнакомой    |
| местности в поисках дороги в деревню.                                        |
| Слушайтесь лидера во всем, не проявляйте инициативу, никогда не садитесь     |
| отдыхать без команды лидера, если у Вас кончаются очки бодрости, сообщите    |
| это группе командой "дол".                                                   |
+------------------------------------------------------------------------------+

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (5/7).
| Когда у Вас собралась сумма монет, которая Вам в данный момент не нужна,     |
| отнесите и сдайте ее в лежню (команды "вложить", "получить", "баланс").      |
| В случае вашей смерти Вы всегда можете снять ваши монеты на начальную        |
| экипировку и еду.                                                            |
+------------------------------------------------------------------------------+
| Если у Вас возникли вопросы, обращайтесь к справке. Команда "справка" или    |
| "справка <умение>". В случае, если справки по данной теме нет, попробуйте    |
| обратиться к другим игрокам. Если они не заняты, Вам помогут. К богам        |
| обращайтесь только по серьезным вопросам.                                    |
+------------------------------------------------------------------------------+
| Пробуйте и экспериментируйте, в игре много возможностей, будьте вежливы и    |
| любознательны, и через некоторое время Вы будете жить в игре: ненавидеть     |
| злых мобов, точнее знать насколько они опасны и чего хорошего остается в них |
| после смерти, уважать друзей, уметь мгновенно выбирать лучшее игровое        |
| решение, то есть умело пользоваться свитками возврата и быстро находить на   |
| клавиатуре великую кнопку "б" и многое другое. Текстовые компьютерные игры   |
| отличаются от графических как небо от земли. Там даже свои эмоции нельзя     |
| никак выразить. А тут - кто-нибудь сказал тебе что-нибудь нехорошее, а ты на |
| него без слов страшную морду скорчил, да еще и зарычал. Самые уверенные в    |
| себе игроки могут даже плюнуть в обидчика. Глядишь, он тебя зауважает и      |
| разговор завяжется. Короче, ни пуха тебе, ни пера. Если из всего выше        |
| сказанного ты понял немного, или совсем ничего - не печалься. На твоем месте |
| я бы тоже ничего не понял. Только войди в игру, а дальше всегда найдутся     |
| хорошие люди, которые помогут и объяснят. Мы все надеемся, что ты скоро      |
| станешь истинным ценителем таких игр. А чтобы ты не бегал, как многие, по    |
| разным MUD'ам и не искал лучший, я советую тебе начать с этого. Скорее всего,|
| тебе уже и не захочется искать ничего другого.                               |
+------------------------------------------------------------------------------+
| До встречи на гостеприимных землях Древней Руси!                             |
+------------------------------------------------------------------------------+

Листать : <RETURN>, Q<К>онец, R<П>овтор, B<Н>азад, или номер страницы (6/7).

Didn't have replay logging going at the time, so it's just something we'll have to watch out for.

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 27, 2017

Managed to get the corruption recorded: 27-04-2017#18-31-03.dat.zip

Copy link
Copy Markdown
Member

@vadi2 vadi2 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It works! I'll help you with the tooltip and will do more testing on this...

src/ctelnet.cpp Outdated
// Report on main console the change in ALL cases, as this can change
// things for the user (e.g. theoretically what characters are
// acceptable to the MUD Server).
QString message = tr("[ ALERT ] - Encoding/decoding of MUD Server traffic set to: \"%1\"...")
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ellipsis is used to indicate there is more that more needs to happen before the action is complete, which isn't the case here.

How about this simpler text: Game text encoding/decoding set to \"%1\". ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might have to clarify that this applies to text to and from the MUD server {and to feedTriggers(...) although the latter is not protected against Utf-8 byte sequences being split but than it doesn't need it}. Might "Game text" be too ambiguous?

In hindsight - agree about "..." not being appropriate.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need that clarification - it's an option the users set and they expect everything to just "work", so no need to spell out that everything.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, what if we use transcoding to mean encoding/decoding? That's more appropriate and less wordy.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well to my ears "transcoding" seems to be like "transforming" one code into another, which is what is happening I suppose; but separating it into encoding / decoding helps to emphasis that two separate operations are happening on traffic (i.e. data) flowing in two separate directions.

Of course, we perhaps do not want to be too specific if someone asks "Well what is it being transformed into here in Mudlet" as that might not be so easy to say. 😜

<bool>true</bool>
</property>
<property name="title">
<string>Character Encoding</string>
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be Character encoding, but how about Text encoding for something less technical? Not that encoding isn't - but there's no way around that.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was just using the text from the old code that I pulled out with git! 😀

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would Data encoding be a reasonable compromise - it implies something a "bit" technical and not something to be messed with causally - and given that Mudlet is all about responding to and handling text the word "Text" seems a bit too general here?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll think on it.

Btw another reason to move off "Character encoding" is to a clueless person, a character in a MUD is the little guy they're playing.

src/TBuffer.cpp Outdated
void TBuffer::translateToPlainText( std::string & s, const bool isFromServer )
{
//cout << "TRANSLATE<"<<s<<">"<<endl;
std::string localBuffer; // As well as enabling the prepending of left-over
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not a comment above the text - it'll take up less lines and be more clang-format friendly.

src/TBuffer.cpp Outdated
else if (mpHost->mTelnet.getEncoding() == QLatin1String("WINDOWS-1252")) {
mMudLine.append(QString(decodeByteToWindows_1252(ch)));
}
else if (mpHost->mTelnet.getEncoding() == QLatin1String("UTF-8")) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is over my head and I won't catch up on this in time next release so leaving to @ahmedcharles to verify.

src/TBuffer.cpp Outdated
switch( utf8SequenceLength ) {
case 4:
if ((localBuffer[msPos+3] & 0xC0) != 0x80) {
qDebug() << "TBuffer::translateToPlainText(...) byte 4 in sequence as UTF-8 rejected!";
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a little cryptic.

Copy link
Copy Markdown
Member Author

@SlySven SlySven Apr 27, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As we work out the sequence length by examining the first byte this is pointing out that the fourth byte does not meet with the expectation that the high bits are not 10.... as the encoding demands.

Edited to correct logic error!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh. I thought it literally said 4. The error message still is not very useful: it does not say what the byte was or why was it rejected. How about "4th byte in UTF-8 sequence is invalid"

newEncoding = QString::fromUtf8(lua_tostring(L,1));
}

QPair<bool, QString> results = pHost->mTelnet.setEncoding(newEncoding);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This errors if you try calling with an encoding that's already set. That shouldn't be an error.

setServerEncoding: bad argument #1 value (no change to encoding, it already was: "UTF-8"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure there is a black and white answer to this. Given that you can determine the current encoding changing it unnecessarily might have an impact on the saved state of the outgoing encoder. so the code takes care to only make a change if it is one.

Using a command and it does not have any effect could be regarded as a run-time issue in some points of view so I felt it was safest to reserve "true" for "this command succeeded in setting the encoding to the given value"...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code taking care to only change it if it needs changing is good. Forcing the user to check what it is before allowing them to change it is unnecessary. With that philosophy, you could redo the whole of Mudlets API design to error if the function doesn't produce any changes...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, without the success message is it an issue that then there would not be clarity whether anything happened or not as a result of the command. Perhaps not, then, perhaps the user will be concerned with now and not what happened before, and of course if they WERE concerned they'd check it themselves so - OK - will change this.


if(results.first) {
lua_pushboolean(L, true);
lua_pushfstring(L, "setServerEncoding: success %s!",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for the string... the code will know what encoding it's setting to.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless it uses the empty string - but that is mapped to "ASCII" anyhow - so yeah that could go.

💭 Am I going to have to code a sysServerEncodingChange event?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about sysServerEncodingChange yet. Let's leave it be for now.

return 0;
}

int TLuaInterpreter::setServerEncoding(lua_State * L)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why server - might as well be getEncoding and setEncoding, it's not like we'll have a client encoding - that's bundled in the same setting.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May be an issue when we allow the GUI to be language dependent - wanted to keep the two things clearly separate. Also, at least keyboards could have encodings and the term encoding might be used in other contexts e.g. cryptography by tying it to server I hope to avoid later confusions.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, that is fine then.

return 2;
}

int TLuaInterpreter::getServerEncoding(lua_State * L)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need a function to get the list of available encodings as well. I think it should be an encoding = true map so people can easily check if a certain encoding is available on users Mudlet - @keneanung thoughts on indexed vs map?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well the error case (for an invalid string) reports the valid ones...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's good - but that's not how you should be checking for the valid ones.

<bool>true</bool>
</property>
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;The way in which data is sent to and received from the MUD Server can vary in different parts of the World and usually has a relation to the language used by players on it. Whilst ASCII is the original form that the underlying Telnet protocol once used it (strictly speaking) only uses 7-bits and only supports 128 character codes (and a quarter of them are reserved for control purposes) so when it became possible to use all 8-bits in a byte various different encoding were developed. Most of these use the upper 128 character codes for extra characters needed for specific languages but which means that it is necessary to use the right encoding to get the right symbols for a particular language. This is the case for the &lt;b&gt;ISO 8859-*&lt;/b&gt;and &lt;b&gt;WINDOWS-*&lt;/b&gt; ranges; however the &lt;b&gt;UTF-8&lt;/b&gt; uses a much more advanced encoding system and uses those same 128 codes to provide for up to 1,112,064 characters in a more complex manner that uses up to four bytes but in a way that the original 128 characters are still represented by single bytes.&lt;/p&gt;&lt;p&gt;MUDs capable of operating with languages other than English will likely offer a choice of encodings, possibly with a &lt;i&gt;charset&lt;/i&gt; command or similar, review the choices that the MUD offers and choose a matching option from the list here. This setting can also be set and read via the Lua commands &lt;i&gt;setServerEncoding&lt;/i&gt;(&amp;quot;&lt;b&gt;encoding name&lt;/b&gt;&lt;i&gt;&amp;quot;)&lt;/i&gt; and &lt;i&gt;getServerEncoding()&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;In all cases Mudlet will spot incoming data that does not seem to fit the current encoding and each occurance will be marked with a &lt;b&gt;�&lt;/b&gt; if you see these then it is possible that this setting does not match what the MUD Server is sending out - or there is a defect in the way Mudlet is handling it.&lt;/p&gt;&lt;p&gt;&lt;i&gt;This feature is planned to be introduced in Mudlet 3.1.0 and is currently not known to be bug-free - please report any defects (including consistantly incorrect single characters for any of the encodings other than &lt;b&gt;ASCII&lt;/b&gt;, &lt;b&gt;ISO 8859-&lt;u&gt;1&lt;/u&gt;&lt;/b&gt; or &lt;b&gt;UTF-8&lt;/b&gt; as it is possible for there to be errors in the other encoding).&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very thorough description but it'll go over most people's heads - I'll help get you a more relatable text later.

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented Apr 27, 2017

So you are saying that the second read does seem correct (and you can read it OK?)

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 27, 2017

Yes, the second read is fine.

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented Apr 27, 2017

Yes, the second read is fine.

That is worrying in that I thought recently that TBuffer may not be fully initialised after creation...

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 27, 2017

@SlySven this was not the first read of the help file, by far - I read it many times before it got corrupted.

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 27, 2017

@ecam85 mind testing our alpha build of encoding support? Here are macOS and Windows binaries, I can do the Linux builds as well if needed.

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented Apr 27, 2017

Ah ha - I have found the source for Qt's own encoding tables src/corelib/codecs/qsimplecodec.cpp - now I can find out what they use for MACHINTOSH...

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 27, 2017

Brilliant! Could we make use of them instead of duplicating?

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented Apr 27, 2017

I do not think that source material is exposed - on the other hand I can do some stuff with a spreadsheet and be much more certain about values used (and the differences between each one and Latin1) - and as it is GPLed we can publish the data in some backwater part of our Wiki...

@ahmedcharles
Copy link
Copy Markdown
Contributor

I want to look at this but don't have time at the moment. Probably over the weekend.

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 28, 2017

I've resolved a merge conflict for you in this.

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented Apr 28, 2017

Thanks...!

@ecam85
Copy link
Copy Markdown
Contributor

ecam85 commented Apr 28, 2017

@vadi2 Sure, but I can only test it for Linux. I will build it myself, no problem.

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented Apr 28, 2017

@ecam85 There is support for other encodings and I have a few more (including "MACINTOSH") and what I think will be a faster system for all the others (apart from "ISO 8859-1", "UTF-8" and what will become the new default unless changed, good ol' 7-bit "ASCII") to follow shortly...

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 28, 2017

Do we have MUDs that actually use those encodings? Adding more isn't going to be a feature if we have to add tests for all of them and nobody us gonna use them, it'll be a maintenance burden on us.

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented Apr 28, 2017

The Realms of Legend one that ecam85 will be testing on offers quite a few:
snapshot2

Generally the different suffixes to the ISO ones cover different countries...

@ecam85
Copy link
Copy Markdown
Contributor

ecam85 commented Apr 28, 2017

Yes, I was about to mention that.

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented Apr 28, 2017 via email

Added getServerEncodingsList() which provides a list with the exact strings
to use - and which allows us to revised them if necessary.

Revise setServerEncoding() to not regard setting the same encoding that is
already being used from being a run-time error - now it will just return
the same true as if the setting had been made - but as no change is
actually taking place, no message will appear on the main console. This
message is now an "[ OK ] -" form one without an ending ellipses whereas it
was an "[ ALERT ] -" with one. Whether a change does occur or not a text
message is not provided, only on the run-time error case of specifying an
incorrect encoding will a nil + error-message now be produced.

Comment at start of TBuffer::translateToPlainText(...) redone.

Renamed data input argument to above function to ensure that the local
version which can be slightly longer if there are bytes "left-over" from
the previous packet that have been prepended to it.  Doing this allowed me
to find and fix places where that was not being used.

Revised some debugging messages to be clearer.

Revised the error handling for where the decoded UTF-8 data yields more
than two QChars from when converted by a QString constructor - it should
not happen but being paranoid is not unreasonable with initial coding
attempts...! Also arranged that more error cases report the actual bytes
that seemed to be in error.

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
Changed to use a C++11 ranged "for" instead of Qt macro "foreach" in
TBuffer constructor.

Changed format of run-time error for an invalid "encoding" string supplied to
to the Lua setServerEncoding("encoding") function.

Reordered encodings list so that UTF-8 follows immediately after ASCII
rather than being on the end of the list.

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
else {
lua_pushnil(L);
lua_pushfstring(L, "setServerEncoding: bad argument #1 value %s",
lua_pushfstring(L, "Error: %s.",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not even an Error - it's obvious it is an error, it is the 2nd return which can only be an error! just the actual error message itself please, leave the styling to the API.

<bool>true</bool>
</property>
<property name="title">
<string>Server Data Encoding</string>
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A case of Needless Capitalisation! See other grouping names on the same menu.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will fix.

<property name="enabled">
<bool>true</bool>
</property>
<property name="toolTip">
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be reworded, as it is unlikely to be understood by the vast majority of the population. What are you trying to communicate here - I can help you reword it but I'm not sure what's the desired outcome is.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Going through what I put there by paragraph:

  1. The first paragraph was an attempt to explain why this control is necessary and how the various choices come about, it indirectly suggests why UTF-8 is the "one-encoding to, in the darkness, bind them" and also suggest that it is a more complex thing to handle!

  2. Invites the user to see what the settings that the MUD offers and suggests they try the word "charset" as one possibility. Having found out they will need to choose the one they want and tell the MUD server to use it before setting Mudlet to match.

  3. Advises them what the symptoms of a mis-match between Mudlet and the MUD server will show up as (characters getting replaced with the '�' symbol).

  4. Is temporary to warn that if there are any characters that are getting consistently displayed wrongly we might have an error in one of those encoding tables - (IIRC there are one or two characters that may be subject to "regional variations" and it could be that the user is not in the right "region" for a particular table to be right for them - this is not applicable for ASCII, UTF-8 or ISO 8859-1 but might be an issue for the other encodings currently). The paragraph is also intended to emphasis that this currently only sorts out the on-screen display and that other parts such as the trigger engine have not yet been fixed up to work with non-ASCII text.

  5. Is also temporary and advises against using anything other than ASCII or ISO-8859-1 - eventually it may become a recommendation to use UTF-8!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking this through, we'd like Mudlet to work straight out of the box, just install and play - and the user will only ever need to use this option if the encoding is not set correctly already. So this really is a fix, a workaround, for when Mudlet didn't do its job right. So now we have an unhappy user because text isn't displayed right and we'd like to minimise the amount of time they're unhappy, so they can enjoy Mudlet and get into the game ASAP.

In order to do that, we need to make the text as short as possible so they've got the least amount of reading to do, and simple as possible so they have the best chance of understanding it. Otherwise, we'll just be keeping them in the unhappy state longer if they have to do a lot of reading and if they don't understand what's being said, they'll definitely be even more unhappy.

This is the reasoning behind not giving as much information about the general topic as you do, but instead being super concise and using simple language to get straight to the point.

I got distracted adding in this to the wiki so I'll provide the revised text later, but thought I'd provide the reasoning first so you'd know where I'm coming from.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got distracted...

I'd say so! That is quite a chunk of UI goodness...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

selection_100

Here's a tooltip that I believe achieves the goals I've set out above. Do you you think?

I did also remove the temporary text because it's an unstated assumption that anything in the development branch is under development. The whole thing might or might not work and we don't support anyone running unreleased code.

Copy link
Copy Markdown
Member Author

@SlySven SlySven May 15, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At present the trigger system is not going to fly with non-ASCII text - which is going to get in the way of anyone wanting to use the development code-base as anything other than a "technology preview" in those situations where they are using anything other than ASCII / ISO 8859-1 (or UTF-8 with just the characters from those charsets) - I still think a "this might make it look right but other things are not currently functional for anything other than that first pair of encodings" message is a requirement at the moment! 😮

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think a tooltip is the right place for this - we'll have it in the release notes and such. Otherwise, this is a very well-hidden place to advertise such lack of functionality and we can't possibly depend on users to find it :\

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've given it more thought and I've changed my mind, it'll be good to mention in both places that not everything is ready yet.

SlySven and others added 5 commits May 12, 2017 20:57
Run-time error string on supplying a bad encoding to setServerEncoding(...)
is now:
"Encoding \"XXXX\" does not exist;
 use one of the following:
 \"ASCII\",
 <list of other encodings (with UTF-8 at the top)>."

Profile Preferences title for encoding is now "Server data encoding" - it
has lost the extra capitalisation I originally used. 8-|

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
If the last bytes of a packet are multi-byte UTF-8 sequence it is necessary
to store them if there is not enough bytes in the packet to complete the
processing of them in TBuffer::translateToPlainText(...) unfortunately I
had made an error in assessing whether there WAS enough bytes so that the
code to store the incomplete bytes was being triggered when the last
character in the packet exactly ended at the end of the packet, i.e. it DID
fit in!

Also:
* Added a couple of QDebug()s - conditional on DEBUG_UTF8_PROCESSING that:
  report that an incomplete sequence has been detected and how many bytes
  are being stored; and report when they are being prepended onto the data
  in the next call to the method concerned.
* Revised the code that prepended those bytes to slightly optimise the
  tests that detect it is needed.
* Whilst using Mudlet replays to debug this issue I noticed that the
  replay starting and ending messages did not have the classification tag
  of the form "[ XXXX ] -" so did not display in any special way, I revised
  them to become an "[ INFO ]" message for replay starting and "[  OK  ]"
  at the end...!

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
@vadi2
Copy link
Copy Markdown
Member

vadi2 commented May 20, 2017

Here's another replay with the m appearing randomly:
20-05-2017#07-11-15.dat.zip

Log of how it looks like in html, incorrect bit is:

selection_116

You can tell it's extra as it throws the last | out of alignment.

Copy link
Copy Markdown
Member

@vadi2 vadi2 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to get this merged in, so approving it now!

I know there is a minor bug with encoding, but it should go in just so we don't delay merging it into development until the very end and don't get much testing on it at all because it was hidden away in a branch.

Conflicts resolved in:
	src/TLuaInterpreter.cpp
	src/TLuaInterpreter.h
	src/ui/profile_preferences.ui

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented May 21, 2017

Hang-on what is wrong now (I just merged the development branch into this PR - and had to resolve a couple of issues:

  • the TLuaInterpreter class issues where both branches had added functions and the header declarations and registration of them into the lua subsystem conflicted - straightforward to merge/combine the changes together
  • a conflicting change to the overall height of the dialog in src/ui/profile_preferences.ui and I choose the one from development branch (668)

So how to resolve this "This branch cannot be rebased due to conflicts" now?

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented May 21, 2017

That "19-05-2017#16-21-55.dat" file that was pointed out to me is showing corruption - and it is happening exactly at the point where the "there is not enough bytes to complete a UTF-8 sequence, we need to carry some over to the next packet" code is activated - so it does give me something to work with...

Found a local automatic variable "msPos" in
TBuffer::trasnlateToPlainText(...) was shadowing an unnecessary TBuffer class
member so renamed/retyped the local to be more appropriate, also found that
a second class member was not needed outside the method so added a local
automatic to do the same job:
* (int) msPos ==> (size_t) localBufferPosition
* msLength ==> (size_t) localBufferLength

Also remove now unused and/or shadowed:
* (int) TBuffer::lookupColor(const QString&, int)
* (int) TBuffer::msLength
* (int) TBuffer::msPos
* (QString) TBuffer::mFormatSequenceRest

I found that there was some MXP related code that was still working on the
incoming string data rather than the possibly pre-pended local copy which
would cause (further) problems in the future for non-ASCII that use MXP! I
changed those to also work on the local version.

Within TBuffer::translateToPlainText(...) I also spotting some single line
if(...) {...} else {...} which I braced as appropriate, a couple of places
where different spacing helps to line up related code and some other
redundant code fragments which I removed.

Signed-off-by: Stephen Lyons <slysven@virginmedia.com>
@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented May 22, 2017

I could not find a definite cause for the problem but I did find that two variables that I was using were shadowing TBuffer class members - and one of them was also in another method - although that was not used. I also spotted some places in the same TBuffer::translatedToPlainText(...) where MPX stuff was using the wrong string data (the incoming text data rather than the possibly prepended-to local copy) whilst it was not used in the replay data that I tested the code on it would break should MXP be used at the same time as non-ASCII text IMHO - so needed fixing.

I did notice the original problem with the "19-05-2017#16-21-55.dat" file but after the last commit it (and the other couple of replays I've been pointed at) seem to work OK even though I do not have a concrete explanation for the bug. I did notice during debuggging where the length of the packet was big enough to "carry" a UTF-8 byte over the display of localBuffer once the carried over byte was prepended - the display of bytes as char (the Qt debug display for the individual bytes) is confusing (they are being interpreted as ISO 8859-1 bytes individually?) but the "combined" string display was fine:
mudlet_snapshot16

The join is after the "На стене на" where the next (lower case?) character 'п' out of the:
"На стене написано ТУТ БЫЛ ПРУЛЬ " was split across packets but successfully rejoined:
mudlet_snapshot17

To confirm this does seem to fix the issue I undid the last commit and ran the same replay through the code without it - to get the following showing the issues arising after that byte:
mudlet_snapshot18

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented May 22, 2017

So this should be good to go - but I cannot see how to get around the conflicts...

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented May 22, 2017

What conflicts? Github says this branch is mergeable.

@SlySven
Copy link
Copy Markdown
Member Author

SlySven commented May 22, 2017

Ah it was greyed out for "Rebase and merge"
mudlet_snapshot19

but that is slightly misleading because it can be "Squashed and merged" - the drop down triangle to select the operation - being black on light grey - also looks to be disabled but it is not - it just turns green when the other option is selected:
mudlet_snapshot20

@vadi2
Copy link
Copy Markdown
Member

vadi2 commented May 22, 2017 via email

@SlySven SlySven merged commit 0b3f322 into Mudlet:development May 22, 2017
@SlySven SlySven deleted the Enhance_addTextTranscoding branch May 22, 2017 15:32
@SlySven SlySven restored the Enhance_addTextTranscoding branch June 22, 2020 18:05
@SlySven SlySven deleted the Enhance_addTextTranscoding branch June 22, 2020 18:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants