{ "translations": { "Couldn't send mail to following users: %s " : "Не могу да пошаљем е-пошту следећим корисницима: %s ", "Preparing update" : "Припремам надоградњу", "Turned on maintenance mode" : "Режим одржавања укључен", "Turned off maintenance mode" : "Режим одржавања искључен", "Maintenance mode is kept active" : "Режим одржавања се држи активним", "Updated database" : "База података ажурирана", "Checked database schema update" : "Ажурирање шеме базе података, проверено", "Checked database schema update for apps" : "Ажурирање шеме базе података за апликације, проверено", "Updated \"%s\" to %s" : "„%s“ ажириран на %s", "Repair warning: " : "Упозорење о поправци :", "Repair error: " : "Грешка поправке:", "Following apps have been disabled: %s" : "Следеће апликације су искључене: %s", "File is too big" : "Фајл је превелик", "Invalid file provided" : "Понуђени фајл је неисправан", "No image or file provided" : "Није дата ни слика ни фајл", "Unknown filetype" : "Непознат тип фајла", "Invalid image" : "Неисправна слика", "No temporary profile picture available, try again" : "Нема привремене слике профила. Покушајте поново", "No crop data provided" : "Нема података о опсецању", "No valid crop data provided" : "Нема података о опсецању", "Crop is not square" : "Опсецање није квадрат", "Couldn't reset password because the token is invalid" : "Није могуће ресетовати лозинку јер je токен неважећи", "Couldn't send reset email. Please make sure your username is correct." : "Не могу да пошаљем поруку за ресетовање лозинке. Проверите да ли је корисничко име исправно.", "%s password reset" : "%s лозинка ресетована", "Couldn't send reset email. Please contact your administrator." : "Не могу да пошаљем е-пошту за ресетовање лозинке. Контактирајте администратора.", "Sunday" : "недеља", "Monday" : "понедељак", "Tuesday" : "уторак", "Wednesday" : "среда", "Thursday" : "четвртак", "Friday" : "петак", "Saturday" : "субота", "Sun." : "нед", "Mon." : "пон", "Tue." : "уто", "Wed." : "сре", "Thu." : "чет", "Fri." : "пет", "Sat." : "суб", "Su" : "Не", "Mo" : "По", "Tu" : "Ут", "We" : "Ср", "Th" : "Че", "Fr" : "Пе", "Sa" : "Су", "January" : "јануар", "February" : "фебруар", "March" : "март", "April" : "април", "May" : "мај", "June" : "јун", "July" : "јул", "August" : "август", "September" : "септембар", "October" : "октобар", "November" : "новембар", "December" : "децембар", "Jan." : "јан", "Feb." : "феб", "Mar." : "мар", "Apr." : "апр", "May." : "мај", "Jun." : "јун", "Jul." : "јул", "Aug." : "авг", "Sep." : "сеп", "Oct." : "окт", "Nov." : "нов", "Dec." : "дец", "Settings" : "Поставке", "Saving..." : "Уписујем...", "Dismiss" : "Откажи", "seconds ago" : "пре пар секунди", "The link to reset your password has been sent to your email. If you do not receive it within a reasonable amount of time, check your spam/junk folders.
If it is not there ask your local administrator." : "Веза за ресетовање лозинке је послата на вашу е-адресу. Ако је не примите ускоро, проверите фасцикле за нежељену пошту.
Ако није ни тамо, контактирајте вашег администратора.", "Your files are encrypted. If you haven't enabled the recovery key, there will be no way to get your data back after your password is reset.
If you are not sure what to do, please contact your administrator before you continue.
Do you really want to continue?" : "Фајлови су вам шифровани. Ако нисте укључили кључ за опоравак, нећете моћи да повратите податке након ресетовања лозинке.
Ако нисте сигурни шта да радите, контактирајте администратора пре него што наставите.
Да ли желите да наставите?", "I know what I'm doing" : "Знам шта радим", "Password can not be changed. Please contact your administrator." : "Лозинка се не може променити. Контактирајте администратора.", "No" : "Не", "Yes" : "Да", "Choose" : "Изабери", "Error loading file picker template: {error}" : "Грешка при учитавању шаблона бирача фајлова: {error}", "Ok" : "У реду", "Error loading message template: {error}" : "Грешка при учитавању шаблона поруке: {error}", "read-only" : "само-за-читање", "_{count} file conflict_::_{count} file conflicts_" : ["{count} сукоб фајлова","{count} сукоба фајлова","{count} сукоба фајлова"], "One file conflict" : "Један сукоб фајлова", "New Files" : "Нови фајлови", "Already existing files" : "Постојећи фајлови", "Which files do you want to keep?" : "Које фајлове желите да задржите?", "If you select both versions, the copied file will have a number added to its name." : "Ако изаберете обе верзије, копираном фајлу ће бити додат број у називу.", "Cancel" : "Одустани", "Continue" : "Настави", "(all selected)" : "(све изабрано)", "({count} selected)" : "(изабраних {count})", "Error loading file exists template" : "Грешка при учитавању шаблона „Фајл постоји“", "Very weak password" : "Веома слаба лозинка", "Weak password" : "Слаба лозинка", "So-so password" : "Осредња лозинка", "Good password" : "Добра лозинка", "Strong password" : "Јака лозинка", "Your web server is not yet set up properly to allow file synchronization because the WebDAV interface seems to be broken." : "Ваш сервер није правилно подешен да омогући синхронизацију фајлова. Изгледа да је ВебДАВ сучеље покварено.", "This server has no working Internet connection. This means that some of the features like mounting external storage, notifications about updates or installation of third-party apps will not work. Accessing files remotely and sending of notification emails might not work, either. We suggest to enable Internet connection for this server if you want to have all features." : "Овај сервер нема везу са интернетом. То значи да неке могућности, попут монтирања спољашњег складишта, обавештења о ажурирању или инсталација апликација треће стране, неће радити. Даљински приступ и слање е-поште, такође неће радити. Предлажемо да омогућите интернет везу за овај сервер ако желите да имате све могућности.", "Error occurred while checking server setup" : "Дошло је до грешке при провери поставки сервера", "Your data directory and your files are probably accessible from the Internet. The .htaccess file is not working. We strongly suggest that you configure your web server in a way that the data directory is no longer accessible or you move the data directory outside the web server document root." : "Ваш директоријум са подацима и ваши фајлови су вероватно доступни са интернета. Фајл .htaccess не ради. Предлажемо да подесите ваш веб сервер на начин да директоријум са подацима не буде доступан или га изместите изван кореног директоријума веб сервера.", "The \"{header}\" HTTP header is not configured to equal to \"{expected}\". This is a potential security or privacy risk and we recommend adjusting this setting." : "ХТТП заглавље „{header}“ није подешено као „{expected}“. Ово потенцијално угрожава безбедност и приватност и препоручујемо да подесите ову поставку.", "Shared" : "Дељено", "Shared with {recipients}" : "Дељено са {recipients}", "Error" : "Грешка", "Error while sharing" : "Грешка при дељењу", "Error while unsharing" : "Грешка при укидању дељења", "Error setting expiration date" : "Грешка при постављању датума истека", "The public link will expire no later than {days} days after it is created" : "Јавна веза ће престати да важи {days} дана након стварања", "Set expiration date" : "Постави датум истека", "Expiration" : "Истиче", "Expiration date" : "Датум истека", "Choose a password for the public link" : "Одредите лозинку за јавну везу", "Sending ..." : "Шаљем...", "Email sent" : "Порука је послата", "Resharing is not allowed" : "Поновно дељење није дозвољено", "Share link" : "Веза дељења", "Link" : "Веза", "Password protect" : "Заштићено лозинком", "Password" : "Лозинка", "Allow editing" : "Дозволи уређивање", "Email link to person" : "Пошаљи е-поштом", "Send" : "Пошаљи", "Shared with you and the group {group} by {owner}" : "{owner} дели са вама и са групом {group}.", "Shared with you by {owner}" : "{owner} дели са вама", "group" : "група", "remote" : "удаљени", "notify by email" : "обавести е-поштом", "Unshare" : "Укини дељење", "can share" : "може да дели", "can edit" : "може да мења", "create" : "направи", "change" : "измени", "delete" : "обриши", "access control" : "права приступа", "An error occured. Please try again" : "Дошло је до грешке. Покушајте поново", "Share" : "Дели", "Share with people on other ownClouds using the syntax username@example.com/owncloud" : "Поделите са људима у другим облацима користећи синтаксу корисничкоиме@сервер.com/owncloud", "Warning" : "Упозорење", "Delete" : "Обриши", "Rename" : "Преименуј", "The object type is not specified." : "Тип објекта није наведен.", "Enter new" : "Унесите нови", "Add" : "Додај", "Edit tags" : "Уреди ознаке", "Error loading dialog template: {error}" : "Грешка при учитавању шаблона дијалога: {error}", "No tags selected for deletion." : "Нема ознака за брисање.", "unknown text" : "непознат текст", "Hello world!" : "Здраво свете!", "sunny" : "сунчано", "Hello {name}, the weather is {weather}" : "Здраво {name}, време је {weather}", "Hello {name}" : "Здраво {name}", "_download %n file_::_download %n files_" : ["преузми %n фајл","преузми %n фајла","преузми %n фајлова"], "Updating {productName} to version {version}, this may take a while." : "Надограђујем {productName} на издање {version}. Ово би могло да потраје.", "Please reload the page." : "Поново учитајте страницу.", "The update was unsuccessful. " : "Ажурирање није успело.", "The update was successful. There were warnings." : "Ажурирање је успело. Било је упозорења.", "The update was successful. Redirecting you to ownCloud now." : "Ажурирање је успело. Преусмеравам вас на оунКлауд.", "Searching other places" : "Претражујем остала места", "Personal" : "Лично", "Users" : "Корисници", "Apps" : "Апликације", "Admin" : "Администрација", "Help" : "Помоћ", "Error loading tags" : "Грешка при учитавању ознака", "Tag already exists" : "Ознака већ постоји", "Error deleting tag(s)" : "Грешка при брисању ознака", "Error tagging" : "Грешка означавања", "Error untagging" : "Грешка при скидању ознака", "Error favoriting" : "Грешка при постављању омиљеног", "Error unfavoriting" : "Грешка при укидању омиљеног", "Access forbidden" : "Забрањен приступ", "File not found" : "Фајл није нађен", "The specified document has not been found on the server." : "Наведени документ није нађен на серверу.", "You can click here to return to %s." : "Кликните овде да се вратите на %s.", "Hey there,\n\njust letting you know that %s shared %s with you.\nView it: %s\n\n" : "Поздрав,\n\nсамо вас обавештавам да %s дели %s са вама.\nПогледајте: %s\n\n", "The share will expire on %s." : "Дељење истиче %s.", "Cheers!" : "Здраво!", "Internal Server Error" : "Унутрашња грешка сервера", "The server encountered an internal error and was unable to complete your request." : "Због интерне грешке на серверу, ваш захтев није могао бити довршен.", "Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report." : "Контактирајте администратора ако се грешка понови и укључите у извештај техничке појединости наведене испод.", "More details can be found in the server log." : "Више детаља се може наћи у дневнику сервера.", "Technical details" : "Технички детаљи", "Remote Address: %s" : "Удаљена адреса: %s", "Request ID: %s" : "ИД захтева: %s", "Type: %s" : "Тип: %s", "Code: %s" : "Кôд: %s", "Message: %s" : "Порука: %s", "File: %s" : "Фајл: %s", "Line: %s" : "Линија: %s", "Trace" : "Траг", "Security warning" : "Безбедносно упозорење", "Your data directory and files are probably accessible from the internet because the .htaccess file does not work." : "Ваш директоријум са подацима и фајлови су вероватно доступни са интернета јер .htaccess не ради.", "For information how to properly configure your server, please see the documentation." : "Информације о томе како исправно подесити серверможете наћи удокументацији.", "Create an admin account" : "Направи административни налог", "Username" : "Корисничко име", "Storage & database" : "Складиште и база података", "Data folder" : "Фацикла података", "Configure the database" : "Подешавање базе", "Only %s is available." : "Само %s је доступна.", "Install and activate additional PHP modules to choose other database types." : "Инсталирајте и активирајте додатне ПХП модуле за избор других врста база података.", "For more details check out the documentation." : "За више детаља погледајте документацију.", "Database user" : "Корисник базе", "Database password" : "Лозинка базе", "Database name" : "Назив базе", "Database tablespace" : "Радни простор базе података", "Database host" : "Домаћин базе", "Performance warning" : "Упозорење о перформансама", "SQLite will be used as database." : "СКуЛајт ће бити коришћен за базу података.", "For larger installations we recommend to choose a different database backend." : "За веће инсталације препоручујемо да изаберете другу позадину базе података.", "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "Нарочито ако се користи клијент програм у графичком окружењу, коришћење СКуЛајта није препоручљиво.", "Finish setup" : "Заврши подешавање", "Finishing …" : "Завршавам…", "Need help?" : "Треба вам помоћ?", "See the documentation" : "Погледајте документацију", "Hey there,

just letting you know that %s shared %s with you.
View it!

" : "Поздрав,

само вас обавештавам да %s дели %s са вама.
Погледајте!

", "This application requires JavaScript for correct operation. Please {linkstart}enable JavaScript{linkend} and reload the page." : "Ова апликација захтева Јава скрипт за исправан рад. {linkstart}Омогућите Јава скрипт{linkend} и поново учитајте страницу.", "Log out" : "Одјава", "Search" : "Претражи", "Server side authentication failed!" : "Аутентификација на серверу није успела!", "Please contact your administrator." : "Контактирајте вашег администратора.", "An internal error occured." : "Дошло је до интерне грешке.", "Please try again or contact your administrator." : "Покушајте поново или контактирајте вашег администратора.", "Log in" : "Пријава", "Alternative Logins" : "Алтернативне пријаве", "Use the following link to reset your password: {link}" : "Употребите следећу везу да ресетујете своју лозинку: {link}", "New password" : "Нова лозинка", "New Password" : "Нова лозинка", "Reset password" : "Ресетуј лозинку", "This ownCloud instance is currently in single user mode." : "Овај оунКлауд тренутно ради у режиму једног корисника.", "This means only administrators can use the instance." : "То значи да га могу користити само администратори.", "Contact your system administrator if this message persists or appeared unexpectedly." : "Контактирајте администратора ако се порука понавља или се неочекивано појавила.", "Thank you for your patience." : "Хвала вам на стрпљењу.", "You are accessing the server from an untrusted domain." : "Приступате серверу са непоузданог домена.", "Depending on your configuration, as an administrator you might also be able to use the button below to trust this domain." : "Зависно од ваших подешавања, као администратор можете употребити дугме испод да потврдите поузданост домена.", "Add \"%s\" as trusted domain" : "Додај „%s“ као поуздан домен", "The theme %s has been disabled." : "Тема %s је онемогућена.", "Please make sure that the database, the config folder and the data folder have been backed up before proceeding." : "Проверите да ли сте направили резервну копију фасцикли са подешавањима и подацима пре него што наставите.", "Start update" : "Почни надоградњу", "To avoid timeouts with larger installations, you can instead run the following command from your installation directory:" : "Да избегнете прекорачење времена одзива на већим инсталацијама, можете покренути следећу команду у инсталационом директоријуму:", "This %s instance is currently in maintenance mode, which may take a while." : "Овај %s је тренутно у режиму одржавања а то може потрајати.", "This page will refresh itself when the %s instance is available again." : "Ова страница ће се сама освежити када %s постане поново доступан." },"pluralForm" :"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);" }38' href='#n438'>438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.layoutmgr.inline;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.fop.area.Area;
import org.apache.fop.area.LineArea;
import org.apache.fop.area.Trait;
import org.apache.fop.area.inline.InlineArea;
import org.apache.fop.complexscripts.bidi.BidiResolver;
import org.apache.fop.datatypes.Length;
import org.apache.fop.datatypes.Numeric;
import org.apache.fop.fo.Constants;
import org.apache.fop.fo.flow.Block;
import org.apache.fop.fo.properties.CommonHyphenation;
import org.apache.fop.fo.properties.KeepProperty;
import org.apache.fop.fonts.Font;
import org.apache.fop.fonts.FontInfo;
import org.apache.fop.fonts.FontTriplet;
import org.apache.fop.hyphenation.Hyphenation;
import org.apache.fop.hyphenation.Hyphenator;
import org.apache.fop.layoutmgr.Adjustment;
import org.apache.fop.layoutmgr.BlockLayoutManager;
import org.apache.fop.layoutmgr.BlockLevelLayoutManager;
import org.apache.fop.layoutmgr.BreakElement;
import org.apache.fop.layoutmgr.BreakingAlgorithm;
import org.apache.fop.layoutmgr.ElementListObserver;
import org.apache.fop.layoutmgr.FloatContentLayoutManager;
import org.apache.fop.layoutmgr.FootenoteUtil;
import org.apache.fop.layoutmgr.FootnoteBodyLayoutManager;
import org.apache.fop.layoutmgr.InlineKnuthSequence;
import org.apache.fop.layoutmgr.Keep;
import org.apache.fop.layoutmgr.KnuthBlockBox;
import org.apache.fop.layoutmgr.KnuthBox;
import org.apache.fop.layoutmgr.KnuthElement;
import org.apache.fop.layoutmgr.KnuthGlue;
import org.apache.fop.layoutmgr.KnuthPenalty;
import org.apache.fop.layoutmgr.KnuthPossPosIter;
import org.apache.fop.layoutmgr.KnuthSequence;
import org.apache.fop.layoutmgr.LayoutContext;
import org.apache.fop.layoutmgr.LayoutManager;
import org.apache.fop.layoutmgr.LeafPosition;
import org.apache.fop.layoutmgr.ListElement;
import org.apache.fop.layoutmgr.NonLeafPosition;
import org.apache.fop.layoutmgr.Position;
import org.apache.fop.layoutmgr.PositionIterator;
import org.apache.fop.layoutmgr.SpaceSpecifier;
import org.apache.fop.traits.MinOptMax;

/**
 * LayoutManager for lines. It builds one or more lines containing
 * inline areas generated by its sub layout managers.
 * A break is found for each line which may contain one of more
 * breaks from the child layout managers.
 * Once a break is found then it is return for the parent layout
 * manager to handle.
 * When the areas are being added to the page this manager
 * creates a line area to contain the inline areas added by the
 * child layout managers.
 */
public class LineLayoutManager extends InlineStackingLayoutManager
                               implements BlockLevelLayoutManager {

    /**
     * this constant is used to create elements when text-align is center:
     * every TextLM descendant of LineLM must use the same value,
     * otherwise the line breaking algorithm does not find the right
     * break point
     */
    public static final int DEFAULT_SPACE_WIDTH = 3336;

    /**
     * logging instance
     */
    private static Log log = LogFactory.getLog(LineLayoutManager.class);

    private final Block fobj;
    private boolean isFirstInBlock;

    /**
     * Private class to store information about inline breaks.
     * Each value holds the start and end indexes into a List of
     * inline break positions.
     */
    public static class LineBreakPosition extends LeafPosition {
        private final int parIndex; // index of the Paragraph this Position refers to
        private final int startIndex; //index of the first element this Position refers to
        private final int availableShrink;
        private final int availableStretch;
        private final int difference;
        private final double dAdjust; // Percentage to adjust (stretch or shrink)
        private final double ipdAdjust; // Percentage to adjust (stretch or shrink)
        private final int startIndent;
        private final int endIndent;
        private final int lineHeight;
        private final int lineWidth;
        private final int spaceBefore;
        private final int spaceAfter;
        private final int baseline;

        LineBreakPosition(LayoutManager lm, int index, int startIndex, int breakIndex,
                int shrink, int stretch, int diff, double ipdA, double adjust, int si,
                int ei, int lh, int lw, int sb, int sa, int bl) {
            super(lm, breakIndex);
            availableShrink = shrink;
            availableStretch = stretch;
            difference = diff;
            parIndex = index;
            this.startIndex = startIndex;
            ipdAdjust = ipdA;
            dAdjust = adjust;
            startIndent = si;
            endIndent = ei;
            lineHeight = lh;
            lineWidth = lw;
            spaceBefore = sb;
            spaceAfter = sa;
            baseline = bl;
        }

    }


    private int bidiLevel = -1;
    private int textAlignment = EN_JUSTIFY;
    private int textAlignmentLast;
    private int effectiveAlignment;
    private Length textIndent;
    private Length lastLineEndIndent;
    private CommonHyphenation hyphenationProperties;
    private Numeric hyphenationLadderCount;
    private int wrapOption = EN_WRAP;
    private int whiteSpaceTreament;
    //private LayoutProps layoutProps;

    private final Length lineHeight;
    private final int lead;
    private final int follow;
    private AlignmentContext alignmentContext;

    private int baselineOffset = -1;

    private List<KnuthSequence> knuthParagraphs;

    private LineLayoutPossibilities lineLayouts;
    private LineLayoutPossibilities[] lineLayoutsList;
    private int ipd;
    /**
     * When layout must be re-started due to a change of IPD, there is no need
     * to perform hyphenation on the remaining Knuth sequence once again.
     */
    private boolean hyphenationPerformed;

    /**
     * This class is used to remember
     * which was the first element in the paragraph
     * returned by each LM.
     */
    private final class Update {
        private final InlineLevelLayoutManager inlineLM;
        private final int firstIndex;

        private Update(InlineLevelLayoutManager lm, int index) {
            inlineLM = lm;
            firstIndex = index;
        }
    }

    // this class represents a paragraph
    private static class Paragraph extends InlineKnuthSequence {

        private static final long serialVersionUID = 5862072380375189105L;

        /** Number of elements to ignore at the beginning of the list. */
        private int ignoreAtStart;
        /** Number of elements to ignore at the end of the list. */
        private int ignoreAtEnd;

        // space at the end of the last line (in millipoints)
        private MinOptMax lineFiller;
        private final int textAlignment;
        private final int textAlignmentLast;
        private final int textIndent;
        private final int lastLineEndIndent;
        // the LM which created the paragraph
        private final LineLayoutManager layoutManager;

        Paragraph(LineLayoutManager llm, int alignment, int alignmentLast,
                         int indent, int endIndent) {
            super();
            layoutManager = llm;
            textAlignment = alignment;
            textAlignmentLast = alignmentLast;
            textIndent = indent;
            lastLineEndIndent = endIndent;
        }

        @Override
        public void startSequence() {
            // set the minimum amount of empty space at the end of the
            // last line
            if (textAlignment == EN_CENTER) {
                lineFiller = MinOptMax.getInstance(lastLineEndIndent);
            } else {
                lineFiller = MinOptMax.getInstance(lastLineEndIndent, lastLineEndIndent,
                        layoutManager.ipd);
            }

            // add auxiliary elements at the beginning of the paragraph
            if (textAlignment == EN_CENTER && textAlignmentLast != EN_JUSTIFY) {
                this.add(new KnuthGlue(0, 3 * DEFAULT_SPACE_WIDTH, 0,
                                       null, false));
                ignoreAtStart++;
            }

            // add the element representing text indentation
            // at the beginning of the first paragraph
            if (layoutManager.isFirstInBlock && layoutManager.knuthParagraphs.size() == 0
                        && textIndent != 0) {
                this.add(new KnuthInlineBox(textIndent, null,
                                      null, false));
                ignoreAtStart++;
            }
        }

        public void endParagraph() {
            KnuthSequence finishedPar = this.endSequence();
            if (finishedPar != null) {
                layoutManager.knuthParagraphs.add(finishedPar);
            }
        }

        @Override
        public KnuthSequence endSequence() {
            if (this.size() > ignoreAtStart) {
                if (textAlignment == EN_CENTER
                    && textAlignmentLast != EN_JUSTIFY) {
                    this.add(new KnuthGlue(0, 3 * DEFAULT_SPACE_WIDTH, 0,
                                           null, false));
                    this.add(new KnuthPenalty(lineFiller.getOpt(), -KnuthElement.INFINITE,
                                              false, null, false));
                    ignoreAtEnd = 2;
                } else if (textAlignmentLast != EN_JUSTIFY) {
                    // add the elements representing the space
                    // at the end of the last line
                    // and the forced break
                    this.add(new KnuthPenalty(0, KnuthElement.INFINITE,
                                              false, null, false));
                    this.add(new KnuthGlue(0,
                            lineFiller.getStretch(),
                            lineFiller.getShrink(), null, false));
                    this.add(new KnuthPenalty(lineFiller.getOpt(), -KnuthElement.INFINITE,
                                              false, null, false));
                    ignoreAtEnd = 3;
                } else {
                    // add only the element representing the forced break
                    this.add(new KnuthPenalty(lineFiller.getOpt(), -KnuthElement.INFINITE,
                                              false, null, false));
                    ignoreAtEnd = 1;
                }
                return this;
            } else {
                this.clear();
                return null;
            }
        }

        /**
         * @return true if the sequence contains a box
         */
        public boolean containsBox() {
            for (Object o : this) {
                KnuthElement el = (KnuthElement) o;
                if (el.isBox()) {
                    return true;
                }
            }
            return false;
        }
    }

    private class LineBreakingAlgorithm extends BreakingAlgorithm {
        private final LineLayoutManager thisLLM;
        private final int pageAlignment;
        private int activePossibility;
        private int addedPositions;
        private final int textIndent;
        private final int lineHeight;
        private final int lead;
        private final int follow;
        private static final double MAX_DEMERITS = 10e6;

        public LineBreakingAlgorithm(int pageAlign, int textAlign, int textAlignLast, int indent, int fillerWidth,
                int lh, int ld, int fl, boolean first, int maxFlagCount, LineLayoutManager llm) {
            super(textAlign, textAlignLast, first, false, maxFlagCount);
            pageAlignment = pageAlign;
            textIndent = indent;
            lineHeight = lh;
            lead = ld;
            follow = fl;
            thisLLM = llm;
            activePossibility = -1;
        }

        @Override
        public void updateData1(int lineCount, double demerits) {
            lineLayouts.addPossibility(lineCount, demerits);
            if (log.isTraceEnabled()) {
                log.trace("Layout possibility in " + lineCount + " lines; break at position:");
            }
        }

        @Override
        public void updateData2(KnuthNode bestActiveNode,
                                KnuthSequence par,
                                int total) {
            // compute indent and adjustment ratio, according to
            // the value of text-align and text-align-last
            int startIndent;
            int endIndent;
            int difference = bestActiveNode.difference;
            int textAlign = (bestActiveNode.line < total) ? alignment : alignmentLast;

            switch (textAlign) {
            case Constants.EN_START:
                startIndent = 0;
                endIndent = difference > 0 ? difference : 0;
                break;
            case Constants.EN_END:
                startIndent = difference;
                endIndent = 0;
                break;
            case Constants.EN_CENTER:
                startIndent = difference / 2;
                endIndent = startIndent;
                break;
            default:
            case Constants.EN_JUSTIFY:
                startIndent = 0;
                endIndent = 0;
                break;
            }

            /*
            startIndent += (textAlign == Constants.EN_CENTER)
                      ? difference / 2 : (textAlign == Constants.EN_END) ? difference : 0;
            */
            startIndent += (bestActiveNode.line == 1 && indentFirstPart && isFirstInBlock)
                      ? textIndent : 0;

            double ratio = (textAlign == Constants.EN_JUSTIFY
                || difference < 0 && -difference <= bestActiveNode.availableShrink)
                        ? bestActiveNode.adjustRatio : 0;

            // add nodes at the beginning of the list, as they are found
            // backwards, from the last one to the first one

            // the first time this method is called, initialize activePossibility
            if (activePossibility == -1) {
                activePossibility = 0;
                addedPositions = 0;
            }

            if (addedPositions == lineLayouts.getLineCount(activePossibility)) {
                activePossibility++;
                addedPositions = 0;
            }

            int lack = difference + bestActiveNode.availableShrink;
            // if this LLM is nested inside a BlockContainerLayoutManager that is constraining
            // the available width and thus responsible for the overflow then we do not issue
            // warning event here and instead let the BCLM handle that at a later stage
            if (lack < 0 && !handleOverflow(-lack)) {
                InlineLevelEventProducer eventProducer
                    = InlineLevelEventProducer.Provider.get(
                        getFObj().getUserAgent().getEventBroadcaster());
                if (curChildLM.getFObj() == null) {
                    eventProducer.lineOverflows(this, getFObj().getName(), bestActiveNode.line,
                            -lack, getFObj().getLocator());
                } else {
                    eventProducer.lineOverflows(this, curChildLM.getFObj().getName(), bestActiveNode.line,
                        -lack, curChildLM.getFObj().getLocator());
                }
            }

            //log.debug("LLM> (" + (lineLayouts.getLineNumber(activePossibility) - addedPositions)
            //    + ") difference = " + difference + " ratio = " + ratio);
            lineLayouts.addBreakPosition(makeLineBreakPosition(par,
                   (bestActiveNode.line > 1 ? bestActiveNode.previous.position + 1 : 0),
                   bestActiveNode.position,
                   bestActiveNode.availableShrink - (addedPositions > 0
                       ? 0 : ((Paragraph) par).lineFiller.getShrink()),
                   bestActiveNode.availableStretch,
                   difference, ratio, startIndent, endIndent), activePossibility);
            addedPositions++;
        }

        /* reset activePossibility, as if breakpoints have not yet been computed
         */
        public void resetAlgorithm() {
            activePossibility = -1;
        }

        private LineBreakPosition makeLineBreakPosition(KnuthSequence par, int firstElementIndex, int lastElementIndex,
                int availableShrink, int availableStretch, int difference, double ratio,
                int startIndent, int endIndent) {
            // line height calculation - spaceBefore may differ from spaceAfter
            // by 1mpt due to rounding
            int spaceBefore = (lineHeight - lead - follow) / 2;
            int spaceAfter = lineHeight - lead - follow - spaceBefore;
            // height before the main baseline
            int lineLead = lead;
            // maximum follow
            int lineFollow = follow;
            // true if this line contains only zero-height, auxiliary boxes
            // and the actual line width is 0; in this case, the line "collapses"
            // i.e. the line area will have bpd = 0
            boolean isZeroHeightLine = (difference == ipd);

            // if line-stacking-strategy is "font-height", the line height
            // is not affected by its content
            if (fobj.getLineStackingStrategy() != EN_FONT_HEIGHT) {
                ListIterator inlineIterator
                    = par.listIterator(firstElementIndex);
                AlignmentContext lastAC = null;
                int maxIgnoredHeight = 0; // See spec 7.13
                for (int j = firstElementIndex;
                     j <= lastElementIndex;
                     j++) {
                    KnuthElement element = (KnuthElement) inlineIterator.next();
                    if (element instanceof KnuthInlineBox) {
                        AlignmentContext ac = ((KnuthInlineBox) element).getAlignmentContext();
                        if (ac != null && lastAC != ac) {
                            if (!ac.usesInitialBaselineTable()
                                || ac.getAlignmentBaselineIdentifier() != EN_BEFORE_EDGE
                                   && ac.getAlignmentBaselineIdentifier() != EN_AFTER_EDGE) {
                                if (fobj.getLineHeightShiftAdjustment() == EN_CONSIDER_SHIFTS
                                    || ac.getBaselineShiftValue() == 0) {
                                    int alignmentOffset = ac.getTotalAlignmentBaselineOffset();
                                    if (alignmentOffset + ac.getAltitude() > lineLead) {
                                        lineLead = alignmentOffset + ac.getAltitude();
                                    }
                                    if (ac.getDepth() - alignmentOffset > lineFollow)  {
                                        lineFollow = ac.getDepth() - alignmentOffset;
                                    }
                                }
                            } else {
                                if (ac.getHeight() > maxIgnoredHeight) {
                                    maxIgnoredHeight = ac.getHeight();
                                }
                            }
                            lastAC = ac;
                        }
                        if (isZeroHeightLine
                            && (!element.isAuxiliary() || ac != null && ac.getHeight() > 0)) {
                            isZeroHeightLine = false;
                        }
                    }
                }

                if (lineFollow < maxIgnoredHeight - lineLead) {
                    lineFollow = maxIgnoredHeight - lineLead;
                }
            }

            constantLineHeight = lineLead + lineFollow;

            if (isZeroHeightLine) {
                return new LineBreakPosition(thisLLM,
                                             knuthParagraphs.indexOf(par),
                                             firstElementIndex, lastElementIndex,
                                             availableShrink, availableStretch,
                                             difference, ratio, 0, startIndent, endIndent,
                                             0, ipd, 0, 0, 0);
            } else {
                return new LineBreakPosition(thisLLM,
                                             knuthParagraphs.indexOf(par),
                                             firstElementIndex, lastElementIndex,
                                             availableShrink, availableStretch,
                                             difference, ratio, 0, startIndent, endIndent,
                                             lineLead + lineFollow,
                                             ipd, spaceBefore, spaceAfter,
                                             lineLead);
            }
        }

        @Override
        protected int filterActiveNodes() {
            KnuthNode bestActiveNode = null;

            if (pageAlignment == EN_JUSTIFY) {
                // leave all active nodes and find the optimum line number
                //log.debug("LBA.filterActiveNodes> " + activeNodeCount + " layouts");
                for (int i = startLine; i < endLine; i++) {
                    for (KnuthNode node = getNode(i); node != null; node = node.next) {
                        //log.debug("                       + lines = "
                        //+ node.line + " demerits = " + node.totalDemerits);
                        bestActiveNode = compareNodes(bestActiveNode, node);
                    }
                }

                // scan the node set once again and remove some nodes
                //log.debug("LBA.filterActiveList> layout selection");
                for (int i = startLine; i < endLine; i++) {
                    for (KnuthNode node = getNode(i); node != null; node = node.next) {
                        //if (Math.abs(node.line - bestActiveNode.line) > maxDiff) {
                        //if (false) {
                        if (node.line != bestActiveNode.line
                            && node.totalDemerits > MAX_DEMERITS) {
                            //log.debug("                     XXX lines = "
                            //+ node.line + " demerits = " + node.totalDemerits);
                            removeNode(i, node);
                        } else {
                            //log.debug("                      ok lines = "
                            //+ node.line + " demerits = " + node.totalDemerits);
                        }
                    }
                }
            } else {
                // leave only the active node with fewest total demerits
                for (int i = startLine; i < endLine; i++) {
                    for (KnuthNode node = getNode(i); node != null; node = node.next) {
                        bestActiveNode = compareNodes(bestActiveNode, node);
                        if (node != bestActiveNode) {
                            removeNode(i, node);
                        }
                    }
                }
            }
            return bestActiveNode.line;
        }
    }


    private int constantLineHeight = 12000;

    /**
     * Create a new Line Layout Manager.
     * This is used by the block layout manager to create
     * line managers for handling inline areas flowing into line areas.
     * @param block the block formatting object
     * @param lh the default line height
     * @param l the default lead, from top to baseline
     * @param f the default follow, from baseline to bottom
     */
    public LineLayoutManager(Block block, Length lh, int l, int f) {
        super(block);
        fobj = block;
        // the child FObj are owned by the parent BlockLM
        // this LM has all its childLMs preloaded
        fobjIter = null;
        lineHeight = lh;
        lead = l;
        follow = f;
    }

    /** {@inheritDoc} */
    @Override
    public void initialize() {
        bidiLevel = fobj.getBidiLevel();
        textAlignment = fobj.getTextAlign();
        textAlignmentLast = fobj.getTextAlignLast();
        textIndent = fobj.getTextIndent();
        lastLineEndIndent = fobj.getLastLineEndIndent();
        hyphenationProperties = fobj.getCommonHyphenation();
        hyphenationLadderCount = fobj.getHyphenationLadderCount();
        wrapOption = fobj.getWrapOption();
        whiteSpaceTreament = fobj.getWhitespaceTreatment();
        //
        effectiveAlignment = getEffectiveAlignment(textAlignment, textAlignmentLast);
        isFirstInBlock = (this == getParent().getChildLMs().get(0));
    }

    private int getEffectiveAlignment(int alignment, int alignmentLast) {
        if (textAlignment != EN_JUSTIFY && textAlignmentLast == EN_JUSTIFY) {
            return 0;
        } else {
            return textAlignment;
        }
    }

    /** {@inheritDoc} */
    @Override
    public List<ListElement> getNextKnuthElements(LayoutContext context, int alignment) {
        if (alignmentContext == null) {
            FontInfo fi = fobj.getFOEventHandler().getFontInfo();
            FontTriplet[] fontkeys = fobj.getCommonFont().getFontState(fi);
            Font fs = fi.getFontInstance(fontkeys[0], fobj.getCommonFont().fontSize.getValue(this));
            alignmentContext = new AlignmentContext(fs, lineHeight.getValue(this),
                    context.getWritingMode());
        }
        context.setAlignmentContext(alignmentContext);
        ipd = context.getRefIPD();

        //PHASE 1: Create Knuth elements
        if (knuthParagraphs == null) {
            // it's the first time this method is called
            knuthParagraphs = new ArrayList<KnuthSequence>();

            // here starts Knuth's algorithm
            collectInlineKnuthElements(context);
        } else {
            // this method has been called before
            // all line breaks are already calculated
        }

        // return finished when there's no content
        if (knuthParagraphs.size() == 0) {
            setFinished(true);
            return null;
        }

        //PHASE 2: Create line breaks
        return createLineBreaks(context.getBPAlignment(), context);
    }

    /**
     * Get a sequence of KnuthElements representing the content
     * of the node assigned to the LM.
     * @param context   the LayoutContext used to store layout information
     * @param alignment the desired text alignment
     * @param restartPosition position at restart
     * @return the list of KnuthElements
     * @see LayoutManager#getNextKnuthElements(LayoutContext,int)
     */
    public List<ListElement> getNextKnuthElements(LayoutContext context, int alignment,
            LeafPosition restartPosition) {
        int parIndex = 0;
        int restartPositionIdx = 0;
        if (restartPosition != null) {
            log.trace("Restarting line breaking from index " + restartPosition.getIndex());
            parIndex = restartPosition.getLeafPos();
            restartPositionIdx = restartPosition.getIndex();
        }

        for (int i = 0; i < parIndex; i++) {
            if (knuthParagraphs.size() > 1) {
                knuthParagraphs.remove(0);
            }
        }
        parIndex = 0;

        KnuthSequence paragraph = knuthParagraphs.get(parIndex);
        if (paragraph instanceof Paragraph) {
            ((Paragraph) paragraph).ignoreAtStart = 0;
            isFirstInBlock = false;
        }
        paragraph.subList(0, restartPositionIdx + 1).clear();
        Iterator<KnuthElement> iter = paragraph.iterator();
        while (iter.hasNext() && !iter.next().isBox()) {
            iter.remove();
        }
        if (!iter.hasNext()) {
            knuthParagraphs.remove(parIndex);
        }

        // return finished when there's no content
        if (knuthParagraphs.size() == 0) {
            setFinished(true);
            return null;
        }

        ipd = context.getRefIPD();
        //PHASE 2: Create line breaks
        return createLineBreaks(context.getBPAlignment(), context);
    }

    /**
     * Phase 1 of Knuth algorithm: Collect all inline Knuth elements before determining line breaks.
     * @param context the LayoutContext
     */
    private void collectInlineKnuthElements(LayoutContext context) {
        LayoutContext inlineLC = LayoutContext.copyOf(context);

        // convert all the text in a sequence of paragraphs made
        // of KnuthBox, KnuthGlue and KnuthPenalty objects
        boolean previousIsBox = false;

        StringBuffer trace = new StringBuffer("LineLM:");

        Paragraph lastPar = null;

        InlineLevelLayoutManager curLM;
        while ((curLM = (InlineLevelLayoutManager) getChildLM()) != null) {
            List<KnuthSequence> inlineElements = curLM.getNextKnuthElements(inlineLC, effectiveAlignment);
            if (inlineElements == null || inlineElements.size() == 0) {
                /* curLM.getNextKnuthElements() returned null or an empty list;
                 * this can happen if there is nothing more to layout,
                 * so just iterate once more to see if there are other children */
                continue;
            }

            if (lastPar != null) {
                KnuthSequence firstSeq = inlineElements.get(0);

                // finish last paragraph before a new block sequence
                if (!firstSeq.isInlineSequence()) {
                    lastPar.endParagraph();
                    ElementListObserver.observe(lastPar, "line", null);
                    lastPar = null;
                    if (log.isTraceEnabled()) {
                        trace.append(" ]");
                    }
                    previousIsBox = false;
                }

                // does the first element of the first paragraph add to an existing word?
                if (lastPar != null) {
                    KnuthElement thisElement;
                    thisElement = (KnuthElement) firstSeq.get(0);
                    if (thisElement.isBox() && !thisElement.isAuxiliary()
                            && previousIsBox) {
                        lastPar.addALetterSpace();
                    }
                }
            }

            // loop over the KnuthSequences (and single KnuthElements) in returnedList
            for (Object inlineElement : inlineElements) {
                KnuthSequence sequence = (KnuthSequence) inlineElement;
                // the sequence contains inline Knuth elements
                if (sequence.isInlineSequence()) {
                    // look at the last element
                    ListElement lastElement = sequence.getLast();
                    assert lastElement != null;
                    previousIsBox = lastElement.isBox()
                            && !((KnuthElement) lastElement).isAuxiliary()
                            && ((KnuthElement) lastElement).getWidth() != 0;

                    // if last paragraph is open, add the new elements to the paragraph
                    // else this is the last paragraph
                    if (lastPar == null) {
                        lastPar = new Paragraph(this,
                                textAlignment, textAlignmentLast,
                                textIndent.getValue(this),
                                lastLineEndIndent.getValue(this));
                        lastPar.startSequence();
                        if (log.isTraceEnabled()) {
                            trace.append(" [");
                        }
                    } else {
                        if (log.isTraceEnabled()) {
                            trace.append(" +");
                        }
                    }
                    lastPar.addAll(sequence);
                    if (log.isTraceEnabled()) {
                        trace.append(" I");
                    }

                    // finish last paragraph if it was closed with a linefeed
                    if (lastElement.isPenalty()
                            && ((KnuthPenalty) lastElement).getPenalty()
                            == -KnuthPenalty.INFINITE) {
                        // a penalty item whose value is -inf
                        // represents a preserved linefeed,
                        // which forces a line break
                        lastPar.removeLast();
                        if (!lastPar.containsBox()) {
                            //only a forced linefeed on this line
                            //-> compensate with an auxiliary glue
                            lastPar.add(new KnuthGlue(ipd, 0, ipd, null, true));
                        }
                        lastPar.endParagraph();
                        ElementListObserver.observe(lastPar, "line", null);
                        lastPar = null;
                        if (log.isTraceEnabled()) {
                            trace.append(" ]");
                        }
                        previousIsBox = false;
                    }
                } else { // the sequence is a block sequence
                    // the positions will be wrapped with this LM in postProcessLineBreaks
                    knuthParagraphs.add(sequence);
                    if (log.isTraceEnabled()) {
                        trace.append(" B");
                    }
                }
            } // end of loop over returnedList
        }

        if (lastPar != null) {
            lastPar.endParagraph();
            ElementListObserver.observe(lastPar, "line", fobj.getId());
            if (log.isTraceEnabled()) {
                trace.append(" ]");
            }
        }
        log.trace(trace);
    }

    /**
     * Phase 2 of Knuth algorithm: find optimal break points.
     * @param alignment alignment in BP direction of the paragraph
     * @param context the layout context
     * @return a list of Knuth elements representing broken lines
     */
    private List<ListElement> createLineBreaks(int alignment, LayoutContext context) {
        // find the optimal line breaking points for each paragraph
        Iterator<KnuthSequence> paragraphsIterator = knuthParagraphs.iterator();
        lineLayoutsList = new LineLayoutPossibilities[knuthParagraphs.size()];
        LineLayoutPossibilities llPoss;
        for (int i = 0; paragraphsIterator.hasNext(); i++) {
            KnuthSequence seq = paragraphsIterator.next();
            if (!seq.isInlineSequence()) {
                // This set of line layout possibilities does not matter;
                // we only need an entry in lineLayoutsList.
                llPoss = new LineLayoutPossibilities();
            } else {
                llPoss = findOptimalBreakingPoints(alignment, (Paragraph) seq,
                                                   !paragraphsIterator.hasNext());
            }
            lineLayoutsList[i] = llPoss;
        }

        setFinished(true);

        //Post-process the line breaks found
        return postProcessLineBreaks(alignment, context);
    }

    /**
     * Find the optimal linebreaks for a paragraph
     * @param alignment alignment of the paragraph
     * @param currPar the Paragraph for which the linebreaks are found
     * @param isLastPar flag indicating whether currPar is the last paragraph
     * @return the line layout possibilities for the paragraph
     */
    private LineLayoutPossibilities findOptimalBreakingPoints(int alignment, Paragraph currPar,
                                                              boolean isLastPar) {
        // use the member lineLayouts, which is read by LineBreakingAlgorithm.updateData1 and 2
        lineLayouts = new LineLayoutPossibilities();
        double maxAdjustment = 1;
        LineBreakingAlgorithm alg = new LineBreakingAlgorithm(alignment,
                                        textAlignment, textAlignmentLast,
                                        textIndent.getValue(this), currPar.lineFiller.getOpt(),
                                        lineHeight.getValue(this), lead, follow,
                                        (knuthParagraphs.indexOf(currPar) == 0),
                                        hyphenationLadderCount.getEnum() == EN_NO_LIMIT
                                            ? 0 : hyphenationLadderCount.getValue(),
                                        this);
        alg.setConstantLineWidth(ipd);
        boolean canWrap = (wrapOption != EN_NO_WRAP);
        boolean canHyphenate = (canWrap && hyphenationProperties.hyphenate.getEnum() == EN_TRUE);

        // find hyphenation points, if allowed and not yet done
        if (canHyphenate && !hyphenationPerformed) {
            // make sure findHyphenationPoints() is bypassed if
            // the method is called twice (e.g. due to changing page-ipd)
            hyphenationPerformed = isLastPar;
            findHyphenationPoints(currPar);
        }

        // first try: do not consider hyphenation points as legal breaks
        int allowedBreaks = (canWrap ? BreakingAlgorithm.NO_FLAGGED_PENALTIES
                : BreakingAlgorithm.ONLY_FORCED_BREAKS);
        int breakingPoints = alg.findBreakingPoints(currPar, maxAdjustment, false, allowedBreaks);

        if (breakingPoints == 0 || alignment == EN_JUSTIFY) {
            // if the first try found a set of breaking points, save them
            if (breakingPoints > 0) {
                alg.resetAlgorithm();
                lineLayouts.savePossibilities(false);
            } else {
                // the first try failed
                log.debug("No set of breaking points found with maxAdjustment = " + maxAdjustment);
            }

            // now try something different
            log.debug("Hyphenation possible? " + canHyphenate);
            boolean simpleLineBreaking = fobj.getUserAgent().isSimpleLineBreaking();

            // Note: if allowedBreaks is guaranteed to be unchanged by alg.findBreakingPoints(),
            // the below check can be simplified to 'if (canHyphenate) ...'
            if (canHyphenate && allowedBreaks != BreakingAlgorithm.ONLY_FORCED_BREAKS) {
                // consider every hyphenation point as a legal break
                allowedBreaks = BreakingAlgorithm.ALL_BREAKS;
            } else if (!simpleLineBreaking) {
                // try with a higher threshold
                maxAdjustment = 5;
            }

            breakingPoints = alg.findBreakingPoints(currPar, maxAdjustment, false, allowedBreaks);
            if (breakingPoints == 0) {
                // the second try failed too, try with a huge threshold
                // and force the algorithm to find a set of breaking points
                if (log.isDebugEnabled()) {
                    log.debug("No set of breaking points found with maxAdjustment = "
                            + maxAdjustment + (canHyphenate ? " and hyphenation" : ""));
                }
                if (!simpleLineBreaking) {
                    maxAdjustment = 20;
                }
                alg.findBreakingPoints(currPar, maxAdjustment, true, allowedBreaks);
            }

            // use non-hyphenated breaks, when possible
            lineLayouts.restorePossibilities();
        }

        return lineLayouts;
    }

    /**
     * Creates the element list in BP direction for the broken lines.
     * @param alignment the currently applicable vertical alignment
     * @param context the layout context
     * @return the newly built element list
     */
    private List<ListElement> postProcessLineBreaks(int alignment, LayoutContext context) {

        List<ListElement> returnList = new LinkedList<>();

        int endIndex = -1;
        for (int p = 0; p < knuthParagraphs.size(); p++) {
            // penalty between paragraphs
            if (p > 0) {
                Keep keep = getKeepTogether();
                returnList.add(new BreakElement(
                            new Position(this),
                            keep.getPenalty(),
                            keep.getContext(),
                            context));
            }

            LineLayoutPossibilities llPoss = lineLayoutsList[p];
            KnuthSequence seq = knuthParagraphs.get(p);

            if (!seq.isInlineSequence()) {
                List<ListElement> targetList = new LinkedList<ListElement>();
                for (Object aSeq : seq) {
                    ListElement tempElement;
                    tempElement = (ListElement) aSeq;
                    LayoutManager lm = tempElement.getLayoutManager();
                    if (baselineOffset < 0 && lm != null && lm.hasLineAreaDescendant()) {
                        baselineOffset = lm.getBaselineOffset();
                    }
                    if (lm != this) {
                        tempElement.setPosition(notifyPos(new NonLeafPosition(this,
                                tempElement.getPosition())));
                    }
                    targetList.add(tempElement);
                }
                returnList.addAll(targetList);
            } else if (seq.isInlineSequence() && alignment == EN_JUSTIFY) {
                /* justified vertical alignment (not in the XSL FO recommendation):
                   create a multi-layout sequence whose elements will contain
                   a conventional Position */
                Position returnPosition = new LeafPosition(this, p);
                createElements(returnList, llPoss, returnPosition);
            } else {
                /* "normal" vertical alignment: create a sequence whose boxes
                   represent effective lines, and contain LineBreakPositions */
                int startIndex = 0;
                int previousEndIndex = 0;
                for (int i = 0;
                        i < llPoss.getChosenLineCount();
                        i++) {
                    int orphans = fobj.getOrphans();
                    int widows = fobj.getWidows();
                    if (handlingFloat()) {
                        orphans = 1;
                        widows = 1;
                    }
                    if (returnList.size() > 0
                            && i > 0 //if i==0 break generated above already
                            && i >= orphans && i <= llPoss.getChosenLineCount() - widows) {
                        // penalty allowing a page break between lines
                        Keep keep = getKeepTogether();
                        returnList.add(new BreakElement(
                                new LeafPosition(this, p, endIndex),
                                    keep.getPenalty(),
                                    keep.getContext(),
                                    context));
                    }
                    endIndex = llPoss.getChosenPosition(i).getLeafPos();
                    // create a list of the FootnoteBodyLM handling footnotes
                    // whose citations are in this line
                    List<FootnoteBodyLayoutManager> footnoteList = FootenoteUtil.getFootnotes(
                            seq, startIndex, endIndex);
                    List<FloatContentLayoutManager> floats = FloatContentLayoutManager.checkForFloats(seq,
                            startIndex, endIndex);
                    startIndex = endIndex + 1;
                    LineBreakPosition lbp = llPoss.getChosenPosition(i);
                    if (baselineOffset < 0) {
                        baselineOffset = lbp.spaceBefore + lbp.baseline;
                    }
                    if (floats.isEmpty()) {
                        returnList.add(new KnuthBlockBox(lbp.lineHeight + lbp.spaceBefore + lbp.spaceAfter,
                                footnoteList, lbp, false));
                    } else {
                        // add a line with height zero and no content and attach float to it
                        returnList.add(new KnuthBlockBox(0, Collections.emptyList(), null, false, floats));
                        // add a break element to signal that we should restart LB at this break
                        Keep keep = getKeepTogether();
                        returnList.add(new BreakElement(new LeafPosition(this, p, previousEndIndex), keep
                                .getPenalty(), keep.getContext(), context));
                        // add the original line where the float was but without the float now
                        returnList.add(new KnuthBlockBox(lbp.lineHeight + lbp.spaceBefore + lbp.spaceAfter,
                                footnoteList, lbp, false));
                    }
                    previousEndIndex = endIndex;
                }
            }
        }

        return returnList;
    }

    private void createElements(List<ListElement> list, LineLayoutPossibilities llPoss,
                                Position elementPosition) {
        /* number of normal, inner lines */
        int innerLines = 0;
        /* number of lines that can be used in order to fill more space */
        int optionalLines = 0;
        /* number of lines that can be used in order to fill more space
           only if the paragraph is not parted */
        int conditionalOptionalLines = 0;
        /* number of lines that can be omitted in order to fill less space */
        int eliminableLines = 0;
        /* number of lines that can be omitted in order to fill less space
           only if the paragraph is not parted */
        int conditionalEliminableLines = 0;
        /* number of the first unbreakable lines */
        int firstLines = fobj.getOrphans();
        /* number of the last unbreakable lines */
        int lastLines = fobj.getWidows();
        /* sub-sequence used to separate the elements representing different lines */
        List<KnuthElement> breaker = new LinkedList<KnuthElement>();

        /* comment out the next lines in order to test particular situations */
        if (fobj.getOrphans() + fobj.getWidows() <= llPoss.getMinLineCount()) {
            innerLines = llPoss.getMinLineCount() - (fobj.getOrphans() + fobj.getWidows());
            optionalLines = llPoss.getMaxLineCount() - llPoss.getOptLineCount();
            eliminableLines = llPoss.getOptLineCount() - llPoss.getMinLineCount();
        } else if (fobj.getOrphans() + fobj.getWidows() <= llPoss.getOptLineCount()) {
            optionalLines = llPoss.getMaxLineCount() - llPoss.getOptLineCount();
            eliminableLines = llPoss.getOptLineCount() - (fobj.getOrphans() + fobj.getWidows());
            conditionalEliminableLines
                    = (fobj.getOrphans() + fobj.getWidows()) - llPoss.getMinLineCount();
        } else if (fobj.getOrphans() + fobj.getWidows() <= llPoss.getMaxLineCount()) {
            optionalLines = llPoss.getMaxLineCount() - (fobj.getOrphans() + fobj.getWidows());
            conditionalOptionalLines
                    = (fobj.getOrphans() + fobj.getWidows()) - llPoss.getOptLineCount();
            conditionalEliminableLines = llPoss.getOptLineCount() - llPoss.getMinLineCount();
            firstLines -= conditionalOptionalLines;
        } else {
            conditionalOptionalLines = llPoss.getMaxLineCount() - llPoss.getOptLineCount();
            conditionalEliminableLines = llPoss.getOptLineCount() - llPoss.getMinLineCount();
            firstLines = llPoss.getOptLineCount();
            lastLines = 0;
        }
        /* comment out the previous lines in order to test particular situations */

        /* use these lines to test particular situations
        innerLines = 0;
        optionalLines = 1;
        conditionalOptionalLines = 2;
        eliminableLines = 0;
        conditionalEliminableLines = 0;
        firstLines = 1;
        lastLines = 3;
        */

        if (lastLines != 0
            && (conditionalOptionalLines > 0 || conditionalEliminableLines > 0)) {
            breaker.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
            breaker.add(new KnuthGlue(0, -conditionalOptionalLines * constantLineHeight,
                                        -conditionalEliminableLines * constantLineHeight,
                                        Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
            breaker.add(new KnuthPenalty(conditionalOptionalLines * constantLineHeight,
                                           0, false, elementPosition, false));
            breaker.add(new KnuthGlue(0, conditionalOptionalLines * constantLineHeight,
                                        conditionalEliminableLines * constantLineHeight,
                                        Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
        } else if (lastLines != 0) {
            breaker.add(new KnuthPenalty(0, 0, false, elementPosition, false));
        }

        // creation of the elements:
        // first group of lines
        list.add(new KnuthBox(firstLines * constantLineHeight, elementPosition,
                              (lastLines == 0
                               && conditionalOptionalLines == 0
                               && conditionalEliminableLines == 0)));
        if (conditionalOptionalLines > 0
            || conditionalEliminableLines > 0) {
            list.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
            list.add(new KnuthGlue(0, conditionalOptionalLines * constantLineHeight,
                                   conditionalEliminableLines * constantLineHeight,
                                   Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
            list.add(new KnuthBox(0, elementPosition, (lastLines == 0)));
        }

        // optional lines
        for (int i = 0; i < optionalLines; i++) {
            list.addAll(breaker);
            list.add(new KnuthBox(0, elementPosition, false));
            list.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
            list.add(new KnuthGlue(0, constantLineHeight, 0,
                                   Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
            list.add(new KnuthBox(0, elementPosition, false));
        }

        // eliminable lines
        for (int i = 0; i < eliminableLines; i++) {
            list.addAll(breaker);
            list.add(new KnuthBox(constantLineHeight, elementPosition, false));
            list.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
            list.add(new KnuthGlue(0, 0, constantLineHeight,
                                   Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
            list.add(new KnuthBox(0, elementPosition, false));
        }

        // inner lines
        for (int i = 0; i < innerLines; i++) {
            list.addAll(breaker);
            list.add(new KnuthBox(constantLineHeight, elementPosition, false));
        }

        // last group of lines
        if (lastLines > 0) {
            list.addAll(breaker);
            list.add(new KnuthBox(lastLines * constantLineHeight,
                                  elementPosition, true));
        }
    }

    /** {@inheritDoc} */
    public boolean mustKeepTogether() {
        return ((BlockLevelLayoutManager) getParent()).mustKeepTogether();
    }

    /** {@inheritDoc} */
    public KeepProperty getKeepTogetherProperty() {
        return ((BlockLevelLayoutManager) getParent()).getKeepTogetherProperty();
    }

    /** {@inheritDoc} */
    public KeepProperty getKeepWithPreviousProperty() {
        return ((BlockLevelLayoutManager) getParent()).getKeepWithPreviousProperty();
    }

    /** {@inheritDoc} */
    public KeepProperty getKeepWithNextProperty() {
        return ((BlockLevelLayoutManager) getParent()).getKeepWithNextProperty();
    }

    /** {@inheritDoc} */
    public Keep getKeepTogether() {
        return ((BlockLevelLayoutManager) getParent()).getKeepTogether();
    }

    /** {@inheritDoc} */
    public boolean mustKeepWithPrevious() {
        return !getKeepWithPrevious().isAuto();
    }

    /** {@inheritDoc} */
    public boolean mustKeepWithNext() {
        return !getKeepWithNext().isAuto();
    }

    /** {@inheritDoc} */
    public Keep getKeepWithNext() {
        return Keep.KEEP_AUTO;
    }

    /** {@inheritDoc} */
    public Keep getKeepWithPrevious() {
        return Keep.KEEP_AUTO;
    }

    /** {@inheritDoc} */
    public int negotiateBPDAdjustment(int adj, KnuthElement lastElement) {
        Position lastPos = lastElement.getPosition();
        assert (lastPos instanceof LeafPosition);
        LeafPosition pos = (LeafPosition) lastPos;
        //if (lastElement.isPenalty()) {
        //    totalAdj += lastElement.getWidth();
        //}
        //int lineNumberDifference = (int)((double) totalAdj / constantLineHeight);
        int lineNumberDifference = (int) Math.round((double) adj / constantLineHeight
                                                    + (adj > 0 ? -0.4 : 0.4));
        //log.debug("   LLM> variazione calcolata = " + ((double) totalAdj / constantLineHeight)
        //+ " variazione applicata = " + lineNumberDifference);
        LineLayoutPossibilities llPoss;
        llPoss = lineLayoutsList[pos.getLeafPos()];
        lineNumberDifference = llPoss.applyLineCountAdjustment(lineNumberDifference);
        return lineNumberDifference * constantLineHeight;
    }

    /** {@inheritDoc} */
    public void discardSpace(KnuthGlue spaceGlue) {
    }

    /** {@inheritDoc} */
    @Override
    public List<ListElement> getChangedKnuthElements(List<ListElement> oldList, int alignment, int depth) {
        return getChangedKnuthElements(oldList, alignment);
    }

    /** {@inheritDoc} */
    @Override
    public List<ListElement> getChangedKnuthElements(List<ListElement> oldList, int alignment) {
        List<ListElement> returnList = new LinkedList<>();
        for (int p = 0; p < knuthParagraphs.size(); p++) {
            LineLayoutPossibilities llPoss = lineLayoutsList[p];
            //log.debug("demerits of the chosen layout: " + llPoss.getChosenDemerits());
            int orphans = fobj.getOrphans();
            int widows = fobj.getWidows();
            if (handlingFloat()) {
                orphans = 1;
                widows = 1;
            }
            for (int i = 0; i < llPoss.getChosenLineCount(); i++) {
                if (!((BlockLevelLayoutManager) parentLayoutManager).mustKeepTogether() && i >= orphans
                        && i <= llPoss.getChosenLineCount() - widows) {
                    // null penalty allowing a page break between lines
                    returnList.add(new KnuthPenalty(0, 0, false, new Position(this), false));
                }
                LineBreakPosition lbp = llPoss.getChosenPosition(i);
                //log.debug("LLM.getChangedKnuthElements> lineWidth= "
                // + lbp.lineWidth + " difference= " + lbp.difference);
                //log.debug("                             shrink= "
                // + lbp.availableShrink + " stretch= " + lbp.availableStretch);
                //log.debug("linewidth= " + lbp.lineWidth + " difference= "
                //+ lbp.difference + " indent= " + lbp.startIndent);
                MinOptMax contentIPD;
                if (alignment == EN_JUSTIFY) {
                    contentIPD = MinOptMax.getInstance(
                        lbp.lineWidth - lbp.difference - lbp.availableShrink,
                        lbp.lineWidth - lbp.difference,
                        lbp.lineWidth - lbp.difference + lbp.availableStretch);
                } else if (alignment == EN_CENTER) {
                    contentIPD = MinOptMax.getInstance(lbp.lineWidth - 2 * lbp.startIndent);
                } else if (alignment == EN_END) {
                    contentIPD = MinOptMax.getInstance(lbp.lineWidth - lbp.startIndent);
                } else {
                    contentIPD
                        = MinOptMax.getInstance(lbp.lineWidth - lbp.difference + lbp.startIndent);
                }
                returnList.add(new KnuthBlockBox(lbp.lineHeight, contentIPD, (lbp.ipdAdjust != 0
                        ? lbp.lineWidth - lbp.difference : 0),
                                                 lbp, false));
            }
        }
        return returnList;
    }

    /**
     * Find hyphenation points for every word in the current paragraph.
     *
     * @param currPar the paragraph whose words will be hyphenated
     */
    private void findHyphenationPoints(Paragraph currPar) {
        // hyphenate every word
        ListIterator currParIterator = currPar.listIterator(currPar.ignoreAtStart);
        // list of TLM involved in hyphenation
        List<Update> updateList = new LinkedList<>();
        KnuthElement firstElement;
        KnuthElement nextElement;
        // current InlineLevelLayoutManager
        InlineLevelLayoutManager currLM = null;
        // number of KnuthBox elements containing word fragments
        int boxCount;
        // number of auxiliary KnuthElements between KnuthBoxes
        int auxCount;
        StringBuffer sbChars;

        // find all hyphenation points
        while (currParIterator.hasNext()) {
            firstElement = (KnuthElement) currParIterator.next();
            //
            if (firstElement.getLayoutManager() != currLM) {
                currLM = (InlineLevelLayoutManager) firstElement.getLayoutManager();
                if (currLM != null) {
                    updateList.add(new Update(currLM, currParIterator.previousIndex()));
                } else {
                    break;
                }
            } else if (currLM == null) {
                break;
            }

            // collect word fragments, ignoring auxiliary elements;
            // each word fragment was created by a different TextLM
            if (firstElement.isBox() && !firstElement.isAuxiliary()) {
                boxCount = 1;
                auxCount = 0;
                sbChars = new StringBuffer();
                sbChars.append(currLM.getWordChars(firstElement.getPosition()));
                // look if next elements are boxes too
                while (currParIterator.hasNext()) {
                    nextElement = (KnuthElement) currParIterator.next();
                    if (nextElement.isBox() && !nextElement.isAuxiliary()) {
                        // a non-auxiliary KnuthBox: append word chars
                        if (currLM != nextElement.getLayoutManager()) {
                            currLM = (InlineLevelLayoutManager) nextElement.getLayoutManager();
                            updateList.add(new Update(currLM, currParIterator.previousIndex()));
                        }
                        // append text to recreate the whole word
                        boxCount++;
                        sbChars.append(currLM.getWordChars(nextElement.getPosition()));
                    } else if (!nextElement.isAuxiliary()) {
                        // a non-auxiliary non-box KnuthElement: stop
                        // go back to the last box or auxiliary element
                        currParIterator.previous();
                        break;
                    } else {
                        if (currLM != nextElement.getLayoutManager()) {
                            currLM = (InlineLevelLayoutManager) nextElement.getLayoutManager();
                            updateList.add(new Update(currLM, currParIterator.previousIndex()));
                        }
                        // an auxiliary KnuthElement: simply ignore it
                        auxCount++;
                    }
                }
                if (log.isTraceEnabled()) {
                    log.trace(" Word to hyphenate: " + sbChars);
                }
                // find hyphenation points
                HyphContext hc = getHyphenContext(sbChars);
                // ask each LM to hyphenate its word fragment
                if (hc != null) {
                    KnuthElement element = null;
                    for (int i = 0; i < (boxCount + auxCount); i++) {
                        currParIterator.previous();
                    }
                    for (int i = 0; i < (boxCount + auxCount); i++) {
                        element = (KnuthElement) currParIterator.next();
                        if (element.isBox() && !element.isAuxiliary()) {
                            ((InlineLevelLayoutManager)
                             element.getLayoutManager()).hyphenate(element.getPosition(), hc);
                        } else {
                            // nothing to do, element is an auxiliary KnuthElement
                        }
                    }
                }
            }
        }
        processUpdates(currPar, updateList);
    }

    private void processUpdates(Paragraph par, List<Update> updateList) {
        // create iterator for the updateList
        ListIterator updateListIterator = updateList.listIterator();
        Update currUpdate;
        int elementsAdded = 0;

        while (updateListIterator.hasNext()) {
            // ask the LMs to apply the changes and return
            // the new KnuthElements to replace the old ones
            currUpdate = (Update) updateListIterator.next();
            int fromIndex = currUpdate.firstIndex;
            int toIndex;
            if (updateListIterator.hasNext()) {
                Update nextUpdate = (Update) updateListIterator.next();
                toIndex = nextUpdate.firstIndex;
                updateListIterator.previous();
            } else {
                // maybe this is not always correct!
                toIndex = par.size() - par.ignoreAtEnd
                    - elementsAdded;
            }

            // applyChanges() returns true if the LM modifies its data,
            // so it must return new KnuthElements to replace the old ones
            if (currUpdate.inlineLM
                .applyChanges(par.subList(fromIndex + elementsAdded,
                                              toIndex + elementsAdded))) {
                // insert the new KnuthElements
                List<ListElement> newElements = currUpdate.inlineLM.getChangedKnuthElements(
                    par.subList(fromIndex + elementsAdded,
                                     toIndex + elementsAdded),
                     /*flaggedPenalty,*/ effectiveAlignment);
                // remove the old elements
                par.subList(fromIndex + elementsAdded,
                                toIndex + elementsAdded).clear();
                // insert the new elements
                par.addAll(fromIndex + elementsAdded, newElements);
                elementsAdded += newElements.size() - (toIndex - fromIndex);
            }
        }
        updateList.clear();
    }

    /**
     * Line area is always considered to act as a fence.
     * @param isNotFirst ignored
     * @return always true
     */
    @Override
    protected boolean hasLeadingFence(boolean isNotFirst) {
        return true;
    }

    /**
     * Line area is always considered to act as a fence.
     * @param isNotLast ignored
     * @return always true
     */
    @Override
    protected boolean hasTrailingFence(boolean isNotLast) {
        return true;
    }

    private HyphContext getHyphenContext(StringBuffer sbChars) {
        // Find all hyphenation points in this word
        // (get in an array of offsets)
        // hyphenationProperties are from the block level?.
        // Note that according to the spec,
        // they also "apply to" fo:character.
        // I don't know what that means, since
        // if we change language in the middle of a "word",
        // the effect would seem quite strange!
        // Or perhaps in that case, we say that it's several words.
        // We probably should bring the hyphenation props up from the actual
        // TextLM which generate the hyphenation buffer,
        // since these properties inherit and could be specified
        // on an inline or wrapper below the block level.
        Hyphenation hyph = Hyphenator.hyphenate(hyphenationProperties.language.getString(),
                               hyphenationProperties.country.getString(),
                               getFObj().getUserAgent().getHyphenationResourceResolver(),
                               getFObj().getUserAgent().getHyphenationPatternNames(),
                               sbChars.toString(),
                               hyphenationProperties.hyphenationRemainCharacterCount.getValue(),
                               hyphenationProperties.hyphenationPushCharacterCount.getValue(),
                               getFObj().getUserAgent());
        // They hyph structure contains the information we need
        // Now start from prev: reset to that position, ask that LM to get
        // a Position for the first hyphenation offset. If the offset isn't in
        // its characters, it returns null,
        // but must tell how many chars it had.
        // Keep looking at currentBP using next hyphenation point until the
        // returned size is greater than the available size
        // or no more hyphenation points remain. Choose the best break.
        if (hyph != null) {
            return new HyphContext(hyph.getHyphenationPoints());
        } else {
            return null;
        }
    }

    @Override
    public boolean hasLineAreaDescendant() {
        return true;
    }

    @Override
    public int getBaselineOffset() {
        return baselineOffset;
    }

    /**
     * Add the areas with the break points.
     *
     * @param parentIter the iterator of break positions
     * @param context the context for adding areas
     */
    @Override
    public void addAreas(PositionIterator parentIter,
                         LayoutContext context) {
        while (parentIter.hasNext()) {
            Position pos = parentIter.next();
            boolean isLastPosition = !parentIter.hasNext();
            if (pos instanceof LineBreakPosition) {
                addInlineArea(context, (LineBreakPosition) pos, isLastPosition);
            } else if ((pos instanceof NonLeafPosition) && pos.generatesAreas()) {
                addBlockArea(context, pos, isLastPosition);
            } else {
                /*
                 * pos was the Position inside a penalty item, nothing to do;
                 * or Pos does not generate an area,
                 * i.e. it stand for spaces, borders and padding.
                 */
            }
        }
        setCurrentArea(null); // ?? necessary
    }

    /**
     * Add a line with inline content
     * @param context the context for adding areas
     * @param lbp the position for which the line is generated
     * @param isLastPosition true if this is the last position of this LM
     */
    private void addInlineArea(LayoutContext context, LineBreakPosition lbp,
            boolean isLastPosition) {

        KnuthSequence seq = knuthParagraphs.get(lbp.parIndex);
        int startElementIndex = lbp.startIndex;
        int endElementIndex = lbp.getLeafPos();

        LineArea lineArea = new LineArea(
                (lbp.getLeafPos() < seq.size() - 1 ? textAlignment : textAlignmentLast),
                lbp.difference, lbp.availableStretch, lbp.availableShrink);
        lineArea.setChangeBarList(getChangeBarList());

        if (lbp.startIndent != 0) {
            lineArea.addTrait(Trait.START_INDENT, lbp.startIndent);
        }
        if (lbp.endIndent != 0) {
            lineArea.addTrait(Trait.END_INDENT, lbp.endIndent);
        }
        lineArea.setBPD(lbp.lineHeight);
        lineArea.setIPD(lbp.lineWidth);
        lineArea.setBidiLevel(bidiLevel);
        lineArea.addTrait(Trait.SPACE_BEFORE, lbp.spaceBefore);
        lineArea.addTrait(Trait.SPACE_AFTER, lbp.spaceAfter);
        alignmentContext.resizeLine(lbp.lineHeight, lbp.baseline);

        if (seq instanceof Paragraph) {
            Paragraph currPar = (Paragraph) seq;
            // ignore the first elements added by the LineLayoutManager
            startElementIndex += (startElementIndex == 0) ? currPar.ignoreAtStart : 0;

            // if this is the last line area that for this paragraph,
            // ignore the last elements added by the LineLayoutManager and
            // subtract the last-line-end-indent from the area ipd
            if (endElementIndex == (currPar.size() - 1)) {
                endElementIndex -= currPar.ignoreAtEnd;
                lineArea.setIPD(lineArea.getIPD() - lastLineEndIndent.getValue(this));
            }
        }

        // ignore the last element in the line if it is a KnuthGlue object
        ListIterator seqIterator = seq.listIterator(endElementIndex);
        KnuthElement lastElement = (KnuthElement) seqIterator.next();
        // the TLM which created the last KnuthElement in this line
        LayoutManager lastLM = lastElement.getLayoutManager();
        if (lastElement.isGlue()) {
            // Remove trailing spaces if allowed so
            if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED
                    || whiteSpaceTreament == EN_IGNORE
                    || whiteSpaceTreament == EN_IGNORE_IF_BEFORE_LINEFEED) {
                endElementIndex--;
                // this returns the same KnuthElement
                seqIterator.previous();
                if (seqIterator.hasPrevious()) {
                    lastLM = ((KnuthElement) seqIterator.previous()).getLayoutManager();
                }
            }
        }

        // Remove leading spaces if allowed so
        if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED
                || whiteSpaceTreament == EN_IGNORE
                || whiteSpaceTreament == EN_IGNORE_IF_AFTER_LINEFEED) {
            // ignore KnuthGlue and KnuthPenalty objects
            // at the beginning of the line
            seqIterator = seq.listIterator(startElementIndex);
            while (seqIterator.hasNext() && !((KnuthElement) seqIterator.next()).isBox()) {
                startElementIndex++;
            }
        }
        // Add the inline areas to lineArea
        PositionIterator inlinePosIter = new KnuthPossPosIter(seq, startElementIndex,
                endElementIndex + 1);

        LayoutContext lc = LayoutContext.offspringOf(context);
        lc.setAlignmentContext(alignmentContext);
        lc.setSpaceAdjust(lbp.dAdjust);
        lc.setIPDAdjust(lbp.ipdAdjust);
        lc.setLeadingSpace(new SpaceSpecifier(true));
        lc.setTrailingSpace(new SpaceSpecifier(false));
        lc.setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);

        setCurrentArea(lineArea);
        setChildContext(lc);
        LayoutManager childLM;
        while ((childLM = inlinePosIter.getNextChildLM()) != null) {
            lc.setFlags(LayoutContext.LAST_AREA, (childLM == lastLM));
            childLM.addAreas(inlinePosIter, lc);
            lc.setLeadingSpace(lc.getTrailingSpace());
            lc.setTrailingSpace(new SpaceSpecifier(false));
        }

        // if display-align is distribute, add space after
        if (context.getSpaceAfter() > 0
                && (!context.isLastArea() || !isLastPosition)) {
            lineArea.setBPD(lineArea.getBPD() + context.getSpaceAfter());
        }
        lineArea.finish();
        if (lineArea.getBidiLevel() >= 0) {
            BidiResolver.reorder(lineArea);
        }
        parentLayoutManager.addChildArea(lineArea);
    }

    /**
     * Add a line with block content
     * @param context the context for adding areas
     * @param pos the position for which the line is generated
     * @param isLastPosition true if this is the last position of this LM
     */
    private void addBlockArea(LayoutContext context, Position pos, boolean isLastPosition) {
        /* Nested block-level content;
         * go down the LM stack again;
         * "unwrap" the positions and put the child positions in a new list.
         * The positionList must contain one area-generating position,
         * which creates one line area.
         */
        List<Position> positionList = new ArrayList<>(1);
        Position innerPosition = pos.getPosition();
        positionList.add(innerPosition);

        // do we have the last LM?
        LayoutManager lastLM = null;
        if (isLastPosition) {
            lastLM = innerPosition.getLM();
        }

        LineArea lineArea = new LineArea();
        lineArea.setChangeBarList(getChangeBarList());
        setCurrentArea(lineArea);
        LayoutContext lc = LayoutContext.newInstance();
        lc.setAlignmentContext(alignmentContext);
        setChildContext(lc);

        PositionIterator childPosIter = new PositionIterator(positionList.listIterator());
        LayoutContext blocklc = LayoutContext.offspringOf(context);
        blocklc.setLeadingSpace(new SpaceSpecifier(true));
        blocklc.setTrailingSpace(new SpaceSpecifier(false));
        blocklc.setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
        LayoutManager childLM;
        while ((childLM = childPosIter.getNextChildLM()) != null) {
            // set last area flag
            blocklc.setFlags(LayoutContext.LAST_AREA,
                             (context.isLastArea() && childLM == lastLM));
            blocklc.setStackLimitBP(context.getStackLimitBP());
            // Add the line areas to Area
            childLM.addAreas(childPosIter, blocklc);
            blocklc.setLeadingSpace(blocklc.getTrailingSpace());
            blocklc.setTrailingSpace(new SpaceSpecifier(false));
        }
        lineArea.updateExtentsFromChildren();
        if (lineArea.getBidiLevel() >= 0) {
            BidiResolver.reorder(lineArea);
        }
        parentLayoutManager.addChildArea(lineArea);
    }

    /** {@inheritDoc} */
    @Override
    public void addChildArea(Area childArea) {
        // Make sure childArea is inline area
        if (childArea instanceof InlineArea) {
            Area parent = getCurrentArea();
            if (getContext().resolveLeadingSpace()) {
                addSpace(parent, getContext().getLeadingSpace().resolve(false),
                        getContext().getSpaceAdjust());
            }
            parent.addChildArea(childArea);
        }
    }

    // --------- Property Resolution related functions --------- //

    /** {@inheritDoc} */
    @Override
    public boolean getGeneratesBlockArea() {
        return true;
    }

    /** {@inheritDoc} */
    @Override
    public boolean getGeneratesLineArea() {
        return true;
    }

    /** {@inheritDoc} */
    @Override
    public boolean isRestartable() {
        return true;
    }

    /**
     * Whether this LM can handle horizontal overflow error messages (only a BlockContainerLayoutManager can).
     * @param milliPoints horizontal overflow
     * @return true if handled by a BlockContainerLayoutManager
     */
    public boolean handleOverflow(int milliPoints) {
        if (getParent() instanceof BlockLayoutManager) {
            return ((BlockLayoutManager) getParent()).handleOverflow(milliPoints);
        }
        return false;
    }
}