1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 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
|
/***** BEGIN LICENSE BLOCK ***** {{{
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
(c) 2006-2008: Martin Stubenschrott <stubenschrott@gmx.net>
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/
liberator.Buffer = function () //{{{
{
////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
var zoomLevels = [ 1, 10, 25, 50, 75, 90, 100,
120, 150, 200, 300, 500, 1000, 2000 ];
function setZoom(value, fullZoom)
{
if (value < 1 || value > 2000)
{
liberator.echoerr("Zoom value out of range (1-2000%)");
return;
}
if (fullZoom)
getBrowser().markupDocumentViewer.fullZoom = value / 100.0;
else
getBrowser().markupDocumentViewer.textZoom = value / 100.0;
liberator.echo((fullZoom ? "Full zoom: " : "Text zoom: ") + value + "%");
// TODO: shouldn't this just recalculate hint coords, rather than
// unsuccessfully attempt to reshow hints? i.e. isn't it just relying
// on the recalculation side effect? -- djk
// NOTE: we could really do with a zoom event...
// liberator.hints.reshowHints();
}
function bumpZoomLevel(steps, fullZoom)
{
if (fullZoom)
var value = getBrowser().markupDocumentViewer.fullZoom * 100.0;
else
var value = getBrowser().markupDocumentViewer.textZoom * 100.0;
var index = -1;
if (steps <= 0)
{
for (var i = zoomLevels.length - 1; i >= 0; i--)
{
if ((zoomLevels[i] + 0.01) < value) // 0.01 for float comparison
{
index = i + 1 + steps;
break;
}
}
}
else
{
for (var i = 0; i < zoomLevels.length; i++)
{
if ((zoomLevels[i] - 0.01) > value) // 0.01 for float comparison
{
index = i - 1 + steps;
break;
}
}
}
if (index < 0 || index >= zoomLevels.length)
{
liberator.beep();
return;
}
setZoom(zoomLevels[index], fullZoom);
}
function checkScrollYBounds(win, direction)
{
// NOTE: it's possible to have scrollY > scrollMaxY - FF bug?
if (direction > 0 && win.scrollY >= win.scrollMaxY || direction < 0 && win.scrollY == 0)
liberator.beep();
}
function findScrollableWindow()
{
var win = window.document.commandDispatcher.focusedWindow;
if (win.scrollMaxX > 0 || win.scrollMaxY > 0)
return win;
win = window.content;
if (win.scrollMaxX > 0 || win.scrollMaxY > 0)
return win;
for (var i = 0; i < win.frames.length; i++)
if (win.frames[i].scrollMaxX > 0 || win.frames[i].scrollMaxY > 0)
return win.frames[i];
return win;
}
// both values are given in percent, -1 means no change
function scrollToPercentiles(horizontal, vertical)
{
var win = findScrollableWindow();
var h, v;
if (horizontal < 0)
h = win.scrollX;
else
h = win.scrollMaxX / 100 * horizontal;
if (vertical < 0)
v = win.scrollY;
else
v = win.scrollMaxY / 100 * vertical;
win.scrollTo(h, v);
}
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["fullscreen", "fs"], "Show the current window fullscreen", "boolean", false,
{
setter: function (value) { window.fullScreen = value; },
getter: function () { return window.fullScreen; }
});
liberator.options.add(["nextpattern"],
"Patterns to use when guessing the 'next' page in a document sequence",
"stringlist", "\\bnext\\b,^>$,^(>>|»)$,^(>|»),(>|»)$,\\bmore\\b");
liberator.options.add(["previouspattern"],
"Patterns to use when guessing the 'previous' page in a document sequence",
"stringlist", "\\bprev|previous\\b,^<$,^(<<|«)$,^(<|«),(<|«)$");
liberator.options.add(["pageinfo", "pa"], "Desired info on :pa[geinfo]", "charlist", "gfm",
{
validator: function (value) { return !(/[^gfm]/.test(value) || value.length > 3 || value.length < 1); }
});
liberator.options.add(["scroll", "scr"],
"Number of lines to scroll with <C-u> and <C-d> commands",
"number", 0,
{
validator: function (value) { return value >= 0; }
}
);
liberator.options.add(["showstatuslinks", "ssli"],
"Show the destination of the link under the cursor in the status bar",
"number", 1,
{
validator: function (value) { return (value >= 0 && value <= 2); }
});
liberator.options.add(["usermode", "um"],
"Show current website with a minimal style sheet to make it easily accessible",
"boolean", false,
{
setter: function (value) { getMarkupDocumentViewer().authorStyleDisabled = value; },
getter: function () { return getMarkupDocumentViewer().authorStyleDisabled; },
});
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.browserModes || [liberator.modes.NORMAL];
liberator.mappings.add(modes, ["i", "<Insert>"],
"Start caret mode",
function ()
{
// setting this option triggers an observer which takes care of the mode setting
liberator.options.setPref("accessibility.browsewithcaret", true);
});
liberator.mappings.add(modes, ["<C-c>"],
"Stop loading",
function () { BrowserStop(); });
// scrolling
liberator.mappings.add(modes, ["j", "<Down>", "<C-e>"],
"Scroll document down",
function (count) { liberator.buffer.scrollLines(count > 1 ? count : 1); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["k", "<Up>", "<C-y>"],
"Scroll document up",
function (count) { liberator.buffer.scrollLines(-(count > 1 ? count : 1)); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, liberator.has("mail") ? ["h"] : ["h", "<Left>"],
"Scroll document to the left",
function (count) { liberator.buffer.scrollColumns(-(count > 1 ? count : 1)); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, liberator.has("mail") ? ["l"] : ["l", "<Right>"],
"Scroll document to the right",
function (count) { liberator.buffer.scrollColumns(count > 1 ? count : 1); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["0", "^"],
"Scroll to the absolute left of the document",
function () { liberator.buffer.scrollStart(); });
liberator.mappings.add(modes, ["$"],
"Scroll to the absolute right of the document",
function () { liberator.buffer.scrollEnd(); });
liberator.mappings.add(modes, ["gg", "<Home>"],
"Goto the top of the document",
function (count) { liberator.buffer.scrollToPercentile(count > 0 ? count : 0); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["G", "<End>"],
"Goto the end of the document",
function (count) { liberator.buffer.scrollToPercentile(count >= 0 ? count : 100); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-d>"],
"Scroll window downwards in the buffer",
function (count) { liberator.buffer.scrollByScrollSize(count, 1); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-u>"],
"Scroll window upwards in the buffer",
function (count) { liberator.buffer.scrollByScrollSize(count, -1); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-b>", "<PageUp>", "<S-Space>"],
"Scroll up a full page",
function (count) { liberator.buffer.scrollPages(-(count > 1 ? count : 1)); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-f>", "<PageDown>", "<Space>"],
"Scroll down a full page",
function (count) { liberator.buffer.scrollPages(count > 1 ? count : 1); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["]f"],
"Focus next frame",
function (count) { liberator.buffer.shiftFrameFocus(count > 1 ? count : 1, true); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["[f"],
"Focus previous frame",
function (count) { liberator.buffer.shiftFrameFocus(count > 1 ? count : 1, false); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["]]"],
"Follow a link labeled to 'next' or '>' if it exists",
function (count) { liberator.buffer.followDocumentRelationship("next"); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["[["],
"Follow a link labeled to 'prev', 'previous' or '<' if it exists",
function (count) { liberator.buffer.followDocumentRelationship("previous"); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["gf"],
"View source",
function () { liberator.buffer.viewSource(null, false); });
liberator.mappings.add(modes, ["gF"],
"View source with an external editor",
function () { liberator.buffer.viewSource(null, true); });
liberator.mappings.add(modes, ["gi"],
"Focus last used input field",
function (count)
{
if (count < 1 && liberator.buffer.lastInputField)
liberator.buffer.lastInputField.focus();
else
{
var first = liberator.buffer.evaluateXPath(
"//*[@type='text'] | //textarea | //xhtml:textarea")
.snapshotItem(count > 0 ? (count - 1) : 0);
if (first)
first.focus();
else
liberator.beep();
}
},
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["gP"],
"Open (put) a URL based on the current clipboard contents in a new buffer",
function ()
{
liberator.open(liberator.util.readFromClipboard(),
/\bpaste\b/.test(liberator.options["activate"]) ?
liberator.NEW_BACKGROUND_TAB : liberator.NEW_TAB);
});
liberator.mappings.add(modes, ["p", "<MiddleMouse>"],
"Open (put) a URL based on the current clipboard contents in the current buffer",
function () { liberator.open(liberator.util.readFromClipboard()); });
liberator.mappings.add(modes, ["P"],
"Open (put) a URL based on the current clipboard contents in a new buffer",
function ()
{
liberator.open(liberator.util.readFromClipboard(),
/\bpaste\b/.test(liberator.options["activate"]) ?
liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB);
});
// reloading
liberator.mappings.add(modes, ["r"],
"Reload current page",
function () { liberator.tabs.reload(getBrowser().mCurrentTab, false); });
liberator.mappings.add(modes, ["R"],
"Reload while skipping the cache",
function () { liberator.tabs.reload(getBrowser().mCurrentTab, true); });
// yanking
liberator.mappings.add(modes, ["Y"],
"Copy selected text or current word",
function ()
{
var sel = liberator.buffer.getCurrentWord();
if (sel)
liberator.util.copyToClipboard(sel, true);
else
liberator.beep();
});
// zooming
liberator.mappings.add(modes, ["zi", "+"],
"Enlarge text zoom of current web page",
function (count) { liberator.buffer.zoomIn(count > 1 ? count : 1, false); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zm"],
"Enlarge text zoom of current web page by a larger amount",
function (count) { liberator.buffer.zoomIn((count > 1 ? count : 1) * 3, false); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zo", "-"],
"Reduce text zoom of current web page",
function (count) { liberator.buffer.zoomOut(count > 1 ? count : 1, false); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zr"],
"Reduce text zoom of current web page by a larger amount",
function (count) { liberator.buffer.zoomOut((count > 1 ? count : 1) * 3, false); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zz"],
"Set text zoom value of current web page",
function (count) { liberator.buffer.textZoom = count > 1 ? count : 100; },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zI"],
"Enlarge full zoom of current web page",
function (count) { liberator.buffer.zoomIn(count > 1 ? count : 1, true); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zM"],
"Enlarge full zoom of current web page by a larger amount",
function (count) { liberator.buffer.zoomIn((count > 1 ? count : 1) * 3, true); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zO"],
"Reduce full zoom of current web page",
function (count) { liberator.buffer.zoomOut(count > 1 ? count : 1, true); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zR"],
"Reduce full zoom of current web page by a larger amount",
function (count) { liberator.buffer.zoomOut((count > 1 ? count : 1) * 3, true); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["zZ"],
"Set full zoom value of current web page",
function (count) { liberator.buffer.fullZoom = count > 1 ? count : 100; },
{ flags: liberator.Mappings.flags.COUNT });
// page info
liberator.mappings.add(modes, ["<C-g>"],
"Print the current file name",
function (count) { liberator.buffer.showPageInfo(false); },
{ flags: liberator.Mappings.flags.COUNT });
liberator.mappings.add(modes, ["g<C-g>"],
"Print file information",
function (count) { liberator.buffer.showPageInfo(true); });
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["ha[rdcopy]"],
"Print current document",
function () { getBrowser().contentWindow.print(); });
liberator.commands.add(["pa[geinfo]"],
"Show various page information",
function () { liberator.buffer.showPageInfo(true); });
liberator.commands.add(["re[load]"],
"Reload current page",
function (args, special) { liberator.tabs.reload(getBrowser().mCurrentTab, special); });
liberator.commands.add(["sav[eas]", "w[rite]"],
"Save current document to disk",
function (args, special)
{
var file = liberator.io.getFile(args || "");
// we always want to save that link relative to the current working directory
liberator.options.setPref("browser.download.lastDir", liberator.io.getCurrentDirectory());
//if (args)
//{
// saveURL(liberator.buffer.URL, args, null, true, special, // special == skipPrompt
// makeURI(liberator.buffer.URL, content.document.characterSet));
//}
//else
saveDocument(window.content.document, special);
});
liberator.commands.add(["st[op]"],
"Stop loading",
function () { BrowserStop(); });
liberator.commands.add(["vie[wsource]"],
"View source code of current document",
function (args, special) { liberator.buffer.viewSource(args, special); });
liberator.commands.add(["zo[om]"],
"Set zoom value of current web page",
function (args, special)
{
var level;
if (!args)
{
level = 100;
}
else if (/^\d+$/.test(args))
{
level = parseInt(args, 10);
}
else if (/^[+-]\d+$/.test(args))
{
if (special)
level = liberator.buffer.fullZoom + parseInt(args, 10);
else
level = liberator.buffer.textZoom + parseInt(args, 10);
// relative args shouldn't take us out of range
if (level < 1)
level = 1;
if (level > 2000)
level = 2000;
}
else
{
liberator.echoerr("E488: Trailing characters");
return;
}
if (special)
liberator.buffer.fullZoom = level;
else
liberator.buffer.textZoom = level;
});
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// PUBLIC SECTION //////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
return {
// 0 if loading, 1 if loaded or 2 if load failed
get loaded()
{
if (typeof window.content.document.pageIsFullyLoaded != "undefined")
return window.content.document.pageIsFullyLoaded;
else
return 0; // in doubt return "loading"
},
set loaded(value)
{
window.content.document.pageIsFullyLoaded = value;
},
// used to keep track of the right field for "gi"
get lastInputField()
{
if (window.content.document.lastInputField)
return window.content.document.lastInputField;
else
return null;
},
set lastInputField(value)
{
window.content.document.lastInputField = value;
},
get URL()
{
// TODO: .URL is not defined for XUL documents
//return window.content.document.URL;
return window.content.document.location.href;
},
get pageHeight()
{
return window.content.innerHeight;
},
get textZoom()
{
return getBrowser().markupDocumentViewer.textZoom * 100;
},
set textZoom(value)
{
setZoom(value, false);
},
get fullZoom()
{
return getBrowser().markupDocumentViewer.fullZoom * 100;
},
set fullZoom(value)
{
setZoom(value, true);
},
get title()
{
return window.content.document.title;
},
// returns an XPathResult object
evaluateXPath: function (expression, doc, elem, asIterator)
{
if (!doc)
doc = window.content.document;
if (!elem)
elem = doc;
var result = doc.evaluate(expression, elem,
function lookupNamespaceURI(prefix)
{
switch (prefix)
{
case "xhtml":
return "http://www.w3.org/1999/xhtml";
default:
return null;
}
},
asIterator ? XPathResult.UNORDERED_NODE_ITERATOR_TYPE : XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null
);
return result;
},
// quick function to get elements inside the document reliably
// argument "args" is something like: @id='myid' or @type='text' (don't forget the quotes around myid)
getElement: function (args, index)
{
return liberator.buffer.evaluateXPath("//*[" + (args || "") + "]").snapshotItem(index || 0);
},
// artificially "clicks" a link in order to open it
followLink: function (elem, where)
{
var doc = window.content.document;
var view = window.document.defaultView;
var offsetX = 1;
var offsetY = 1;
var localName = elem.localName.toLowerCase();
if (localName == "frame" || localName == "iframe") // broken?
{
elem.contentWindow.focus();
return false;
}
else if (localName == "area") // for imagemap
{
var coords = elem.getAttribute("coords").split(",");
offsetX = Number(coords[0]) + 1;
offsetY = Number(coords[1]) + 1;
}
var newTab = false, newWindow = false;
switch (where)
{
case liberator.NEW_TAB:
case liberator.NEW_BACKGROUND_TAB:
newTab = true;
break;
case liberator.NEW_WINDOW:
newWindow = true;
break;
default:
liberator.log("Invalid where argument for followLink()");
}
elem.focus();
var evt = doc.createEvent("MouseEvents");
evt.initMouseEvent("mousedown", true, true, view, 1, offsetX, offsetY, 0, 0, /*ctrl*/ newTab, /*event.altKey*/0, /*event.shiftKey*/ newWindow, /*event.metaKey*/ newTab, 0, null);
elem.dispatchEvent(evt);
evt.initMouseEvent("click", true, true, view, 1, offsetX, offsetY, 0, 0, /*ctrl*/ newTab, /*event.altKey*/0, /*event.shiftKey*/ newWindow, /*event.metaKey*/ newTab, 0, null);
elem.dispatchEvent(evt);
},
// more advanced than a simple elem.focus() as it also works for iframes
// and image maps
// TODO: merge with followLink()?
focusElement: function (elem)
{
var doc = window.content.document;
var elemTagName = elem.localName.toLowerCase();
if (elemTagName == "frame" || elemTagName == "iframe")
{
elem.contentWindow.focus();
return false;
}
else
{
elem.focus();
}
var evt = doc.createEvent("MouseEvents");
var x = 0;
var y = 0;
// for imagemap
if (elemTagName == "area")
{
var coords = elem.getAttribute("coords").split(",");
x = Number(coords[0]);
y = Number(coords[1]);
}
evt.initMouseEvent("mouseover", true, true, doc.defaultView, 1, x, y, 0, 0, 0, 0, 0, 0, 0, null);
elem.dispatchEvent(evt);
},
saveLink: function (elem, skipPrompt)
{
var doc = elem.ownerDocument;
var url = makeURLAbsolute(elem.baseURI, elem.href);
var text = elem.textContent;
try
{
urlSecurityCheck(url, doc.nodePrincipal);
// we always want to save that link relative to the current working directory
liberator.options.setPref("browser.download.lastDir", liberator.io.getCurrentDirectory());
saveURL(url, text, null, true, skipPrompt, makeURI(url, doc.characterSet));
}
catch (e)
{
liberator.echoerr(e);
}
},
// in contrast to vim, returns the selection if one is made,
// otherwise tries to guess the current word unter the text cursor
// NOTE: might change the selection
getCurrentWord: function ()
{
var selection = window.content.getSelection().toString();
if (!selection)
{
var selectionController = getBrowser().docShell
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsISelectionDisplay)
.QueryInterface(Components.interfaces.nsISelectionController);
selectionController.setCaretEnabled(true);
selectionController.wordMove(false, false);
selectionController.wordMove(true, true);
selection = window.content.getSelection().toString();
}
return selection;
},
scrollBottom: function ()
{
scrollToPercentiles(-1, 100);
},
scrollColumns: function (cols)
{
var win = findScrollableWindow();
const COL_WIDTH = 20;
if (cols > 0 && win.scrollX >= win.scrollMaxX || cols < 0 && win.scrollX == 0)
liberator.beep();
win.scrollBy(COL_WIDTH * cols, 0);
},
scrollEnd: function ()
{
scrollToPercentiles(100, -1);
},
scrollLines: function (lines)
{
var win = findScrollableWindow();
checkScrollYBounds(win, lines);
win.scrollByLines(lines);
},
scrollPages: function (pages)
{
var win = findScrollableWindow();
checkScrollYBounds(win, pages);
win.scrollByPages(pages);
},
scrollByScrollSize: function (count, direction)
{
if (count > 0)
liberator.options["scroll"] = count;
var win = findScrollableWindow();
checkScrollYBounds(win, direction);
if (liberator.options["scroll"] > 0)
this.scrollLines(liberator.options["scroll"] * direction);
else // scroll half a page down in pixels
win.scrollBy(0, win.innerHeight / 2 * direction);
},
scrollToPercentile: function (percentage)
{
scrollToPercentiles(-1, percentage);
},
scrollStart: function ()
{
scrollToPercentiles(0, -1);
},
scrollTop: function ()
{
scrollToPercentiles(-1, 0);
},
// TODO: allow callback for filtering out unwanted frames? User defined?
shiftFrameFocus: function (count, forward)
{
if (!window.content.document instanceof HTMLDocument)
return;
var frames = [];
// find all frames - depth-first search
(function (frame)
{
if (frame.document.body.localName.toLowerCase() == "body")
frames.push(frame);
for (var i = 0; i < frame.frames.length; i++)
arguments.callee(frame.frames[i]);
})(window.content);
if (frames.length == 0) // currently top is always included
return;
// remove all unfocusable frames
// TODO: find a better way to do this - walking the tree is too slow
var start = document.commandDispatcher.focusedWindow;
frames = frames.filter(function (frame) {
frame.focus();
if (document.commandDispatcher.focusedWindow == frame)
return frame;
});
start.focus();
// find the currently focused frame index
// TODO: If the window is a frameset then the first _frame_ should be
// focused. Since this is not the current FF behaviour,
// we initalize current to -1 so the first call takes us to the
// first frame.
var current = -1;
for (var i = 0; i < frames.length; i++)
{
if (frames[i] == document.commandDispatcher.focusedWindow)
{
var current = i;
break;
}
}
// calculate the next frame to focus
var next = current;
if (forward)
{
if (count > 1)
next = current + count;
else
next++;
if (next > frames.length - 1)
{
if (current == frames.length - 1)
liberator.beep(); // still allow the frame indicator to be activated
next = frames.length - 1;
}
}
else
{
if (count > 1)
next = current - count;
else
next--;
if (next < 0)
{
if (current == 0)
liberator.beep(); // still allow the frame indicator to be activated
next = 0;
}
}
// focus next frame and scroll into view
frames[next].focus();
if (frames[next] != window.content)
frames[next].frameElement.scrollIntoView(false);
// add the frame indicator
// TODO: make this an XBL element rather than messing with the content
// document
var doc = frames[next].document;
var indicator = doc.createElement("div");
indicator.id = "liberator-frame-indicator";
// NOTE: need to set a high z-index - it's a crapshoot!
var style = "background-color: red; opacity: 0.5; z-index: 999;" +
"position: fixed; top: 0; bottom: 0; left: 0; right: 0;";
indicator.setAttribute("style", style);
doc.body.appendChild(indicator);
// remove the frame indicator
setTimeout(function () { doc.body.removeChild(indicator); }, 500);
},
// XXX: probably remove this method/functionality
// updates the buffer preview in place only if list is visible
updateBufferList: function ()
{
if (!liberator.bufferwindow.visible())
return;
var items = liberator.completion.buffer("")[1];
liberator.bufferwindow.show(items);
liberator.bufferwindow.selectItem(getBrowser().mTabContainer.selectedIndex);
},
zoomIn: function (steps, fullZoom)
{
bumpZoomLevel(steps, fullZoom);
},
zoomOut: function (steps, fullZoom)
{
bumpZoomLevel(-steps, fullZoom);
},
// similar to pageInfo
// TODO: print more useful information, just like the DOM inspector
showElementInfo: function (elem)
{
liberator.echo("Element:<br/>" + liberator.util.objectToString(elem), liberator.commandline.FORCE_MULTILINE);
},
showPageInfo: function (verbose)
{
const feedTypes = {
"application/rss+xml": "RSS",
"application/atom+xml": "Atom",
"text/xml": "XML",
"application/xml": "XML",
"application/rdf+xml": "XML"
};
function isValidFeed(data, principal, isFeed)
{
if (!data || !principal)
return false;
if (!isFeed)
{
var type = data.type && data.type.toLowerCase();
type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
isFeed = (type == "application/rss+xml" || type == "application/atom+xml");
if (!isFeed)
{
// really slimy: general XML types with magic letters in the title
const titleRegex = /(^|\s)rss($|\s)/i;
isFeed = ((type == "text/xml" || type == "application/rdf+xml" ||
type == "application/xml") && titleRegex.test(data.title));
}
}
if (isFeed)
{
try
{
urlSecurityCheck(data.href, principal,
Components.interfaces.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
}
catch (e)
{
isFeed = false;
}
}
if (type)
data.type = type;
return isFeed;
}
// TODO: could this be useful for other commands?
function createTable(data)
{
var ret = "<table><tr><th class='hl-Title' style='font-weight: bold;' align='left' colspan='2'>" +
data[data.length - 1][0] + "</th></tr>";
if (data.length - 1)
{
for (var i = 0; i < data.length - 1; i++)
ret += "<tr><td style='font-weight: bold; min-width: 150px'> " + data[i][0] + ": </td><td>" + data[i][1] + "</td></tr>";
}
else
{
ret += "<tr><td colspan='2'> (" + data[data.length - 1][1] + ")</td></tr>";
}
return ret + "</table>";
}
var pageGeneral = [];
var pageFeeds = [];
var pageMeta = [];
// get file size
const nsICacheService = Components.interfaces.nsICacheService;
const ACCESS_READ = Components.interfaces.nsICache.ACCESS_READ;
const cacheService = Components.classes["@mozilla.org/network/cache-service;1"].getService(nsICacheService);
var httpCacheSession = cacheService.createSession("HTTP", 0, true);
var ftpCacheSession = cacheService.createSession("FTP", 0, true);
httpCacheSession.doomEntriesIfExpired = false;
ftpCacheSession.doomEntriesIfExpired = false;
var cacheKey = window.content.document.location.toString().replace(/#.*$/, "");
try
{
var cacheEntryDescriptor = httpCacheSession.openCacheEntry(cacheKey, ACCESS_READ, false);
}
catch (e)
{
try
{
cacheEntryDescriptor = ftpCacheSession.openCacheEntry(cacheKey, ACCESS_READ, false);
}
catch (e) { }
}
var pageSize = []; // [0] bytes; [1] kbytes
if (cacheEntryDescriptor)
{
pageSize[0] = liberator.util.formatBytes(cacheEntryDescriptor.dataSize, 0, false);
pageSize[1] = liberator.util.formatBytes(cacheEntryDescriptor.dataSize, 2, true);
if (pageSize[1] == pageSize[0])
pageSize[1] = null; // don't output "xx Bytes" twice
}
// put feeds rss into pageFeeds[]
var linkNodes = window.content.document.getElementsByTagName("link");
var length = linkNodes.length;
for (var i = 0; i < length; i++)
{
var link = linkNodes[i];
if (!link.href)
continue;
var rel = link.rel && link.rel.toLowerCase();
var rels = {};
if (rel)
{
for each (let relVal in rel.split(/\s+/))
rels[relVal] = true;
}
if (rels.feed || (link.type && rels.alternate && !rels.stylesheet))
{
var feed = { title: link.title, href: link.href, type: link.type || "" };
if (isValidFeed(feed, window.content.document.nodePrincipal, rels.feed))
{
var type = feedTypes[feed.type] || feedTypes["application/rss+xml"];
pageFeeds.push([feed.title, liberator.util.highlightURL(feed.href, true) + " <span style='color: gray;'>(" + type + ")</span>"]);
}
}
}
var lastModVerbose = new Date(window.content.document.lastModified).toLocaleString();
var lastMod = new Date(window.content.document.lastModified).toLocaleFormat("%x %X");
// FIXME: probably unportable across differnet language versions
if (lastModVerbose == "Invalid Date" || new Date(window.content.document.lastModified).getFullYear() == 1970)
lastModVerbose = lastMod = null;
// Ctrl-g single line output
if (!verbose)
{
var info = []; // tmp array for joining later
var file = window.content.document.location.pathname.split("/").pop() || "[No Name]";
var title = window.content.document.title || "[No Title]";
if (pageSize[0])
info.push(pageSize[1] || pageSize[0]);
if (lastMod)
info.push(lastMod);
var countFeeds = "";
if (pageFeeds.length)
countFeeds = pageFeeds.length + (pageFeeds.length == 1 ? " feed" : " feeds");
if (countFeeds)
info.push(countFeeds);
if (liberator.bookmarks.isBookmarked(this.URL))
info.push("bookmarked");
var pageInfoText = '"' + file + '" [' + info.join(", ") + "] " + title;
liberator.echo(pageInfoText, liberator.commandline.FORCE_SINGLELINE);
return;
}
// get general infos
pageGeneral.push(["Title", window.content.document.title]);
pageGeneral.push(["URL", liberator.util.highlightURL(window.content.document.location.toString(), true)]);
var ref = "referrer" in window.content.document && window.content.document.referrer;
if (ref)
pageGeneral.push(["Referrer", liberator.util.highlightURL(ref, true)]);
if (pageSize[0])
{
if (pageSize[1])
pageGeneral.push(["File Size", pageSize[1] + " (" + pageSize[0] + ")"]);
else
pageGeneral.push(["File Size", pageSize[0]]);
}
pageGeneral.push(["Mime-Type", content.document.contentType]);
pageGeneral.push(["Encoding", content.document.characterSet]);
pageGeneral.push(["Compatibility", content.document.compatMode == "BackCompat" ? "Quirks Mode" : "Full/Almost Standards Mode"]);
if (lastModVerbose)
pageGeneral.push(["Last Modified", lastModVerbose]);
// get meta tag data, sort and put into pageMeta[]
var metaNodes = window.content.document.getElementsByTagName("meta");
var length = metaNodes.length;
if (length)
{
var tmpSort = [];
var tmpDict = [];
for (var i = 0; i < length; i++)
{
var tmpTag = metaNodes[i].name || metaNodes[i].httpEquiv;// +
var tmpTagNr = tmpTag + "-" + i; // allows multiple (identical) meta names
tmpDict[tmpTagNr] = [tmpTag, metaNodes[i].content];
tmpSort.push(tmpTagNr); // array for sorting
}
// sort: ignore-case
tmpSort.sort(function (a, b) { return a.toLowerCase() > b.toLowerCase() ? 1 : -1; });
for (var i = 0; i < tmpSort.length; i++)
pageMeta.push([tmpDict[tmpSort[i]][0], liberator.util.highlightURL(tmpDict[tmpSort[i]][1], false)]);
}
pageMeta.push(["Meta Tags", ""]); // add extra text to the end
pageGeneral.push(["General Info", ""]);
pageFeeds.push(["Feeds", ""]);
var pageInfoText = "";
var option = liberator.options["pageinfo"];
var br = "";
for (var z = 0; z < option.length; z++)
{
switch (option[z])
{
case "g":
if (pageGeneral.length > 1)
{
pageInfoText += br + createTable(pageGeneral);
if (!br)
br = "<br/>";
}
break;
case "f":
if (pageFeeds.length > 1)
{
pageInfoText += br + createTable(pageFeeds);
if (!br)
br = "<br/>";
}
break;
case "m":
if (pageMeta.length > 1)
{
pageInfoText += br + createTable(pageMeta);
if (!br)
br = "<br/>";
}
break;
}
}
liberator.echo(pageInfoText, liberator.commandline.FORCE_MULTILINE);
},
followDocumentRelationship: function (relationship)
{
function followFrameRelationship(relationship, parsedFrame)
{
var regexps;
var relText;
var patternText;
var revString;
switch (relationship)
{
case "next":
regexps = liberator.options["nextpattern"].split(",");
revString = "previous";
break;
case "previous":
// TODO: accept prev\%[ious]
regexps = liberator.options["previouspattern"].split(",");
revString = "next";
break;
default:
liberator.echoerr("Bad document relationship: " + relationship);
}
relText = new RegExp(relationship, "i");
revText = new RegExp(revString, "i");
var elems = parsedFrame.document.getElementsByTagName("link");
// links have higher priority than normal <a> hrefs
for (var i = 0; i < elems.length; i++)
{
if (relText.test(elems[i].rel) || revText.test(elems[i].rev))
{
liberator.open(elems[i].href);
return true;
}
}
// no links? ok, look for hrefs
elems = parsedFrame.document.getElementsByTagName("a");
for (var i = 0; i < elems.length; i++)
{
if (relText.test(elems[i].rel) || revText.test(elems[i].rev))
{
liberator.buffer.followLink(elems[i], liberator.CURRENT_TAB);
return true;
}
}
for (var pattern = 0; pattern < regexps.length; pattern++)
{
patternText = new RegExp(regexps[pattern], "i");
for (var i = 0; i < elems.length; i++)
{
if (patternText.test(elems[i].textContent))
{
liberator.buffer.followLink(elems[i], liberator.CURRENT_TAB);
return true;
}
else
{
// images with alt text being href
var children = elems[i].childNodes;
for (var j = 0; j < children.length; j++)
{
if (patternText.test(children[j].alt))
{
liberator.buffer.followLink(elems[i], liberator.CURRENT_TAB);
return true;
}
}
}
}
}
return false;
}
var retVal;
if (window.content.frames.length != 0)
{
retVal = followFrameRelationship(relationship, window.content);
if (!retVal)
{
// only loop through frames if the main content didnt match
for (var i = 0; i < window.content.frames.length; i++)
{
retVal = followFrameRelationship(relationship, window.content.frames[i]);
if (retVal)
break;
}
}
}
else
{
retVal = followFrameRelationship(relationship, window.content);
}
if (!retVal)
liberator.beep();
},
viewSelectionSource: function ()
{
// copied (and tuned somebit) from browser.jar -> nsContextMenu.js
var focusedWindow = document.commandDispatcher.focusedWindow;
if (focusedWindow == window)
focusedWindow = content;
var docCharset = null;
if (focusedWindow)
docCharset = "charset=" + focusedWindow.document.characterSet;
var reference = null;
reference = focusedWindow.getSelection();
var docUrl = null;
window.openDialog("chrome://global/content/viewPartialSource.xul",
"_blank", "scrollbars,resizable,chrome,dialog=no",
docUrl, docCharset, reference, "selection");
},
// url is optional
viewSource: function (url, useExternalEditor)
{
var url = url || liberator.buffer.URL;
if (useExternalEditor)
{
// TODO: make that a helper function
// TODO: save return value in v:shell_error
var newThread = Components.classes["@mozilla.org/thread-manager;1"].getService().newThread(0);
var editor = liberator.options["editor"];
var args = editor.split(" "); // FIXME: too simple
if (args.length < 1)
{
liberator.echoerr("no editor specified");
return;
}
var prog = args.shift();
args.push(url)
liberator.callFunctionInThread(newThread, liberator.io.run, [prog, args, true]);
}
else
{
liberator.open("view-source:" + url)
}
}
};
//}}}
}; //}}}
liberator.Marks = function () //{{{
{
////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
var localMarks = {};
var urlMarks = {};
var pendingJumps = [];
var appContent = document.getElementById("appcontent");
if (appContent)
appContent.addEventListener("load", onPageLoad, true);
function onPageLoad(event)
{
var win = event.originalTarget.defaultView;
for (var i = 0, length = pendingJumps.length; i < length; i++)
{
var mark = pendingJumps[i];
if (win.location.href == mark.location)
{
win.scrollTo(mark.position.x * win.scrollMaxX, mark.position.y * win.scrollMaxY);
pendingJumps.splice(i, 1);
return;
}
}
}
function removeLocalMark(mark)
{
if (mark in localMarks)
{
var win = window.content;
for (var i = 0; i < localMarks[mark].length; i++)
{
if (localMarks[mark][i].location == win.location.href)
{
liberator.log("Deleting local mark: " + mark + " | " + localMarks[mark][i].location + " | (" + localMarks[mark][i].position.x + ", " + localMarks[mark][i].position.y + ") | tab: " + liberator.tabs.index(localMarks[mark][i].tab), 5);
localMarks[mark].splice(i, 1);
if (localMarks[mark].length == 0)
delete localMarks[mark];
break;
}
}
}
}
function removeURLMark(mark)
{
if (mark in urlMarks)
{
liberator.log("Deleting URL mark: " + mark + " | " + urlMarks[mark].location + " | (" + urlMarks[mark].position.x + ", " + urlMarks[mark].position.y + ") | tab: " + liberator.tabs.index(urlMarks[mark].tab), 5);
delete urlMarks[mark];
}
}
function isLocalMark(mark)
{
return /^[a-z]$/.test(mark);
}
function isURLMark(mark)
{
return /^[A-Z0-9]$/.test(mark);
}
function getSortedMarks()
{
// local marks
var lmarks = [];
for (var mark in localMarks)
{
for (var i = 0; i < localMarks[mark].length; i++)
{
if (localMarks[mark][i].location == window.content.location.href)
lmarks.push([mark, localMarks[mark][i]]);
}
}
lmarks.sort();
// URL marks
var umarks = [];
for (var mark in urlMarks)
umarks.push([mark, urlMarks[mark]]);
// FIXME: why does umarks.sort() cause a "Component is not available =
// NS_ERROR_NOT_AVAILABLE" exception when used here?
umarks.sort(function (a, b) {
if (a[0] < b[0])
return -1;
else if (a[0] > b[0])
return 1;
else
return 0;
});
return lmarks.concat(umarks);
}
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.browserModes || [liberator.modes.NORMAL];
liberator.mappings.add(modes,
["m"], "Set mark at the cursor position",
function (arg)
{
if (/[^a-zA-Z]/.test(arg))
{
liberator.beep();
return;
}
liberator.marks.add(arg);
},
{ flags: liberator.Mappings.flags.ARGUMENT });
liberator.mappings.add(modes,
["'", "`"], "Jump to the mark in the current buffer",
function (arg) { liberator.marks.jumpTo(arg); },
{ flags: liberator.Mappings.flags.ARGUMENT });
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["delm[arks]"],
"Delete the specified marks",
function (args, special)
{
if (!special && !args)
{
liberator.echoerr("E471: Argument required");
return;
}
if (special && args)
{
liberator.echoerr("E474: Invalid argument");
return;
}
var matches;
if (matches = args.match(/(?:(?:^|[^a-zA-Z0-9])-|-(?:$|[^a-zA-Z0-9])|[^a-zA-Z0-9 -]).*/))
{
// NOTE: this currently differs from Vim's behavior which
// deletes any valid marks in the arg list, up to the first
// invalid arg, as well as giving the error message.
liberator.echoerr("E475: Invalid argument: " + matches[0]);
return;
}
// check for illegal ranges - only allow a-z A-Z 0-9
if (matches = args.match(/[a-zA-Z0-9]-[a-zA-Z0-9]/g))
{
for (var i = 0; i < matches.length; i++)
{
var start = matches[i][0];
var end = matches[i][2];
if (/[a-z]/.test(start) != /[a-z]/.test(end) ||
/[A-Z]/.test(start) != /[A-Z]/.test(end) ||
/[0-9]/.test(start) != /[0-9]/.test(end) ||
start > end)
{
liberator.echoerr("E475: Invalid argument: " + args.match(new RegExp(matches[i] + ".*"))[0]);
return;
}
}
}
liberator.marks.remove(args, special);
});
liberator.commands.add(["ma[rk]"],
"Mark current location within the web page",
function (args)
{
if (!args)
{
liberator.echoerr("E471: Argument required");
return;
}
if (args.length > 1)
{
liberator.echoerr("E488: Trailing characters");
return;
}
if (!/[a-zA-Z]/.test(args))
{
liberator.echoerr("E191: Argument must be a letter or forward/backward quote");
return;
}
liberator.marks.add(args);
});
liberator.commands.add(["marks"],
"Show all location marks of current web page",
function (args)
{
// ignore invalid mark characters unless there are no valid mark chars
if (args && !/[a-zA-Z]/.test(args))
{
liberator.echoerr("E283: No marks matching \"" + args + "\"");
return;
}
var filter = args.replace(/[^a-zA-Z]/g, "");
liberator.marks.list(filter);
});
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// PUBLIC SECTION //////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
return {
// TODO: add support for frameset pages
add: function (mark)
{
var win = window.content;
if (win.document.body.localName.toLowerCase() == "frameset")
{
liberator.echoerr("marks support for frameset pages not implemented yet");
return;
}
var x = win.scrollMaxX ? win.pageXOffset / win.scrollMaxX : 0;
var y = win.scrollMaxY ? win.pageYOffset / win.scrollMaxY : 0;
var position = { x: x, y: y };
if (isURLMark(mark))
{
liberator.log("Adding URL mark: " + mark + " | " + win.location.href + " | (" + position.x + ", " + position.y + ") | tab: " + liberator.tabs.index(liberator.tabs.getTab()), 5);
urlMarks[mark] = { location: win.location.href, position: position, tab: liberator.tabs.getTab() };
}
else if (isLocalMark(mark))
{
// remove any previous mark of the same name for this location
removeLocalMark(mark);
if (!localMarks[mark])
localMarks[mark] = [];
liberator.log("Adding local mark: " + mark + " | " + win.location.href + " | (" + position.x + ", " + position.y + ")", 5);
localMarks[mark].push({ location: win.location.href, position: position });
}
},
remove: function (filter, special)
{
if (special)
{
// :delmarks! only deletes a-z marks
for (var mark in localMarks)
removeLocalMark(mark);
}
else
{
var pattern = new RegExp("[" + filter.replace(/\s+/g, "") + "]");
for (var mark in urlMarks)
{
if (pattern.test(mark))
removeURLMark(mark);
}
for (var mark in localMarks)
{
if (pattern.test(mark))
removeLocalMark(mark);
}
}
},
jumpTo: function (mark)
{
var ok = false;
if (isURLMark(mark))
{
var slice = urlMarks[mark];
if (slice && slice.tab && slice.tab.linkedBrowser)
{
if (!slice.tab.parentNode)
{
pendingJumps.push(slice);
// NOTE: this obviously won't work on generated pages using
// non-unique URLs, like liberator's help :(
liberator.open(slice.location, liberator.NEW_TAB);
return;
}
var index = liberator.tabs.index(slice.tab);
if (index != -1)
{
liberator.tabs.select(index);
var win = slice.tab.linkedBrowser.contentWindow;
if (win.location.href != slice.location)
{
pendingJumps.push(slice);
win.location.href = slice.location;
return;
}
liberator.log("Jumping to URL mark: " + mark + " | " + slice.location + " | (" + slice.position.x + ", " + slice.position.y + ") | tab: " + liberator.tabs.index(slice.tab), 5);
win.scrollTo(slice.position.x * win.scrollMaxX, slice.position.y * win.scrollMaxY);
ok = true;
}
}
}
else if (isLocalMark(mark))
{
var win = window.content;
var slice = localMarks[mark] || [];
for (var i = 0; i < slice.length; i++)
{
if (win.location.href == slice[i].location)
{
liberator.log("Jumping to local mark: " + mark + " | " + slice[i].location + " | (" + slice[i].position.x + ", " + slice[i].position.y + ")", 5);
win.scrollTo(slice[i].position.x * win.scrollMaxX, slice[i].position.y * win.scrollMaxY);
ok = true;
}
}
}
if (!ok)
liberator.echoerr("E20: Mark not set"); // FIXME: move up?
},
list: function (filter)
{
var marks = getSortedMarks();
if (marks.length == 0)
{
liberator.echoerr("No marks set");
return;
}
if (filter.length > 0)
{
marks = marks.filter(function (mark) {
if (filter.indexOf(mark[0]) > -1)
return mark;
});
if (marks.length == 0)
{
liberator.echoerr("E283: No marks matching \"" + filter + "\"");
return;
}
}
var list = ":" + liberator.util.escapeHTML(liberator.commandline.getCommand()) + "<br/>" +
"<table><tr align=\"left\" class=\"hl-Title\"><th>mark</th><th>line</th><th>col</th><th>file</th></tr>";
for (var i = 0; i < marks.length; i++)
{
list += "<tr>" +
"<td> " + marks[i][0] + "</td>" +
"<td align=\"right\">" + Math.round(marks[i][1].position.y * 100) + "%</td>" +
"<td align=\"right\">" + Math.round(marks[i][1].position.x * 100) + "%</td>" +
"<td style=\"color: green;\">" + liberator.util.escapeHTML(marks[i][1].location) + "</td>" +
"</tr>";
}
list += "</table>";
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE);
}
};
//}}}
}; //}}}
// vim: set fdm=marker sw=4 ts=4 et:
|