code
stringlengths
1
2.08M
language
stringclasses
1 value
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','cs',{uicolor:{title:'Výběr barvy rozhraní',preview:'Živý náhled',config:'Vložte tento řetězec do Vašeho souboru config.js',predefined:'Přednastavené sady barev'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','pt-br',{uicolor:{title:'Paleta de Cores',preview:'Visualização ao vivo',config:'Cole o texto no seu arquivo config.js',predefined:'Conjuntos de cores predefinidos'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','nl',{devTools:{title:'Elementinformatie',dialogName:'Naam dialoogvenster',tabName:'Tabnaam',elementId:'Element ID',elementType:'Elementtype'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','ug',{devTools:{title:'ئېلېمېنت ئۇچۇرى',dialogName:'سۆزلەشكۈ كۆزنەك ئاتى',tabName:'Tab ئاتى',elementId:'ئېلېمېنت كىملىكى',elementType:'ئېلېمېنت تىپى'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','it',{devTools:{title:'Informazioni elemento',dialogName:'Nome finestra di dialogo',tabName:'Nome Tab',elementId:'ID Elemento',elementType:'Tipo elemento'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','de',{devTools:{title:'Elementinformation',dialogName:'Dialogfenstername',tabName:'Reitername',elementId:'Element ID',elementType:'Elementtyp'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','pl',{devTools:{title:'Informacja o elemencie',dialogName:'Nazwa okna dialogowego',tabName:'Nazwa zakładki',elementId:'ID elementu',elementType:'Typ elementu'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','vi',{devTools:{title:'Thông tin thành ph',dialogName:'Tên hộp tho',tabName:'Tên th',elementId:'Mã thành ph',elementType:'Loại thành ph'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','hr',{devTools:{title:'Informacije elementa',dialogName:'Naziv prozora za dijalog',tabName:'Naziva jahača',elementId:'ID elementa',elementType:'Vrsta elementa'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','tr',{devTools:{title:'Eleman Bilgisi',dialogName:'İletişim pencere ismi',tabName:'Sekme adı',elementId:'Eleman ID',elementType:'Eleman türü'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','fr',{devTools:{title:"Information sur l'élément",dialogName:'Nom de la fenêtre de dialogue',tabName:"Nom de l'onglet",elementId:"ID de l'élément",elementType:"Type de l'élément"}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','zh-cn',{devTools:{title:'元素信息',dialogName:'对话框窗口名称',tabName:'Tab 名称',elementId:'元素 ID',elementType:'元素类型'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','eo',{devTools:{title:'Informo pri la elemento',dialogName:'Nomo de la dialogfenestro',tabName:'Langetnomo',elementId:'ID de la elemento',elementType:'Tipo de la elemento'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','en',{devTools:{title:'Element Information',dialogName:'Dialog window name',tabName:'Tab name',elementId:'Element ID',elementType:'Element type'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','da',{devTools:{title:'Information på elementet',dialogName:'Dialogboks',tabName:'Tab beskrivelse',elementId:'ID på element',elementType:'Type af element'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','nb',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','bg',{devTools:{title:'Информация за елемента',dialogName:'Име на диалоговия прозорец',tabName:'Име на таб',elementId:'ID на елемента',elementType:'Тип на елемента'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','el',{devTools:{title:'Πληροφορίες Στοιχείου',dialogName:'Όνομα παραθύρου διαλόγου',tabName:'Όνομα καρτέλας',elementId:'ID Στοιχείου',elementType:'Τύπος στοιχείου'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','fi',{devTools:{title:'Elementin tiedot',dialogName:'Dialogi-ikkunan nimi',tabName:'Välilehden nimi',elementId:'Elementin ID',elementType:'Elementin tyyppi'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','cy',{devTools:{title:'Gwybodaeth am yr Elfen',dialogName:'Enw ffenestr y deialog',tabName:"Enw'r tab",elementId:'ID yr Elfen',elementType:'Math yr elfen'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','no',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','fa',{devTools:{title:'اطلاعات عنصر',dialogName:'نام پنجره محاورهای',tabName:'نام برگه',elementId:'ID عنصر',elementType:'نوع عنصر'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','et',{devTools:{title:'Elemendi andmed',dialogName:'Dialoogiakna nimi',tabName:'Saki nimi',elementId:'Elemendi ID',elementType:'Elemendi liik'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','he',{devTools:{title:'מידע על האלמנט',dialogName:'שם הדיאלוג',tabName:'שם הטאב',elementId:'ID של האלמנט',elementType:'סוג האלמנט'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','uk',{devTools:{title:'Відомості про Елемент',dialogName:'Заголовок діалогового вікна',tabName:'Назва вкладки',elementId:'Ідентифікатор Елемента',elementType:'Тип Елемента'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','cs',{devTools:{title:'Informace o prvku',dialogName:'Název dialogového okna',tabName:'Název karty',elementId:'ID prvku',elementType:'Typ prvku'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','pt-br',{devTools:{title:'Informação do Elemento',dialogName:'Nome da janela de diálogo',tabName:'Nome da aba',elementId:'ID do elemento',elementType:'Tipo do elemento'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','gu',{devTools:{title:'પ્રાથમિક માહિતી',dialogName:'વિન્ડોનું નામ',tabName:'ટેબનું નામ',elementId:'પ્રાથમિક આઈડી',elementType:'પ્રાથમિક પ્રકાર'}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add('docprops',{init:function(a){var b=new CKEDITOR.dialogCommand('docProps');b.modes={wysiwyg:a.config.fullPage};a.addCommand('docProps',b);CKEDITOR.dialog.add('docProps',this.path+'dialogs/docprops.js');a.ui.addButton('DocProps',{label:a.lang.docprops.label,command:'docProps'});}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'myDialog', function( editor ) { return { title : 'My Dialog', minWidth : 400, minHeight : 200, contents : [ { id : 'tab1', label : 'First Tab', title : 'First Tab', elements : [ { id : 'input1', type : 'text', label : 'Input 1' } ] } ] }; } );
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // This file is not required by CKEditor and may be safely ignored. // It is just a helper file that displays a red message about browser compatibility // at the top of the samples (if incompatible browser is detected). if ( window.CKEDITOR ) { (function() { var showCompatibilityMsg = function() { var env = CKEDITOR.env; var html = '<p><strong>Your browser is not compatible with CKEditor.</strong>'; var browsers = { gecko : 'Firefox 2.0', ie : 'Internet Explorer 6.0', opera : 'Opera 9.5', webkit : 'Safari 3.0' }; var alsoBrowsers = ''; for ( var key in env ) { if ( browsers[ key ] ) { if ( env[key] ) html += ' CKEditor is compatible with ' + browsers[ key ] + ' or higher.'; else alsoBrowsers += browsers[ key ] + '+, '; } } alsoBrowsers = alsoBrowsers.replace( /\+,([^,]+), $/, '+ and $1' ); html += ' It is also compatible with ' + alsoBrowsers + '.'; html += '</p><p>With non compatible browsers, you should still be able to see and edit the contents (HTML) in a plain text field.</p>'; var alertsEl = document.getElementById( 'alerts' ); alertsEl && ( alertsEl.innerHTML = html ); }; var onload = function() { // Show a friendly compatibility message as soon as the page is loaded, // for those browsers that are not compatible with CKEditor. if ( !CKEDITOR.env.isCompatible ) showCompatibilityMsg(); }; // Register the onload listener. if ( window.addEventListener ) window.addEventListener( 'load', onload, false ); else if ( window.attachEvent ) window.attachEvent( 'onload', onload ); })(); }
JavaScript
/** * Creates a new Floor. * @constructor * @param {google.maps.Map=} opt_map */ function Floor(opt_map) { /** * @type Array.<google.maps.MVCObject> */ this.overlays_ = []; /** * @type boolean */ this.shown_ = true; if (opt_map) { this.setMap(opt_map); } } /** * @param {google.maps.Map} map */ Floor.prototype.setMap = function(map) { this.map_ = map; }; /** * @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel. * Requires a setMap method. */ Floor.prototype.addOverlay = function(overlay) { if (!overlay) return; this.overlays_.push(overlay); overlay.setMap(this.shown_ ? this.map_ : null); }; /** * Sets the map on all the overlays * @param {google.maps.Map} map The map to set. */ Floor.prototype.setMapAll_ = function(map) { this.shown_ = !!map; for (var i = 0, overlay; overlay = this.overlays_[i]; i++) { overlay.setMap(map); } }; /** * Hides the floor and all associated overlays. */ Floor.prototype.hide = function() { this.setMapAll_(null); }; /** * Shows the floor and all associated overlays. */ Floor.prototype.show = function() { this.setMapAll_(this.map_); };
JavaScript
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
/** * @license * * Copyright 2011 Google Inc. * * Licensed 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. */ /** * @fileoverview SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript
// Copyright 2011 Google /** * Licensed 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. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
// Copyright (c) 2008 by Christian Dietrich <stettberger@dokucode.de> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const Addressbook = Module("addressbook", { init: function () { services.add("abManager", "@mozilla.org/abmanager;1", Ci.nsIAbManager); }, // TODO: add option for a format specifier, like: // :set displayname=%l, %f generateDisplayName: function (firstName, lastName) { if (firstName && lastName) return lastName + ", " + firstName; else if (firstName) return firstName; else if (lastName) return lastName; else return ""; }, add: function (address, firstName, lastName, displayName) { const personalAddressbookURI = "moz-abmdbdirectory://abook.mab"; let directory = services.get("abManager").getDirectory(personalAddressbookURI); let card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard); if (!address || !directory || !card) return false; card.primaryEmail = address; card.firstName = firstName; card.lastName = lastName; card.displayName = displayName; return directory.addCard(card); }, // TODO: add telephone number support list: function (filter, newMail) { let addresses = []; let dirs = services.get("abManager").directories; let lowerFilter = filter.toLowerCase(); while (dirs.hasMoreElements()) { let addrbook = dirs.getNext().QueryInterface(Ci.nsIAbDirectory); let cards = addrbook.childCards; while (cards.hasMoreElements()) { let card = cards.getNext().QueryInterface(Ci.nsIAbCard); //var mail = card.primaryEmail || ""; //XXX let displayName = card.displayName; if (!displayName) displayName = this.generateDisplayName(card.firstName, card.lastName); if (displayName.toLowerCase().indexOf(lowerFilter) > -1 || card.primaryEmail.toLowerCase().indexOf(lowerFilter) > -1) addresses.push([displayName, card.primaryEmail]); } } if (addresses.length < 1) { if (!filter) liberator.echoerr("No contacts"); else liberator.echoerr("No matching contacts for: " + filter); return false; } if (newMail) { // Now we have to create a new message let args = {}; args.to = addresses.map( function (address) "\"" + address[0].replace(/"/g, "") + " <" + address[1] + ">\"" ).join(", "); mail.composeNewMail(args); } else { let list = template.tabular(["Name", "Address"], [[util.clip(address[0], 50), address[1]] for ([, address] in Iterator(addresses))]); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } return true; } }, { }, { commands: function () { commands.add(["con[tact]"], "Add an address book entry", function (args) { let mailAddr = args[0]; // TODO: support more than one email address let firstName = args["-firstname"] || null; let lastName = args["-lastname"] || null; let displayName = args["-name"] || null; if (!displayName) displayName = addressbook.generateDisplayName(firstName, lastName); if (addressbook.add(mailAddr, firstName, lastName, displayName)) liberator.echomsg("Added contact: " + displayName + " <" + mailAddr + ">"); else liberator.echoerr("Could not add contact: " + mailAddr); }, { argCount: "+", options: [[["-firstname", "-f"], commands.OPTION_STRING], [["-lastname", "-l"], commands.OPTION_STRING], [["-name", "-n"], commands.OPTION_STRING]] }); commands.add(["contacts", "addr[essbook]"], "List or open multiple addresses", function (args) { addressbook.list(args.string, args.bang); }, { bang: true }); }, mappings: function () { var myModes = config.mailModes; mappings.add(myModes, ["a"], "Open a prompt to save a new addressbook entry for the sender of the selected message", function () { try { var to = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor; } catch (e) { liberator.beep(); } if (!to) return; let address = to.substring(to.indexOf("<") + 1, to.indexOf(">")); let displayName = to.substr(0, to.indexOf("<") - 1); if (/^\S+\s+\S+\s*$/.test(displayName)) { let names = displayName.split(/\s+/); displayName = "-firstname=" + names[0].replace(/"/g, "") + " -lastname=" + names[1].replace(/"/g, ""); } else displayName = "-name=\"" + displayName.replace(/"/g, "") + "\""; commandline.open("", "contact " + address + " " + displayName, modes.EX); }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const Mail = Module("mail", { requires: ["liberator"], init: function () { services.add("smtpService", "@mozilla.org/messengercompose/smtp;1", Ci.nsISmtpService); // used for asynchronously selecting messages after wrapping folders this._selectMessageKeys = []; this._selectMessageCount = 1; this._selectMessageReverse = false; this._mailSession = Cc["@mozilla.org/messenger/services/session;1"].getService(Ci.nsIMsgMailSession); this._notifyFlags = Ci.nsIFolderListener.intPropertyChanged | Ci.nsIFolderListener.event; this._mailSession.AddFolderListener(this._folderListener, this._notifyFlags); liberator.open = this.open; }, _folderListener: { OnItemAdded: function (parentItem, item) {}, OnItemRemoved: function (parentItem, item) {}, OnItemPropertyChanged: function (item, property, oldValue, newValue) {}, OnItemIntPropertyChanged: function (item, property, oldValue, newValue) {}, OnItemBoolPropertyChanged: function (item, property, oldValue, newValue) {}, OnItemUnicharPropertyChanged: function (item, property, oldValue, newValue) {}, OnItemPropertyFlagChanged: function (item, property, oldFlag, newFlag) {}, OnItemEvent: function (folder, event) { let eventType = event.toString(); if (eventType == "FolderLoaded") { if (folder) { let msgFolder = folder.QueryInterface(Ci.nsIMsgFolder); autocommands.trigger("FolderLoaded", { url: msgFolder }); // Jump to a message when requested let indices = []; if (mail._selectMessageKeys.length > 0) { for (let j = 0; j < mail._selectMessageKeys.length; j++) indices.push([gDBView.findIndexFromKey(mail._selectMessageKeys[j], true), mail._selectMessageKeys[j]]); indices.sort(); let index = mail._selectMessageCount - 1; if (mail._selectMessageReverse) index = mail._selectMessageKeys.length - 1 - index; gDBView.selectMsgByKey(indices[index][1]); mail._selectMessageKeys = []; } } } /*else if (eventType == "ImapHdrDownloaded") {} else if (eventType == "DeleteOrMoveMsgCompleted") {} else if (eventType == "DeleteOrMoveMsgFailed") {} else if (eventType == "AboutToCompact") {} else if (eventType == "CompactCompleted") {} else if (eventType == "RenameCompleted") {} else if (eventType == "JunkStatusChanged") {}*/ } }, _getCurrentFolderIndex: function () { // for some reason, the index is interpreted as a string, therefore the parseInt return parseInt(gFolderTreeView.getIndexOfFolder(gFolderTreeView.getSelectedFolders()[0])); }, _getRSSUrl: function () { return gDBView.hdrForFirstSelectedMessage.messageId.replace(/(#.*)?@.*$/, ""); }, _moveOrCopy: function (copy, destinationFolder, operateOnThread) { let folders = mail.getFolders(destinationFolder); if (folders.length == 0) return void liberator.echoerr("No matching folder for: " + destinationFolder); else if (folders.length > 1) return liberator.echoerr("More than one match for: " + destinationFolder); let count = gDBView.selection.count; if (!count) return void liberator.beep(); (copy ? MsgCopyMessage : MsgMoveMessage)(folders[0]); setTimeout(function () { liberator.echomsg((copy ? "Copied " : "Moved ") + count + " message(s) " + " to: " + folders[0].prettyName); }, 100); }, _parentIndex: function (index) { let parent = index; let tree = GetThreadTree(); while (true) { let tmp = tree.view.getParentIndex(parent); if (tmp >= 0) parent = tmp; else break; } return parent; }, // does not wrap yet, intentional? _selectUnreadFolder: function (backwards, count) { count = Math.max(1, count); let direction = backwards ? -1 : 1; let c = this._getCurrentFolderIndex(); let i = direction; let folder; while (count > 0 && (c + i) < gFolderTreeView.rowCount && (c + i) >= 0) { let resource = gFolderTreeView._rowMap[c+i]._folder; if (!resource.isServer && resource.getNumUnread(false)) { count -= 1; folder = i; } i += direction; } if (!folder || count > 0) liberator.beep(); else gFolderTreeView.selection.timedSelect(c + folder, 500); }, _escapeRecipient: function (recipient) { // strip all ": recipient = recipient.replace(/"/g, ""); return "\"" + recipient + "\""; }, get currentAccount() this.currentFolder.rootFolder, get currentFolder() gFolderTreeView.getSelectedFolders()[0], /** @property {nsISmtpServer[]} The list of configured SMTP servers. */ get smtpServers() { let servers = services.get("smtpService").smtpServers; let ret = []; while (servers.hasMoreElements()) { let server = servers.getNext(); if (server instanceof Ci.nsISmtpServer) ret.push(server); } return ret; }, composeNewMail: function (args) { let params = Cc["@mozilla.org/messengercompose/composeparams;1"].createInstance(Ci.nsIMsgComposeParams); params.composeFields = Cc["@mozilla.org/messengercompose/composefields;1"].createInstance(Ci.nsIMsgCompFields); if (args) { if (args.originalMsg) params.originalMsgURI = args.originalMsg; if (args.to) params.composeFields.to = args.to; if (args.cc) params.composeFields.cc = args.cc; if (args.bcc) params.composeFields.bcc = args.bcc; if (args.newsgroups) params.composeFields.newsgroups = args.newsgroups; if (args.subject) params.composeFields.subject = args.subject; if (args.body) params.composeFields.body = args.body; if (args.attachments) { while (args.attachments.length > 0) { let url = args.attachments.pop(); let file = io.File(url); if (!file.exists()) return void liberator.echoerr("Could not attach file: " + url); attachment = Cc["@mozilla.org/messengercompose/attachment;1"].createInstance(Ci.nsIMsgAttachment); attachment.url = "file://" + file.path; params.composeFields.addAttachment(attachment); } } } params.type = Ci.nsIMsgCompType.New; const msgComposeService = Cc["@mozilla.org/messengercompose;1"].getService(); msgComposeService = msgComposeService.QueryInterface(Ci.nsIMsgComposeService); msgComposeService.OpenComposeWindowWithParams(null, params); }, /** * returns Generator of all folders in the current view * @param {Boolean} includeServers * @param {Boolean} includeMsgFolders * @return {Generator} * [ * [{Object ftvItem} row, {String} folderPath] * ... * ] */ getAllFolderRowMap: function (includeServers, includeMsgFolders) { if (includeServers === undefined) includeServers = false; if (includeMsgFolders === undefined) includeMsgFolders = true; function walkChildren(children, prefix) { for (let [, row] in Iterator(children)) { let folder = row._folder; let folderString = prefix + "/" + (row.useServerNameOnly ? folder.server.prettyName : folder.abbreviatedName); yield [row, folderString]; if (row.children.length > 0) for (let child in walkChildren(row.children, folderString)) yield child; } } for (let i = 0; i < gFolderTreeView.rowCount; i++) { let row = gFolderTreeView._rowMap[i]; if (row.level != 0) continue; let folder = row._folder; let folderString = folder.server.prettyName + ": " + (row.useServerNameOnly ? folder.server.prettyName : folder.abbreviatedName); if ((folder.isServer && includeServers) || (!folder.isServer && includeMsgFolders)) yield [row, folderString]; if (includeMsgFolders && row.children.length > 0) for (let child in walkChildren(row.children, folderString)) yield child; } }, // returns an array of nsIMsgFolder objects getFolders: function (filter, includeServers, includeMsgFolders) { let folders = []; if (!filter) filter = ""; else filter = filter.toLowerCase(); for (let [row, name] in this.getAllFolderRowMap(includeServers, includeMsgFolders)) { let folder = row._folder; // XXX: row._folder.prettyName is needed ? -- teramako if (name.toLowerCase().indexOf(filter) >= 0) folders.push(row._folder); } return folders; }, /** * returns array of nsIMsgFolder objects * @param {Number} flag * e.g.) Ci.nsMsgFolderFlags.Inbox * @see Ci.nsMsgFolderFlags * @return {nsIMsgFolder[]} */ getFoldersWithFlag: function (flag) { if (flag) { return [row._folder for ([row] in this.getAllFolderRowMap(true,true)) if (row._folder.flags & flag)] } return []; }, getNewMessages: function (currentAccountOnly) { if (currentAccountOnly) MsgGetMessagesForAccount(); else GetMessagesForAllAuthenticatedAccounts(); }, getStatistics: function (currentAccountOnly) { let accounts = currentAccountOnly ? [this.currentAccount] : this.getFolders("", true, false); let unreadCount = 0, totalCount = 0, newCount = 0; for (let i = 0; i < accounts.length; i++) { let account = accounts[i]; unreadCount += account.getNumUnread(true); // true == deep (includes subfolders) totalCount += account.getTotalMessages(true); newCount += account.getNumUnread(true); } return { numUnread: unreadCount, numTotal: totalCount, numNew: newCount }; }, collapseThread: function () { let tree = GetThreadTree(); if (tree) { let parent = this._parentIndex(tree.currentIndex); if (tree.changeOpenState(parent, false)) { tree.view.selection.select(parent); tree.treeBoxObject.ensureRowIsVisible(parent); return true; } } return false; }, expandThread: function () { let tree = GetThreadTree(); if (tree) { let row = tree.currentIndex; if (row >= 0 && tree.changeOpenState(row, true)) return true; } return false; }, /** * General-purpose method to find messages. * * @param {function(nsIMsgDBHdr):boolean} validatorFunc Return * true/false whether msg should be selected or not. * @param {boolean} canWrap When true, wraps around folders. * @param {boolean} openThreads Should we open closed threads? * @param {boolean} reverse Change direction of searching. */ selectMessage: function (validatorFunc, canWrap, openThreads, reverse, count) { function currentIndex() { let index = gDBView.selection.currentIndex; if (index < 0) index = 0; return index; } function closedThread(index) { if (!(gDBView.viewFlags & nsMsgViewFlagsType.kThreadedDisplay)) return false; index = (typeof index == "number") ? index : currentIndex(); return !gDBView.isContainerOpen(index) && !gDBView.isContainerEmpty(index); } if (typeof validatorFunc != "function") return; if (typeof count != "number" || count < 1) count = 1; // first try to find in current folder if (gDBView) { for (let i = currentIndex() + (reverse ? -1 : (openThreads && closedThread() ? 0 : 1)); reverse ? (i >= 0) : (i < gDBView.rowCount); reverse ? i-- : i++) { let key = gDBView.getKeyAt(i); let msg = gDBView.db.GetMsgHdrForKey(key); // a closed thread if (openThreads && closedThread(i)) { let thread = gDBView.db.GetThreadContainingMsgHdr(msg); let originalCount = count; for (let j = (i == currentIndex() && !reverse) ? 1 : (reverse ? thread.numChildren - 1 : 0); reverse ? (j >= 0) : (j < thread.numChildren); reverse ? j-- : j++) { msg = thread.getChildAt(j); if (validatorFunc(msg) && --count == 0) { // this hack is needed to get the correct message, because getChildAt() does not // necessarily return the messages in the order they are displayed gDBView.selection.timedSelect(i, GetThreadTree()._selectDelay || 500); GetThreadTree().treeBoxObject.ensureRowIsVisible(i); if (j > 0) { GetThreadTree().changeOpenState(i, true); this.selectMessage(validatorFunc, false, false, false, originalCount); } return; } } } else { // simple non-threaded message if (validatorFunc(msg) && --count == 0) { gDBView.selection.timedSelect(i, GetThreadTree()._selectDelay || 500); GetThreadTree().treeBoxObject.ensureRowIsVisible(i); return; } } } } // then in other folders if (canWrap) { this._selectMessageReverse = reverse; let folders = this.getFolders("", true, true); let ci = this._getCurrentFolderIndex(); for (let i = 1; i < folders.length; i++) { let index = (i + ci) % folders.length; if (reverse) index = folders.length - 1 - index; let folder = folders[index]; if (folder.isServer) continue; this._selectMessageCount = count; this._selectMessageKeys = []; // sometimes folder.getMessages can fail with an exception // TODO: find out why, and solve the problem try { var msgs = folder.messages; } catch (e) { msgs = folder.getMessages(msgWindow); // for older thunderbirds } while (msgs.hasMoreElements()) { let msg = msgs.getNext().QueryInterface(Ci.nsIMsgDBHdr); if (validatorFunc(msg)) { count--; this._selectMessageKeys.push(msg.messageKey); } } if (count <= 0) { // SelectFolder is asynchronous, message is selected in this._folderListener SelectFolder(folder.URI); return; } } } // TODO: finally for the "rest" of the current folder liberator.beep(); }, setHTML: function (value) { let values = [[true, 1, gDisallow_classes_no_html], // plaintext [false, 0, 0], // HTML [false, 3, gDisallow_classes_no_html]]; // sanitized/simple HTML if (typeof value != "number" || value < 0 || value > 2) value = 1; gPrefBranch.setBoolPref("mailnews.display.prefer_plaintext", values[value][0]); gPrefBranch.setIntPref("mailnews.display.html_as", values[value][1]); gPrefBranch.setIntPref("mailnews.display.disallow_mime_handlers", values[value][2]); ReloadMessage(); }, /** * open folders and URLs * @param {Object} targets * @param {Object|Number} params */ open: function (targets, params) { let tabmail = document.getElementById("tabmail"); if (!(targets instanceof Array)) targets = [targets]; if (!params) params = {}; else if (params instanceof Array) params = { where: params }; let where = params.where || liberator.CURRENT_TAB; if (liberator.forceNewTab || liberator.forceNewWindow) where = liberator.NEW_TAB; if ("from" in params) { if (!("where" in params) && options["newtab"] && options.get("newtab").has("all", params.from)) where = liberator.NEW_TAB; if (options["activate"] && !options.get("activate").has("all", params.from)) { if (where == liberator.NEW_TAB) where = liberator.NEW_BACKGROUND_TAB; else if (where == liberator.NEW_BACKGROUND_TAB) where = liberator.NEW_TAB; } } function openTarget(target, where) { if (target instanceof Ci.nsIMsgFolder) { if (where == liberator.CURRENT_TAB && tabmail.currentTabInfo.mode.name == "folder") { SelectFolder(target.URI); return; } let args = { folder: target, background: where != liberator.NEW_TAB }; ["folderPaneVisible", "messagePaneVisible", "msgHdr"].forEach(function(opt){ if (opt in params) args[opt] = params[opt]; }); tabmail.openTab("folder", args); return; } if (typeof target == "string") { try { target = util.createURI(target); } catch(e) { return; } } if (!(target instanceof Ci.nsIURI)) return; if (target.schemeIs("mailto")){ mail.composeNewMail({to: target.path}); return; } switch (where) { case liberator.CURRENT_TAB: if (tabmail.currentTabInfo.mode.name == "contentTab") { tabmail.currentTabInfo.browser.loadURI(target.spec); break; } case liberator.NEW_TAB: case liberator.NEW_WINDOW: case liberator.NEW_BACKGROUND_TAB: let tab = tabmail.openTab("contentTab", { contentPage: target.spec, background: where != liberator.NEW_TAB, clickHandler: "liberator.modules.mail.siteClickHandler(event)" }); let browser = tab.browser; if (browser.hasAttribute("disablehistory")) { browser.webNavigation.sessionHistory = Cc["@mozilla.org/browser/shistory;1"].createInstance(Ci.nsISHistory); browser.removeAttribute("disablehistory"); } break; } } for (let [,target] in Iterator(targets)) { openTarget(target, where); where = liberator.NEW_BACKGROUND_TAB; } }, /** * @see specialTabs.siteClickHandler */ siteClickHandler: function(event){ if (!event.isTrusted || event.getPreventDefault() || event.button) return true; let href = hRefForClickEvent(event, true); let isOpenExternal = true; if (href) { let uri = makeURI(href); switch(uri.scheme){ case "http": case "https": case "chrome": case "about": isOpenExternal = false; break; case "liberator": if (event.target.ownerDocument.location.protocol == "liberator:") config.browser.loadURI(uri.spec); event.preventDefault(); return true; default: if (specialTabs._protocolSvc.isExposedProtocol(uri.scheme)) isOpenExternal = false; } if (isOpenExternal) { event.preventDefault(); openLinkExternally(href); } } } }, { }, { commands: function () { commands.add(["go[to]"], "Select a folder", function (args) { let count = Math.max(0, args.count - 1); let arg = args.literalArg; let folder = arg ? mail.getFolders(arg, true, true)[count] : mail.getFoldersWithFlag(Ci.nsMsgFolderFlags.Inbox)[count]; if (!folder) liberator.echoerr("No such folder: " + arg); else liberator.open(folder, {from: "goto"}); }, { argCount: "?", completer: function (context) completion.mailFolder(context), count: true, literal: 0 }); function attachmentsCompletion (context) { let i = context.filter.lastIndexOf(","); if (i !== -1) context.advance(i + 1); completion.file(context); return context.items; } commands.add(["c[ompose]"], "Compose a new message", function (args) { let mailargs = {}; mailargs.to = args.join(", "); mailargs.subject = args["-subject"]; mailargs.bcc = args["-bcc"]; mailargs.cc = args["-cc"]; mailargs.body = args["-text"]; mailargs.attachments = args["-attachment"] || []; let addresses = args; if (mailargs.bcc) addresses = addresses.concat(mailargs.bcc); if (mailargs.cc) addresses = addresses.concat(mailargs.cc); // TODO: is there a better way to check for validity? if (addresses.some(function (recipient) !(/\S@\S+\.\S/.test(recipient)))) return void liberator.echoerr("Invalid e-mail address"); mail.composeNewMail(mailargs); }, { options: [[["-subject", "-s"], commands.OPTION_STRING], [["-attachment", "-a"], commands.OPTION_LIST, null, attachmentsCompletion], [["-bcc", "-b"], commands.OPTION_STRING], [["-cc", "-c"], commands.OPTION_STRING], [["-text", "-t"], commands.OPTION_STRING]] }); commands.add(["copy[to]"], "Copy selected messages", function (args) { mail._moveOrCopy(true, args.literalArg); }, { argCount: 1, completer: function (context) completion.mailFolder(context), literal: 0 }); commands.add(["move[to]"], "Move selected messages", function (args) { mail._moveOrCopy(false, args.literalArg); }, { argCount: 1, completer: function (context) completion.mailFolder(context), literal: 0 }); commands.add(["empty[trash]"], "Empty trash of the current account", function () { window.goDoCommand("cmd_emptyTrash"); }, { argCount: "0" }); commands.add(["get[messages]"], "Check for new messages", function (args) mail.getNewMessages(!args.bang), { argCount: "0", bang: true, }); }, completion: function () { completion.mailFolder = function mailFolder(context) { context.anchored = false; context.quote = false; context.completions = [[row[1], "Unread: " + row[0]._folder.getNumUnread(false)] for (row in mail.getAllFolderRowMap(true,true))]; }; }, mappings: function () { var myModes = config.mailModes; mappings.add(myModes, ["<Return>", "m"], "Start message mode", //function () { config.browser.contentWindow.focus(); }); function () { modes.main = modes.MESSAGE; }); mappings.add(myModes, ["M"], "Open the message in new tab", function () { if (gDBView && gDBView.selection.count < 1) return void liberator.beep(); OpenMessageInNewTab({shiftKey: options.getPref("mail.tabs.loadInBackground") }); }); /*mappings.add([modes.NORMAL], ["o"], "Open a message", function () { commandline.open("", "open ", modes.EX); });*/ mappings.add(myModes, ["<Space>"], "Scroll message or select next unread one", function () true, { route: true }); mappings.add(myModes, ["t"], "Select thread", function () { gDBView.ExpandAndSelectThreadByIndex(GetThreadTree().currentIndex, false); }); mappings.add(myModes, ["d", "<Del>"], "Move mail to Trash folder", function () { window.goDoCommand("cmd_delete"); }); mappings.add(myModes, ["j", "<Right>"], "Select next message", function (count) { mail.selectMessage(function (msg) true, false, false, false, count); }, { count: true }); mappings.add(myModes, ["gj"], "Select next message, including closed threads", function (count) { mail.selectMessage(function (msg) true, false, true, false, count); }, { count: true }); mappings.add(myModes, ["J", "<Tab>"], "Select next unread message", function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, false, count); }, { count: true }); mappings.add(myModes, ["k", "<Left>"], "Select previous message", function (count) { mail.selectMessage(function (msg) true, false, false, true, count); }, { count: true }); mappings.add(myModes, ["gk"], "Select previous message", function (count) { mail.selectMessage(function (msg) true, false, true, true, count); }, { count: true }); mappings.add(myModes, ["K"], "Select previous unread message", function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, true, count); }, { count: true }); mappings.add(myModes, ["*"], "Select next message from the same sender", function (count) { try { let author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase(); mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, false, count); } catch (e) { liberator.beep(); } }, { count: true }); mappings.add(myModes, ["#"], "Select previous message from the same sender", function (count) { try { let author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase(); mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, true, count); } catch (e) { liberator.beep(); } }, { count: true }); // SENDING MESSAGES mappings.add(myModes, ["c"], "Compose a new message", function () { commandline.open("", "compose -subject=", modes.EX); }); mappings.add(myModes, ["C"], "Compose a new message to the sender of selected mail", function () { try { let to = mail._escapeRecipient(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor); commandline.open("", "compose " + to + " -subject=", modes.EX); } catch (e) { liberator.beep(); } }); mappings.add(myModes, ["r"], "Reply to sender", function () { window.goDoCommand("cmd_reply"); }); mappings.add(myModes, ["R"], "Reply to all", function () { window.goDoCommand("cmd_replyall"); }); mappings.add(myModes, ["f"], "Forward message", function () { window.goDoCommand("cmd_forward"); }); mappings.add(myModes, ["F"], "Forward message inline", function () { window.goDoCommand("cmd_forwardInline"); }); // SCROLLING mappings.add(myModes, ["<Down>"], "Scroll message down", function (count) { buffer.scrollLines(Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["+"], "Scroll message down pagewise", function (count) { buffer.scrollPages(Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["<Up>"], "Scroll message up", function (count) { buffer.scrollLines(-Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["-"], "Scroll message up pagewise", function (count) { buffer.scrollPages(-Math.max(count, 1)); }, { count: true }); mappings.add([modes.MESSAGE], ["<Left>"], "Select previous message", function (count) { mail.selectMessage(function (msg) true, false, false, true, count); }, { count: true }); mappings.add([modes.MESSAGE], ["<Right>"], "Select next message", function (count) { mail.selectMessage(function (msg) true, false, false, false, count); }, { count: true }); // UNDO/REDO mappings.add(myModes, ["u"], "Undo", function () { if (messenger.canUndo()) messenger.undo(msgWindow); else liberator.beep(); }); mappings.add(myModes, ["<C-r>"], "Redo", function () { if (messenger.canRedo()) messenger.redo(msgWindow); else liberator.beep(); }); // GETTING MAIL mappings.add(myModes, ["gm"], "Get new messages", function () { liberator.echomsg("Fetching mail..."); mail.getNewMessages(); }); mappings.add(myModes, ["gM"], "Get new messages for current account only", function () { liberator.echomsg("Fetching mail for current account..."); mail.getNewMessages(true); }); mappings.add(myModes, ["o"], "Goto folder", function () { commandline.open("", "goto ", modes.EX); }); // MOVING MAIL mappings.add(myModes, ["s"], "Move selected messages", function () { commandline.open("", "moveto ", modes.EX); }); mappings.add(myModes, ["S"], "Copy selected messages", function () { commandline.open("", "copyto ", modes.EX); }); mappings.add(myModes, ["<C-s>"], "Archive message", function () { MsgArchiveSelectedMessages(); }); mappings.add(myModes, ["!"], "Mark/unmark selected messages as junk", function () { JunkSelectedMessages(!SelectedMessagesAreJunk()); }); mappings.add(myModes, ["]s"], "Select next starred message", function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, false, count); }, { count: true }); mappings.add(myModes, ["[s"], "Select previous starred message", function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, true, count); }, { count: true }); mappings.add(myModes, ["]a"], "Select next message with an attachment", function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, false, count); }, { count: true }); mappings.add(myModes, ["[a"], "Select previous message with an attachment", function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, true, count); }, { count: true }); // FOLDER SWITCHING mappings.add(myModes, ["gi"], "Go to inbox", function (count) { let folder = mail.getFoldersWithFlag(Ci.nsMsgFolderFlags.Inbox)[(count > 0) ? (count - 1) : 0] if (folder) SelectFolder(folder.URI); else liberator.beep(); }, { count: true }); mappings.add(myModes, ["<C-n>"], "Select next folder", function (count) { count = Math.max(1, count); let newPos = mail._getCurrentFolderIndex() + count; if (newPos >= gFolderTreeView.rowCount) { newPos = newPos % gFolderTreeView.rowCount; commandline.echo("search hit BOTTOM, continuing at TOP", commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES); } gFolderTreeView.selection.timedSelect(newPos, 500); }, { count: true }); mappings.add(myModes, ["<C-S-N>"], "Go to next mailbox with unread messages", function (count) { mail._selectUnreadFolder(false, count); }, { count: true }); mappings.add(myModes, ["<C-p>"], "Select previous folder", function (count) { count = Math.max(1, count); let newPos = mail._getCurrentFolderIndex() - count; if (newPos < 0) { newPos = (newPos % gFolderTreeView.rowCount) + gFolderTreeView.rowCount; commandline.echo("search hit TOP, continuing at BOTTOM", commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES); } gFolderTreeView.selection.timedSelect(newPos, 500); }, { count: true }); mappings.add(myModes, ["<C-S-P>"], "Go to previous mailbox with unread messages", function (count) { mail._selectUnreadFolder(true, count); }, { count: true }); // THREADING mappings.add(myModes, ["za"], "Toggle thread collapsed/expanded", function () { if (!mail.expandThread()) mail.collapseThread(); }); mappings.add(myModes, ["zc"], "Collapse thread", function () { mail.collapseThread(); }); mappings.add(myModes, ["zo"], "Open thread", function () { mail.expandThread(); }); mappings.add(myModes, ["zr", "zR"], "Expand all threads", function () { window.goDoCommand("cmd_expandAllThreads"); }); mappings.add(myModes, ["zm", "zM"], "Collapse all threads", function () { window.goDoCommand("cmd_collapseAllThreads"); }); mappings.add(myModes, ["<C-i>"], "Go forward", function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.forward, true); }, { count: true }); mappings.add(myModes, ["<C-o>"], "Go back", function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.back, true); }, { count: true }); mappings.add(myModes, ["gg"], "Select first message", function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.firstMessage, true); }, { count: true }); mappings.add(myModes, ["G"], "Select last message", function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.lastMessage, false); }, { count: true }); // tagging messages mappings.add(myModes, ["l"], "Label message", function (arg) { if (!gDBView.numSelected) return void liberator.beep(); switch (arg) { case "r": MsgMarkMsgAsRead(); break; case "s": MsgMarkAsFlagged(); break; case "i": // Important case "1": ToggleMessageTagKey(1); break; case "w": // Work case "2": ToggleMessageTagKey(2); break; case "p": // Personal case "3": ToggleMessageTagKey(3); break; case "t": // TODO case "4": ToggleMessageTagKey(4); break; case "l": // Later case "5": ToggleMessageTagKey(5); break; default: liberator.beep(); } }, { arg: true }); // TODO: change binding? mappings.add(myModes, ["T"], "Mark current folder as read", function () { if (mail.currentFolder.isServer) return liberator.beep(); mail.currentFolder.markAllMessagesRead(msgWindow); }); mappings.add(myModes, ["<C-t>"], "Mark all messages as read", function () { mail.getFolders("", false).forEach(function (folder) { folder.markAllMessagesRead(msgWindow); }); }); // DISPLAY OPTIONS mappings.add(myModes, ["h"], "Toggle displayed headers", function () { let value = gPrefBranch.getIntPref("mail.show_headers", 2); gPrefBranch.setIntPref("mail.show_headers", value == 2 ? 1 : 2); ReloadMessage(); }); mappings.add(myModes, ["x"], "Toggle HTML message display", function () { let wantHtml = (gPrefBranch.getIntPref("mailnews.display.html_as", 1) == 1); mail.setHTML(wantHtml ? 1 : 0); }); // YANKING TEXT mappings.add(myModes, ["y"], "Yank field", function (arg) { try { let text = ""; switch (arg) { case "f": case "y": text = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor; break; case "s": text = gDBView.hdrForFirstSelectedMessage.mime2DecodedSubject; break; case "#": text = gDBView.hdrForFirstSelectedMessage.messageId; break; case "t": text = gDBView.hdrForFirstSelectedMessage.mime2DecodedRecipients; break; case "r": // all recipients let cc = gDBView.hdrForFirstSelectedMessage.ccList; text = gDBView.hdrForFirstSelectedMessage.mime2DecodedRecipients + (cc ? ", " + cc : ""); break; case "u": if (mail.currentAccount.server.type == "rss") { text = util.this._getRSSUrl(); // TODO: util.this? } // if else, yank nothing break; default: liberator.beep(); } util.copyToClipboard(text, true); } catch (e) { liberator.beep(); } }, { arg: true }); // RSS specific mappings mappings.add(myModes, ["p"], "Open RSS message in browser", function () { try { if (mail.currentAccount.server.type == "rss") messenger.launchExternalURL(mail._getRSSUrl()); // TODO: what to do for non-rss message? } catch (e) { liberator.beep(); } }); }, options: function () { // TODO: generate the possible values dynamically from the menu options.add(["layout"], "Set the layout of the mail window", "string", "inherit", { setter: function (value) { switch (value) { case "classic": ChangeMailLayout(0); break; case "wide": ChangeMailLayout(1); break; case "vertical": ChangeMailLayout(2); break; // case "inherit" just does nothing } return value; }, completer: function (context) [ ["inherit", "Default View"], // FIXME: correct description? ["classic", "Classic View"], ["wide", "Wide View"], ["vertical", "Vertical View"] ], validator: Option.validateCompleter }); options.add(["smtpserver", "smtp"], "Set the default SMTP server", "string", services.get("smtpService").defaultServer.key, // TODO: how should we handle these persistent external defaults - "inherit" or null? { getter: function () services.get("smtpService").defaultServer.key, setter: function (value) { let server = mail.smtpServers.filter(function (s) s.key == value)[0]; services.get("smtpService").defaultServer = server; return value; }, completer: function (context) [[s.key, s.serverURI] for ([, s] in Iterator(mail.smtpServers))], validator: Option.validateCompleter }); options.add(["foldermode", "folder"], "Set the folder mode", "string", "smart", { getter: function () gFolderTreeView.mode, setter: function (value) { gFolderTreeView.mode = value; return value; }, completer: function (context) { let modes = gFolderTreeView._modeNames; return modes.map(function(mode) { let name = (mode in gFolderTreeView._modeDisplayNames) ? gFolderTreeView._modeDisplayNames[mode] : document.getElementById("bundle_messenger").getString("folderPaneHeader_" + mode); return [mode, name]; }); }, validator: Option.validateCompleter }); options.add(["remotecontent", "rc"], "Allow display remote content", "boolean", false, { scope: Option.SCOPE_LOCAL, getter: function () { if (config.browser.id == "messagepane") { let msg = gMessageDisplay.displayedMessage; if (msg) return msg.getUint32Property("remoteContentPolicy") == kAllowRemoteContent ? true : false; } }, setter: function (value) { var policy = value ? kAllowRemoteContent : kBlockRemoteContent; if (config.browser.id == "messagepane") { let msg = gMessageDisplay.displayedMessage; if (msg && msg.getUint32Property("remoteContentPolicy") != policy) { msg.setUint32Property("remoteContentPolicy", policy); ReloadMessage(); } } return value; }, }); /*options.add(["threads"], "Use threading to group messages", "boolean", true, { setter: function (value) { if (value) MsgSortThreaded(); else MsgSortUnthreaded(); return value; } });*/ } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const Compose = Module("compose", { init: function () { var stateListener = { QueryInterface: function (id) { if (id.equals(Ci.nsIDocumentStateListener)) return this; throw Cr.NS_NOINTERFACE; }, // this is (also) fired once the new compose window loaded the message for the first time NotifyDocumentStateChanged: function (nowDirty) { // only edit with external editor if this window was not cached! if (options["autoexternal"] && !window.messageWasEditedExternally/* && !gMsgCompose.recycledWindow*/) { window.messageWasEditedExternally = true; editor.editFieldExternally(); } }, NotifyDocumentCreated: function () {}, NotifyDocumentWillBeDestroyed: function () {} }; // XXX: Hack! window.addEventListener("load", function () { if (window.messageWasEditedExternally === undefined) { window.messageWasEditedExternally = false; GetCurrentEditor().addDocumentStateListener(stateListener); } }, true); window.addEventListener("compose-window-close", function () { window.messageWasEditedExternally = false; }, true); } }, { }, { mappings: function () { mappings.add([modes.COMPOSE], ["e"], "Edit message", function () { GetCurrentEditorElement().contentWindow.focus(); editor.editFieldExternally(); }); mappings.add([modes.COMPOSE], ["y"], "Send message now", function () { window.goDoCommand("cmd_sendNow"); }); mappings.add([modes.COMPOSE], ["Y"], "Send message later", function () { window.goDoCommand("cmd_sendLater"); }); // FIXME: does not really work reliably mappings.add([modes.COMPOSE], ["t"], "Select To: field", function () { awSetFocus(0, awGetInputElement(1)); }); mappings.add([modes.COMPOSE], ["s"], "Select Subject: field", function () { GetMsgSubjectElement().focus(); }); mappings.add([modes.COMPOSE], ["i"], "Select message body", function () { SetMsgBodyFrameFocus(); }); mappings.add([modes.COMPOSE], ["q"], "Close composer, ask when for unsaved changes", function () { DoCommandClose(); }); mappings.add([modes.COMPOSE], ["Q", "ZQ"], "Force closing composer", function () { MsgComposeCloseWindow(true); /* cache window for better performance*/ }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const DEFAULT_FAVICON = "chrome://global/skin/icons/Portrait.png"; const Config = Module("config", ConfigBase, { init: function () { // don't wait too long when selecting new messages // GetThreadTree()._selectDelay = 300; // TODO: make configurable }, /*** required options, no checks done if they really exist, so be careful ***/ name: "Muttator", hostApplication: "Thunderbird", get mainWindowId() this.isComposeWindow ? "msgcomposeWindow" : "messengerWindow", /*** optional options, there are checked for existence and a fallback provided ***/ get features() { Object.defineProperty(this, "features", { value: new Set(this.isComposeWindow ? ["addressbook"] : ["hints", "mail", "marks", "addressbook", "tabs"]), }); return this.features; }, defaults: { titlestring: "Muttator" }, toolbars: { composition: [["composeToolbar2"], "Composition toolbar"], folderlist: [["folderPaneBox", "folderpane_splitter"], "Folder list"], mail: [["mail-bar3"], "Main toolbar for getting mail and composing new ones."], menu: [["mail-toolbar-menubar2", "compose-toolbar-menubar2"], "Menu Bar"], tabs: [["tabs-toolbar"], "Tab bar"], status: [["status-bar"], "Status Bar"] }, //get isComposeWindow() window.wintype == "msgcompose", get isComposeWindow() window.document.location == "chrome://messenger/content/messengercompose/messengercompose.xul", get browserModes() [modes.MESSAGE], get mailModes() [modes.NORMAL], // focusContent() focuses this widget get mainWidget() this.isComposeWindow ? document.getElementById("content-frame") : GetThreadTree(), get mainToolbar() document.getElementById(this.isComposeWindow ? "compose-toolbar-menubar2" : "mail-bar3"), get visualbellWindow() document.getElementById(this.mainWindowId), styleableChrome: ["chrome://messenger/content/messenger.xul", "chrome://messenger/content/messengercompose/messengercompose.xul"], autocommands: [["DOMLoad", "Triggered when a page's DOM content has fully loaded"], ["FolderLoad", "Triggered after switching folders in Thunderbird"], ["PageLoadPre", "Triggered after a page load is initiated"], ["PageLoad", "Triggered when a page gets (re)loaded/opened"], ["MuttatorEnter", "Triggered after Thunderbird starts"], ["MuttatorLeave", "Triggered before exiting Thunderbird"], ["MuttatorLeavePre", "Triggered before exiting Thunderbird"]], dialogs: [ ["about", "About Thunderbird", function () { window.openAboutDialog(); }], ["addons", "Manage Add-ons", function () { window.toOpenWindowByType("Addons:Manager", "about:addons", "chrome,centerscreen,resizable,dialog=no,width=700,height=600"); }], ["addressbook", "Address book", function () { window.toAddressBook(); }], ["accounts", "Account Manager", function () { MsgAccountManager(); }], ["checkupdates", "Check for updates", function () { window.checkForUpdates(); }], /*["cleardata", "Clear private data", function () { Cc[GLUE_CID].getService(Ci.nsIBrowserGlue).sanitize(window || null); }],*/ ["console", "JavaScript console", function () { window.toJavaScriptConsole(); }], /*["customizetoolbar", "Customize the Toolbar", function () { BrowserCustomizeToolbar(); }],*/ ["dominspector", "DOM Inspector", function () { window.inspectDOMDocument(content.document); }], ["downloads", "Manage Downloads", function () { window.toOpenWindowByType('Download:Manager', 'chrome://mozapps/content/downloads/downloads.xul', 'chrome,dialog=no,resizable'); }], /*["import", "Import Preferences, Bookmarks, History, etc. from other browsers", function () { BrowserImport(); }], ["openfile", "Open the file selector dialog", function () { BrowserOpenFileWindow(); }], ["pageinfo", "Show information about the current page", function () { BrowserPageInfo(); }], ["pagesource", "View page source", function () { BrowserViewSourceOfDocument(content.document); }],*/ ["preferences", "Show Thunderbird preferences dialog", function () { openOptionsDialog(); }], /*["printpreview", "Preview the page before printing", function () { PrintUtils.printPreview(onEnterPrintPreview, onExitPrintPreview); }],*/ ["printsetup", "Setup the page size and orientation before printing", function () { PrintUtils.showPageSetup(); }], ["print", "Show print dialog", function () { PrintUtils.print(); }], ["saveframe", "Save frame to disk", function () { window.saveFrameDocument(); }], ["savepage", "Save page to disk", function () { window.saveDocument(window.content.document); }], /*["searchengines", "Manage installed search engines", function () { openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }], ["selectionsource", "View selection source", function () { buffer.viewSelectionSource(); }]*/ ], get hasTabbrowser() !this.isComposeWindow, /*focusChange: function (win) { // we switch to -- MESSAGE -- mode for Muttator, when the main HTML widget gets focus if (win && (win.document instanceof HTMLDocument || win.document instanceof XMLDocument) || liberator.focus instanceof HTMLAnchorElement) { if (config.isComposeWindow) modes.set(modes.INSERT, modes.TEXTAREA); else if (liberator.mode != modes.MESSAGE) liberator.mode = modes.MESSAGE; } },*/ get browser() this.isComposeWindow ? window.GetCurrentEditorElement() : window.getBrowser(), tabbrowser: { __proto__: document.getElementById("tabmail"), get mTabContainer() this.tabContainer, get mTabs() this.tabContainer.childNodes, get visibleTabs() Array.slice(this.mTabs), get mCurrentTab() this.tabContainer.selectedItem, get mStrip() this.tabStrip, get browsers() { let browsers = []; for ([,tab] in Iterator(this.tabInfo)) { let func = tab.mode.getBrowser || tab.mode.tabType.getBrowser; if (func) browsers.push(func.call(tab.mode.tabType, tab)); } return browsers; } }, modes: [ ["MESSAGE", { char: "m" }], ["COMPOSE"] ], // NOTE: as I don't use TB I have no idea how robust this is. --djk get outputHeight() { if (!this.isComposeWindow) { let container = document.getElementById("tabpanelcontainer").boxObject; let deck = document.getElementById("displayDeck"); let box = document.getElementById("messagepanebox"); let splitter = document.getElementById("threadpane-splitter").boxObject; if (splitter.width > splitter.height) return container.height - deck.minHeight - box.minHeight- splitter.height; else return container.height - Math.max(deck.minHeight, box.minHeight); } else return document.getElementById("appcontent").boxObject.height; }, get scripts() this.isComposeWindow ? ["compose/compose.js"] : [ "addressbook.js", "mail.js", "tabs.js", ], // to allow Vim to :set ft=mail automatically tempFile: "mutt-ator-mail", }, { }, { commands: function () { commands.add(["pref[erences]", "prefs"], "Show " + config.hostApplication + " preferences", function () { window.openOptionsDialog(); }, { argCount: "0" }); }, modes: function () { this.ignoreKeys = { "<Return>": modes.NORMAL | modes.INSERT, "<Space>": modes.NORMAL | modes.INSERT, "<Up>": modes.INSERT, "<Down>": modes.INSERT }; }, options: function () { // FIXME: comment obviously incorrect // 0: never automatically edit externally // 1: automatically edit externally when message window is shown the first time // 2: automatically edit externally, once the message text gets focus (not working currently) options.add(["autoexternal", "ae"], "Edit message with external editor by default", "boolean", false); if (!this.isComposeWindow) { options.add(["online"], "Set the 'work offline' option", "boolean", true, { setter: function (value) { if (MailOfflineMgr.isOnline() != value) MailOfflineMgr.toggleOfflineStatus(); return value; }, getter: function () MailOfflineMgr.isOnline() }); } } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2009 by Doug Kearns // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const Name = "Muttator"; /* * We can't load our modules here, so the following code is sadly * duplicated: .w !sh vimdiff ../../*'/components/about-handler.js' */ Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); const Cc = Components.classes; const Ci = Components.interfaces; const name = Name.toLowerCase(); function AboutHandler() {} AboutHandler.prototype = { classDescription: "About " + Name + " Page", classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"), contractID: "@mozilla.org/network/protocol/about;1?what=" + name, QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]), newChannel: function (uri) { let channel = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService) .newChannel("chrome://" + name + "/content/about.html", null, null); channel.originalURI = uri; return channel; }, getURIFlags: function (uri) Ci.nsIAboutModule.ALLOW_SCRIPT }; if(XPCOMUtils.generateNSGetFactory) var NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutHandler]); else function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([AboutHandler]); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Header: const Name = "Muttator"; /* * We can't load our modules here, so the following code is sadly * duplicated: .w !sh vimdiff ../../*'/components/commandline-handler.js' */ // Copyright (c) 2009 by Doug Kearns // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); const name = Name.toLowerCase(); function CommandLineHandler() { this.wrappedJSObject = this; } CommandLineHandler.prototype = { classDescription: Name + " Command-line Handler", classID: Components.ID("{16dc34f7-6d22-4aa4-a67f-2921fb5dcb69}"), contractID: "@mozilla.org/commandlinehandler/general-startup;1?type=" + name, _xpcom_categories: [{ category: "command-line-handler", entry: "m-" + name }], QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsICommandLineHandler]), handle: function (commandLine) { // TODO: handle remote launches differently? try { this.optionValue = commandLine.handleFlagWithParam(name, false); } catch (e) { dump(name + ": option '-" + name + "' requires an argument\n"); } } }; if(XPCOMUtils.generateNSGetFactory) var NSGetFactory = XPCOMUtils.generateNSGetFactory([CommandLineHandler]); else function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([CommandLineHandler]); // vim: set ft=javascript fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /* Adds support for data: URIs with chrome privileges * and fragment identifiers. * * "chrome-data:" <content-type> [; <flag>]* "," [<data>] * * By Kris Maglione, ideas from Ed Anuff's nsChromeExtensionHandler. */ const { classes: Cc, interfaces: Ci, utils: Cu } = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyGetter(this, "convert", function () { var obj = new Object; Cu.import("resource://liberator/template.js", obj); return obj.convert; }); const NS_BINDING_ABORTED = 0x804b0002; const nsIProtocolHandler = Ci.nsIProtocolHandler; const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); let channel = Components.classesByID["{61ba33c0-3031-11d3-8cd0-0060b0fc14a3}"] .getService(Ci.nsIProtocolHandler) .newChannel(ioService.newURI("chrome://liberator/content/data", null, null)) .QueryInterface(Ci.nsIRequest); const systemPrincipal = channel.owner; channel.cancel(NS_BINDING_ABORTED); delete channel; function dataURL(type, data) "data:" + (type || "application/xml;encoding=UTF-8") + "," + encodeURIComponent(data); function makeChannel(url, orig) { if (typeof url == "function") url = dataURL.apply(null, url()); let uri = ioService.newURI(url, null, null); let channel = ioService.newChannelFromURI(uri); channel.owner = systemPrincipal; channel.originalURI = orig; return channel; } function fakeChannel(orig) makeChannel("chrome://liberator/content/does/not/exist", orig); function redirect(to, orig) { //xxx: escape let html = '<html><head><meta http-equiv="Refresh" content="' + ("0;" + to).replace(/"/g, "&quot;") + '"/></head></html>'; return makeChannel(dataURL('text/html', html), ioService.newURI(to, null, null)); } XPCOMUtils.defineLazyGetter(this, "cache", function () { var dir = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile); dir.append("liberatorCache"); if (!dir.exists()) { dir.create(dir.DIRECTORY_TYPE, -1); } return dir; }); XPCOMUtils.defineLazyGetter(this, "version", function () { return Services.appinfo.version; }); function ChromeData() {} ChromeData.prototype = { contractID: "@mozilla.org/network/protocol;1?name=chrome-data", classID: Components.ID("{c1b67a07-18f7-4e13-b361-2edcc35a5a0d}"), classDescription: "Data URIs with chrome privileges", QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]), _xpcom_factory: { createInstance: function (outer, iid) { if (!ChromeData.instance) ChromeData.instance = new ChromeData(); if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION; return ChromeData.instance.QueryInterface(iid); } }, scheme: "chrome-data", defaultPort: -1, allowPort: function (port, scheme) false, protocolFlags: nsIProtocolHandler.URI_NORELATIVE | nsIProtocolHandler.URI_NOAUTH | nsIProtocolHandler.URI_IS_UI_RESOURCE, newURI: function (spec, charset, baseURI) { var uri = Cc["@mozilla.org/network/standard-url;1"] .createInstance(Ci.nsIStandardURL) .QueryInterface(Ci.nsIURI); uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, null); return uri; }, newChannel: function (uri) { try { if (uri.scheme == this.scheme) return makeChannel(uri.spec.replace(/^.*?:\/*(.*)(?:#.*)?/, "data:$1"), uri); } catch (e) {} return fakeChannel(); } }; function Liberator() { this.wrappedJSObject = this; const self = this; this.HELP_TAGS = {}; this.FILE_MAP = {}; this.OVERLAY_MAP = {}; } Liberator.prototype = { contractID: "@mozilla.org/network/protocol;1?name=liberator", classID: Components.ID("{9c8f2530-51c8-4d41-b356-319e0b155c44}"), classDescription: "Liberator utility protocol", QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]), _xpcom_factory: { createInstance: function (outer, iid) { if (!Liberator.instance) Liberator.instance = new Liberator(); if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION; return Liberator.instance.QueryInterface(iid); } }, init: function (obj) { for each (let prop in ["HELP_TAGS", "FILE_MAP", "OVERLAY_MAP"]) { this[prop] = this[prop].constructor(); for (let [k, v] in Iterator(obj[prop] || {})) this[prop][k] = v } }, scheme: "liberator", defaultPort: -1, allowPort: function (port, scheme) false, protocolFlags: 0 | nsIProtocolHandler.URI_IS_UI_RESOURCE | nsIProtocolHandler.URI_IS_LOCAL_RESOURCE, newURI: function (spec, charset, baseURI) { var uri = Cc["@mozilla.org/network/standard-url;1"] .createInstance(Ci.nsIStandardURL) .QueryInterface(Ci.nsIURI); uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, baseURI); if (uri.host !== "template") return uri; try { spec = uri.spec; //uri.init(uri.URLTYPE_STANDARD, this.defaultPort, uri.path.substr(1), charset, null); // xxx: uri = ioService.newURI(uri.path.replace(new RegExp("^/+"), ""), charset, null); // recursible when override while (uri.scheme === "chrome") { uri = Cc["@mozilla.org/chrome/chrome-registry;1"] .getService(Ci.nsIChromeRegistry) .convertChromeURL(uri); } var nest = Cc["@mozilla.org/network/util;1"].getService(Ci.nsINetUtil).newSimpleNestedURI(uri); nest.spec = spec; } catch (ex) { Cu.reportError(ex); } return nest; }, newChannel: function (uri) { try { if ((uri instanceof Ci.nsINestedURI)) { var m = (new RegExp("^/{2,}([^/]+)/([^?]+)")).exec(uri.path); if (m) { var host = m[1]; var path = m[2]; switch (host) { case "template": try { var nest = ioService.newURI(path, uri.charset, null); var channel = ioService.newChannelFromURI(nest); // xxx: support template if (0) return channel; // xxx: NG: Firefox 16, 17 // NG: Cu.import if (parseFloat(version) < 17) { var stream = Cc["@mozilla.org/scriptableinputstream;1"] .createInstance(Ci.nsIScriptableInputStream); var cstream = channel.open(); stream.init(cstream); var text = stream.read(-1); stream.close(); cstream.close(); stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream); stream.setData(convert(text), -1); var channel = Cc["@mozilla.org/network/input-stream-channel;1"] .createInstance(Ci.nsIInputStreamChannel); channel.contentStream = stream; channel.QueryInterface(Ci.nsIChannel); channel.setURI(uri); return channel; } var innerURI = uri.innerURI; var temp = cache.clone(); var path = nest.spec.replace(/[:\/]/g, "_"); var lastModifiedTime; if (innerURI.scheme === "resource") { innerURI = Cc["@mozilla.org/network/protocol;1?name=resource"] .getService(Ci.nsIResProtocolHandler).resolveURI(innerURI); innerURI = ioService.newURI(innerURI, null, null); } if (innerURI.scheme === "jar") { innerURI = innerURI.QueryInterface(Ci.nsIJARURI).JARFile; } if (innerURI.scheme === "file") { lastModifiedTime = innerURI.QueryInterface(Ci.nsIFileURL).file.lastModifiedTime; } else { Cu.reportError("do not support:" + innerURI.spec); } temp.append(path); if (!temp.exists() || temp.lastModifiedTime !== lastModifiedTime) { var stream = Cc["@mozilla.org/scriptableinputstream;1"] .createInstance(Ci.nsIScriptableInputStream); var cstream = channel.open(); stream.init(cstream); var text = stream.read(-1); stream.close(); cstream.close(); text = convert(text); var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream); Services.console.logStringMessage("create:" + temp.leafName); stream.init(temp, 0x2 | 0x8 | 0x20, 0644, 0); stream.write(text, text.length); stream.close(); temp.lastModifiedTime = lastModifiedTime; } else { Services.console.logStringMessage("use cache:" + uri.spec); } return ioService.newChannelFromURI(ioService.newFileURI(temp)); } catch (ex) { Cu.reportError(ex); } } } return fakeChannel(uri); } switch(uri.host) { case "help": let url = this.FILE_MAP[uri.path.replace(/^\/|#.*/g, "")]; return makeChannel(url, uri); case "help-overlay": url = this.OVERLAY_MAP[uri.path.replace(/^\/|#.*/g, "")]; return makeChannel(url, uri); case "help-tag": let tag = uri.path.substr(1); if (tag in this.HELP_TAGS) return redirect("liberator://help/" + this.HELP_TAGS[tag] + "#" + tag, uri); } } catch (e) { Cu.reportError(e); } return fakeChannel(uri); } }; var components = [ChromeData, Liberator]; if(XPCOMUtils.generateNSGetFactory) var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); else function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule(components); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2012 by Martin Stubenschrott <stubenschrott AT vimperator> // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const IgnoreKeys = Module("ignoreKeys", { requires: ["config", "storage"], init: function init() { this._ignoredKeys = storage.newMap("ignored-keys", { store: true, privateData: true }); }, add: function add(filter, exceptions) { if (!exceptions) exceptions = []; // TODO: Add a regular expression cache somewhere? this._ignoredKeys.set(filter, exceptions); }, get: function get(filter) { let filtered = []; for (let [page, exceptions] in this._ignoredKeys) { if (!filter || page.indexOf(filter) >= 0) filtered.push([page, exceptions]); } return filtered; }, hasIgnoredKeys: function isKeyIgnored(url) { for (let [page, exceptions] in this._ignoredKeys) { let re = RegExp(page); if (re.test(url)) return exceptions; } return null; }, isKeyIgnored: function isKeyIgnored(url, key) { // Don't cripple Vimperator ;) Later this will be part of a new "unignorekeys" option if (key == ":") return false; for (let [page, exceptions] in this._ignoredKeys) { let re = RegExp(page); if (re.test(url) && exceptions.indexOf(key) < 0) return true; } return false; }, remove: function remove(filter) { if (!filter) { liberator.echoerr("Invalid filter"); return; } for (let [page, ] in this._ignoredKeys) { if (filter == page) this._ignoredKeys.remove(page); } }, clear: function clear() { this._ignoredKeys.clear(); } }, { }, { mappings: function () { mappings.add([modes.NORMAL], ["I"], "Open an :ignorekeys prompt for the current domain or URL", function (count) { commandline.open("", "ignorekeys add ", modes.EX); }, { count: false }); }, commands: function () { commands.add(["ignore[keys]"], "Ignore all (or most) " + config.name + " keys for certain URLs", function (args) { // Without argument, list current pages with ignored keys completion.listCompleter("ignorekeys"); }, { subCommands: [ new Command(["add"], "Add an URL filter to the list of ignored keys", function (args) { ignoreKeys.add(args[0], args["-except"] || []); }, { argCount: "1", options: [ [["-except", "-e"], commands.OPTION_LIST, null, null], ], completer: function (context, args) { let completions = []; if (args.completeArg == 0) { if (buffer.URL) completions.unshift([util.escapeRegex(buffer.URL), "Current URL"]); if (content.document && content.document.domain) completions.unshift([util.escapeRegex(content.document.domain), "Current domain"]); } context.compare = CompletionContext.Sort.unsorted; context.completions = completions; } }), new Command(["clear"], "Clear all ignored pages", function (args) { ignoreKeys.clear(); }, { argCount: 0 }), new Command(["list", "ls"], "List pages with ignored keys", function (args) { let res = ignoreKeys.get(args.literalArg || ""); if (res.length == undefined || res.length == 0) { if (!args.literalArg) liberator.echomsg("No ignored keys"); else liberator.echomsg("No ignored keys for pages matching " + args.literalArg); return; } completion.listCompleter("ignorekeys", args.literalArg || ""); }, { argCount: "?", literal: 0 }), new Command(["remove", "rm"], "Remove an URL filter from the list of ignored keys", function (args) { ignoreKeys.remove(args.literalArg || ""); }, { argCount: 1, literal: 0, completer: function (context, args) completion.ignorekeys(context, args.literalArg || ""), }) ] }); }, completion: function () { completion.ignorekeys = function (context) { context.title = ["URL filter", "Ignored keys"]; context.anchored = false; // match the filter anywhere context.completions = ignoreKeys.get(); }; } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const Config = Module("config", ConfigBase, { init: function () { }, /*** required options, no checks done if they really exist, so be careful ***/ name: "Vimperator", hostApplication: "Firefox", features: new Set(["bookmarks", "hints", "history", "marks", "quickmarks", "sanitizer", "session", "tabs", "tabs_undo", "windows", "tabgroup", "privatebrowsing"]), /*** optional options, there are checked for existence and a fallback provided ***/ autocommands: [["BookmarkAdd", "Triggered after a page is bookmarked"], ["ColorScheme", "Triggered after a color scheme has been loaded"], ["DOMLoad", "Triggered when a page's DOM content has fully loaded"], ["DownloadPost", "Triggered when a download has completed"], ["Fullscreen", "Triggered when the browser's fullscreen state changes"], ["LocationChange", "Triggered when changing tabs or when navigation to a new location"], ["PageLoadPre", "Triggered after a page load is initiated"], ["PageLoad", "Triggered when a page gets (re)loaded/opened"], // TODO: remove when FF ESR's version is over 20 ["PrivateMode", "Triggered when private mode is activated or deactivated"], ["Sanitize", "Triggered when a sanitizeable item is cleared"], ["ShellCmdPost", "Triggered after executing a shell command with :!cmd"], ["VimperatorEnter", "Triggered after Firefox starts"], ["VimperatorLeavePre", "Triggered before exiting Firefox, just before destroying each module"], ["VimperatorLeave", "Triggered before exiting Firefox"]], defaults: { complete: "slf", titlestring: "Vimperator" }, dialogs: [ ["about", "About Firefox", function () { window.openDialog("chrome://browser/content/aboutDialog.xul", "_blank", "chrome,dialog,modal,centerscreen"); }], ["addbookmark", "Add bookmark for the current page", function () { PlacesCommandHook.bookmarkCurrentPage(true, PlacesUtils.bookmarksRootId); }], ["addons", "Manage Add-ons", function () { window.toOpenWindowByType("Addons:Manager", "about:addons", "chrome,centerscreen,resizable,dialog=no,width=700,height=600"); }], ["bookmarks", "List your bookmarks", function () { window.openDialog("chrome://browser/content/bookmarks/bookmarksPanel.xul", "Bookmarks", "dialog,centerscreen,width=600,height=600"); }], ["checkupdates", "Check for updates", // show the About dialog which includes the Check For Updates button function () { window.openDialog("chrome://browser/content/aboutDialog.xul", "_blank", "chrome,dialog,modal,centerscreen"); }], /*function () { window.checkForUpdates(); }],*/ ["cleardata", "Clear private data", function () { Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIBrowserGlue).sanitize(window || null); }], ["cookies", "List your cookies", function () { window.toOpenWindowByType("Browser:Cookies", "chrome://browser/content/preferences/cookies.xul", "chrome,dialog=no,resizable"); }], ["console", "JavaScript console", function () { window.toJavaScriptConsole(); }], ["customizetoolbar", "Customize the Toolbar", function () { window.BrowserCustomizeToolbar(); }], ["dominspector", "DOM Inspector", function () { try { window.inspectDOMDocument(content.document); } catch (e) { liberator.echoerr("DOM Inspector extension not installed"); } }], ["downloads", "Manage Downloads", function () { window.toOpenWindowByType("Download:Manager", "chrome://mozapps/content/downloads/downloads.xul", "chrome,dialog=no,resizable"); }], ["history", "List your history", function () { window.openDialog("chrome://browser/content/history/history-panel.xul", "History", "dialog,centerscreen,width=600,height=600"); }], ["import", "Import Preferences, Bookmarks, History, etc. from other browsers", function () { var tmp = {}; Cu.import("resource://app/modules/MigrationUtils.jsm", tmp); tmp.MigrationUtils.showMigrationWizard(window); } ], ["openfile", "Open the file selector dialog", function () { window.BrowserOpenFileWindow(); }], ["pageinfo", "Show information about the current page", function () { window.BrowserPageInfo(); }], ["pagesource", "View page source", function () { window.BrowserViewSourceOfDocument(content.document); }], ["passwords", "Show passwords window", function () { window.openDialog("chrome://passwordmgr/content/passwordManager.xul"); }], ["places", "Places Organizer: Manage your bookmarks and history", function () { PlacesCommandHook.showPlacesOrganizer(ORGANIZER_ROOT_BOOKMARKS); }], ["preferences", "Show Firefox preferences dialog", function () { var features = "chrome,titlebar,toolbar,centerscreen," + (options.getPref("browser.preferences.instantApply", false) ? "dialog=no" : "modal"); window.toOpenWindowByType("Browser:Preferences", "chrome://browser/content/preferences/preferences.xul", features); }], ["printpreview", "Preview the page before printing", function () { PrintUtils.printPreview(PrintPreviewListener); }], ["printsetup", "Setup the page size and orientation before printing", function () { PrintUtils.showPageSetup(); }], ["print", "Show print dialog", function () { PrintUtils.print(); }], ["saveframe", "Save frame to disk", function () { window.saveFrameDocument(); }], ["savepage", "Save page to disk", function () { window.saveDocument(window.content.document); }], ["searchengines", "Manage installed search engines", function () { window.openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }], ["selectionsource", "View selection source", function () { buffer.viewSelectionSource(); }] ], hasTabbrowser: true, ignoreKeys: {}, get mainToolbar() document.getElementById("nav-bar"), scripts: [ "browser.js", "bookmarks.js", "history.js", "ignorekeys.js", "quickmarks.js", "sanitizer.js", "tabs.js", "tabgroup.js", ], styleableChrome: ["chrome://browser/content/browser.xul"], get tempFile() { let prefix = this.name.toLowerCase(); try { prefix += "-" + window.content.document.location.hostname; } catch (e) {} return prefix + ".tmp"; }, toolbars: { addons: [["addon-bar"], "Add-on bar. By default, only visible if you have addons installed."], bookmarks: [["PersonalToolbar"], "Bookmarks Toolbar"], menu: [["toolbar-menubar"], "Menu Bar"], navigation: [["nav-bar"], "Main toolbar with back/forward buttons location box"], tabs: [["TabsToolbar"], "Tab bar"] }, get visualbellWindow() getBrowser().mPanelContainer }, { }, { commands: function () { commands.add(["winon[ly]"], "Close all other windows", function () { liberator.windows.forEach(function (win) { if (win != window) win.close(); }); }, { argCount: "0" }); commands.add(["pref[erences]", "prefs"], "Show " + config.hostApplication + " preferences", function (args) { if (args.bang) { // open Firefox settings GUI dialog liberator.open("about:config", (options["newtab"] && options.get("newtab").has("all", "prefs")) ? liberator.NEW_TAB : liberator.CURRENT_TAB); } else window.openPreferences(); }, { argCount: "0", bang: true }); commands.add(["sbcl[ose]"], "Close the sidebar window", function () { if (!document.getElementById("sidebar-box").hidden) window.toggleSidebar(); }, { argCount: "0" }); commands.add(["sideb[ar]", "sb[ar]", "sbope[n]"], "Open the sidebar window", function (args) { let arg = args.literalArg; function compare(a, b) util.compareIgnoreCase(a, b) == 0 // focus if the requested sidebar is already open if (compare(document.getElementById("sidebar-title").value, arg)) { document.getElementById("sidebar-box").focus(); return; } let menu = document.getElementById("viewSidebarMenu"); for (let [, panel] in Iterator(menu.childNodes)) { if (compare(panel.label, arg)) { panel.doCommand(); return; } } liberator.echoerr("No such sidebar: " + arg); }, { argCount: "1", completer: function (context) { context.ignoreCase = true; return completion.sidebar(context); }, literal: 0 }); commands.add(["wind[ow]"], "Execute a command and tell it to output in a new window", function (args) { var prop = args["-private"] ? "forceNewPrivateWindow" : "forceNewWindow"; try { liberator[prop] = true; liberator.execute(args.literalArg, null, true); } finally { liberator[prop] = false; } }, { argCount: "+", options: [ [["-private", "-p"], commands.OPTION_NOARG], ], completer: function (context) completion.ex(context), literal: 0 }); commands.add(["winc[lose]", "wc[lose]"], "Close window", function () { window.close(); }, { argCount: "0" }); commands.add(["wino[pen]", "wo[pen]"], "Open one or more URLs in a new window", function (args) { var where = args["-private"] ? liberator.NEW_PRIVATE_WINDOW : liberator.NEW_WINDOW; args = args.literalArg; if (args) liberator.open(args, where); else liberator.open("", where); }, { options: [ [["-private", "-p"], commands.OPTION_NOARG], ], completer: function (context) completion.url(context), literal: 0, privateData: true }); }, completion: function () { completion.location = function location(context) { if (!services.get("autoCompleteSearch")) return; context.anchored = false; context.title = ["Smart Completions"]; context.keys.icon = 2; context.incomplete = true; context.hasItems = context.completions.length > 0; // XXX context.filterFunc = null; context.cancel = function () { services.get("autoCompleteSearch").stopSearch(); context.completions = []; }; context.compare = CompletionContext.Sort.unsorted; services.get("autoCompleteSearch").stopSearch(); // just to make sure we cancel old running completions let timer = new Timer(50, 100, function (result) { context.incomplete = result.searchResult >= result.RESULT_NOMATCH_ONGOING; context.completions = [ [result.getValueAt(i), result.getCommentAt(i), result.getImageAt(i)] for (i in util.range(0, result.matchCount)) ]; }); services.get("autoCompleteSearch").startSearch(context.filter, "", context.result, { onSearchResult: function onSearchResult(search, result) { timer.tell(result); if (result.searchResult <= result.RESULT_SUCCESS) { timer.flush(); } } }); }; completion.sidebar = function sidebar(context) { let menu = document.getElementById("viewSidebarMenu"); context.title = ["Sidebar Panel"]; context.completions = Array.map(menu.childNodes, function (n) [n.label, ""]); }; completion.addUrlCompleter("l", "Firefox location bar entries (bookmarks and history sorted in an intelligent way)", completion.location); }, modes: function () { this.ignoreKeys = { "<Return>": modes.NORMAL | modes.INSERT, "<Space>": modes.NORMAL | modes.INSERT, "<Up>": modes.NORMAL | modes.INSERT, "<Down>": modes.NORMAL | modes.INSERT }; }, options: function () { options.add(["online"], "Set the 'work offline' option", "boolean", true, { setter: function (value) { const ioService = services.get("io"); if (ioService.offline == value) BrowserOffline.toggleOfflineStatus(); return value; }, getter: function () !services.get("io").offline }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2011-2012 by teramako <teramako at Gmail> // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ // TODO: many methods do not work with Thunderbird correctly yet /** * @instance tabgroup */ const TabGroup = Module("tabGroup", { requires: ["config", "tabs"], TV: window.TabView, get tabView () { const TV = window.TabView; if (!TV) return null; if (!TV._window || !TV._window.GroupItems) { let waiting = true; TV._initFrame(function() { waiting = false; }); while (waiting) liberator.threadYield(false, true); } delete this.tabView; return this.tabView = TV._window; }, get appTabs () { var apps = []; for (let tab of config.tabbrowser.tabs) { if (tab.pinned) apps.push(tab); else break; } return apps; }, /** * @param {string|number} name * @param {number} count * @return {GroupItem} */ getGroup: function getGroup (name, count) { let i = 0; if (!count) count = 1; let test; if (typeof name == "number") test = function (g) g.id == name; else { name = name.toLowerCase(); let id; let matches = name.match(/^(\d+)(?::(?:\s+(.*))?)?$/); if (matches) [, id, name] = matches; if (id) { id = parseInt(id, 10); test = function (g) g.id == id; } else test = function (g) g.getTitle().toLowerCase() == name; } for (let group of this.tabView.GroupItems.groupItems) { if (test(group)) { i++; if (i == count) return group; } } return null; }, /** * switch to a group or an orphaned tab * @param {String|Number} spec * @param {Boolean} wrap */ switchTo: function (spec, wrap) { const GI = tabGroup.tabView.GroupItems; let current = GI.getActiveGroupItem() || GI.getActiveOrphanTab(); let groups = GI.groupItems; let offset = 1, relative = false, index; if (typeof spec === "number") index = parseInt(spec, 10); else if (/^[+-]\d+$/.test(spec)) { let buf = parseInt(spec, 10); index = groups.indexOf(current) + buf; offset = buf >= 0 ? 1 : -1; relative = true; } else if (spec != "") { let targetGroup = tabGroup.getGroup(spec); if (targetGroup) index = groups.indexOf(targetGroup); else { liberator.echoerr("No such tab group: " + spec); return; } } else return; let length = groups.length; let apps = tabGroup.appTabs; function groupSwitch (index, wrap) { if (index > length - 1) index = wrap ? index % length : length - 1; else if (index < 0) index = wrap ? index % length + length : 0; let target = groups[index], group = null; if (target instanceof tabGroup.tabView.GroupItem) { group = target; target = target.getActiveTab() || target.getChild(0); } if (target) gBrowser.mTabContainer.selectedItem = target.tab; // for empty group else if (group) { if (apps.length === 0) group.newTab(); else { GI.setActiveGroupItem(group); tabGroup.tabView.UI.goToTab(tabs.getTab(0)); } } else if (relative) groupSwitch(index + offset, true); else { liberator.echoerr("Cannot switch to tab group: " + spec); return; } } groupSwitch(index, wrap); }, /** * @param {string} name Group Name * @param {boolean} shouldSwitch switch to the created group if true * @param {element} tab * @return {GroupItem} created GroupItem instance */ createGroup: function createGroup (name, shouldSwitch, tab) { let pageBounds = tabGroup.tabView.Items.getPageBounds(); pageBounds.inset(20, 20); let box = new tabGroup.tabView.Rect(pageBounds); box.width = 125; box.height = 110; let group = new tabGroup.tabView.GroupItem([], { bounds: box, title: name }); if (tab && !tab.pinned) tabGroup.TV.moveTabTo(tab, group.id); if (shouldSwitch) { let appTabs = tabGroup.appTabs, child = group.getChild(0); if (child) { tabGroup.tabView.GroupItems.setActiveGroupItem(group); tabGroup.tabView.UI.goToTab(child.tab); } else if (appTabs.length == 0) group.newTab(); else { tabGroup.tabView.GroupItems.setActiveGroupItem(group); tabGroup.tabView.UI.goToTab(appTabs[appTabs.length - 1]); } } return group; }, /** * @param {element} tab element * @param {GroupItem||string} group See {@link tabGroup.getGroup}. * @param {boolean} create Create a new group named {group} * if {group} doesn't exist. */ moveTab: function moveTabToGroup (tab, group, shouldSwitch) { liberator.assert(tab && !tab.pinned, "Cannot move an AppTab"); let groupItem = (group instanceof tabGroup.tabView.GroupItem) ? group : tabGroup.getGroup(group); liberator.assert(groupItem, "No such group: " + group); if (groupItem) { tabGroup.TV.moveTabTo(tab, groupItem.id); if (shouldSwitch) tabGroup.tabView.UI.goToTab(tab); } }, /** * close all tabs in the {groupName}'s or current group * @param {string} groupName */ remove: function removeGroup (groupName) { const GI = tabGroup.tabView.GroupItems; let activeGroup = GI.getActiveGroupItem(); let group = groupName ? tabGroup.getGroup(groupName) : activeGroup; liberator.assert(group, "No such group: " + groupName); if (group === activeGroup) { let gb = config.tabbrowser; let vTabs = gb.visibleTabs; if (vTabs.length < gb.tabs.length) tabGroup.switchTo("+1", true); else { let appTabs = tabGroup.appTabs; if (appTabs.length == 0) gb.loadOnTab(window.BROWSER_NEW_TAB_URL || "about:blank", { inBackground: false, relatedToCurrent: false }); else gb.mTabContainer.selectedIndex = appTabs.length - 1; for (let i = vTabs.length - 1, tab; (tab = vTabs[i]) && !tab.pinned; i--) gb.removeTab(tab); return; } } group.closeAll(); } }, { }, { mappings: function () { mappings.add([modes.NORMAL], ["g@"], "Go to an AppTab", function (count) { let appTabs = tabGroup.appTabs; let i = 0; if (count != null) i = count - 1; else { let currentTab = tabs.getTab(); if (currentTab.pinned) i = appTabs.indexOf(currentTab) + 1; i %= appTabs.length; } if (appTabs[i]) config.tabbrowser.mTabContainer.selectedIndex = i; }, { count: true }); mappings.add([modes.NORMAL], ["<C-S-n>", "<C-S-PageDown>"], "Switch to next tab group", function (count) { tabGroup.switchTo("+" + (count || 1), true); }, { count: true }); mappings.add([modes.NORMAL], ["<C-S-p>", "<C-S-PageUp>"], "Switch to previous tab group", function (count) { tabGroup.switchTo("-" + (count || 1), true); }, { count: true }); }, commands: function () { let panoramaSubCommands = [ /** * Panorama SubCommand add * make a group and switch to the group. * take up the current tab to the group if bang(!) specified. */ new Command(["add"], "Create a new tab group", function (args) { tabGroup.createGroup(args.literalArg, true, args.bang ? tabs.getTab() : null); }, { bang: true, literal: 0 }), /** * Panorama SubCommand list * list current tab groups */ new Command(["list", "ls"], "List current tab groups", function (args) { completion.listCompleter("tabgroup"); }, { bang: false, argCount: 0 }), /** * Panorama SubCommad pullTab * pull the other group's tab */ new Command(["pull[tab]"], "Pull a tab from another group", function (args) { let activeGroup = tabGroup.tabView.GroupItems.getActiveGroupItem(); if (!activeGroup) { liberator.echoerr("Cannot pull tab to the current group"); return; } let buffer = args.literalArg; if (!buffer) return; let tabItems = tabs.getTabsFromBuffer(buffer); if (tabItems.length == 0) { liberator.echoerr("No matching buffer for: " + buffer); return; } else if (tabItems.length > 1) { liberator.echoerr("More than one match for: " + buffer); return; } tabGroup.moveTab(tabItems[0], activeGroup, args.bang); }, { bang: true, literal: 0, completer: function (context) completion.buffer(context), }), /** * Panorama SubCommand pushTab * stash the current tab to the {group} * create {group} and stash if bang(!) specified and {group} doesn't exists. */ new Command(["push[tab]", "stash"], "Move the current tab to another group", function (args) { let currentTab = tabs.getTab(); if (currentTab.pinned) { liberator.echoerr("Cannot move an App Tab"); return; } let groupName = args.literalArg; let group = tabGroup.getGroup(groupName); if (!group) { if (args.bang) group = tabGroup.createGroup(groupName); else { liberator.echoerr("No such group: " + groupName.quote() + ". Add \"!\" if you want to create it."); return; } } tabGroup.moveTab(currentTab, group); }, { bang: true, literal: 0, completer: function (context) completion.tabgroup(context, true), }), /** * Panorama SubCommand remove * remove {group}. * remove the current group if {group} is ommited. */ new Command(["remove", "rm"], "Close the tab group (including all tabs!)", function (args) { tabGroup.remove(args.literalArg); }, { literal: 0, completer: function (context) completion.tabgroup(context, false), }), /** * Panorama SubCommand switch * switch to the {group}. * switch to {count}th next group if {count} specified. */ new Command(["switch"], "Switch to another group", function (args) { if (args.count > 0) tabGroup.switchTo("+" + args.count, true); else tabGroup.switchTo(args.literalArg); }, { count: true, literal: 0, completer: function (context) completion.tabgroup(context, true), }), ]; commands.add(["tabgroups", "panorama"], "Manage tab groups", function (args) { // Without argument, list current groups completion.listCompleter("tabgroup"); }, { subCommands: panoramaSubCommands }); }, completion: function () { completion.tabgroup = function TabGroupCompleter (context, excludeActiveGroup) { const GI = tabGroup.tabView.GroupItems; let groupItems = GI.groupItems; if (excludeActiveGroup) { let activeGroup = GI.getActiveGroupItem(); if (activeGroup) groupItems = groupItems.filter(function(group) group.id != activeGroup.id); } context.title = ["Tab Group"]; context.anchored = false; context.completions = groupItems.map(function(group) { let title = group.id + ": " + (group.getTitle() || "(Untitled)"); let desc = "Tabs: " + group.getChildren().length; return [title, desc]; }); }; }, options: function () { options.add(["apptab", "app"], "Pin the current tab as App Tab", "boolean", false, { scope: Option.SCOPE_LOCAL, setter: function (value) { config.tabbrowser[value ? "pinTab" : "unpinTab"](tabs.getTab()); return value; }, getter: function () { return tabs.getTab().pinned; } }); }, }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2009 by Doug Kearns // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const Name = "Vimperator"; /* * We can't load our modules here, so the following code is sadly * duplicated: .w !sh vimdiff ../../*'/components/about-handler.js' */ Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); const Cc = Components.classes; const Ci = Components.interfaces; const name = Name.toLowerCase(); function AboutHandler() {} AboutHandler.prototype = { classDescription: "About " + Name + " Page", classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"), contractID: "@mozilla.org/network/protocol/about;1?what=" + name, QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]), newChannel: function (uri) { let channel = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService) .newChannel("chrome://" + name + "/content/about.html", null, null); channel.originalURI = uri; return channel; }, getURIFlags: function (uri) Ci.nsIAboutModule.ALLOW_SCRIPT }; if(XPCOMUtils.generateNSGetFactory) var NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutHandler]); else function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([AboutHandler]); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Header: const Name = "Vimperator"; /* * We can't load our modules here, so the following code is sadly * duplicated: .w !sh vimdiff ../../*'/components/commandline-handler.js' */ // Copyright (c) 2009 by Doug Kearns // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); const name = Name.toLowerCase(); function CommandLineHandler() { this.wrappedJSObject = this; } CommandLineHandler.prototype = { classDescription: Name + " Command-line Handler", classID: Components.ID("{16dc34f7-6d22-4aa4-a67f-2921fb5dcb69}"), contractID: "@mozilla.org/commandlinehandler/general-startup;1?type=" + name, _xpcom_categories: [{ category: "command-line-handler", entry: "m-" + name }], QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsICommandLineHandler]), handle: function (commandLine) { // TODO: handle remote launches differently? try { this.optionValue = commandLine.handleFlagWithParam(name, false); } catch (e) { dump(name + ": option '-" + name + "' requires an argument\n"); } } }; if(XPCOMUtils.generateNSGetFactory) var NSGetFactory = XPCOMUtils.generateNSGetFactory([CommandLineHandler]); else function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([CommandLineHandler]); // vim: set ft=javascript fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /* Adds support for data: URIs with chrome privileges * and fragment identifiers. * * "chrome-data:" <content-type> [; <flag>]* "," [<data>] * * By Kris Maglione, ideas from Ed Anuff's nsChromeExtensionHandler. */ const { classes: Cc, interfaces: Ci, utils: Cu } = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyGetter(this, "convert", function () { var obj = new Object; Cu.import("resource://liberator/template.js", obj); return obj.convert; }); const NS_BINDING_ABORTED = 0x804b0002; const nsIProtocolHandler = Ci.nsIProtocolHandler; const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); let channel = Components.classesByID["{61ba33c0-3031-11d3-8cd0-0060b0fc14a3}"] .getService(Ci.nsIProtocolHandler) .newChannel(ioService.newURI("chrome://liberator/content/data", null, null)) .QueryInterface(Ci.nsIRequest); const systemPrincipal = channel.owner; channel.cancel(NS_BINDING_ABORTED); delete channel; function dataURL(type, data) "data:" + (type || "application/xml;encoding=UTF-8") + "," + encodeURIComponent(data); function makeChannel(url, orig) { if (typeof url == "function") url = dataURL.apply(null, url()); let uri = ioService.newURI(url, null, null); let channel = ioService.newChannelFromURI(uri); channel.owner = systemPrincipal; channel.originalURI = orig; return channel; } function fakeChannel(orig) makeChannel("chrome://liberator/content/does/not/exist", orig); function redirect(to, orig) { //xxx: escape let html = '<html><head><meta http-equiv="Refresh" content="' + ("0;" + to).replace(/"/g, "&quot;") + '"/></head></html>'; return makeChannel(dataURL('text/html', html), ioService.newURI(to, null, null)); } XPCOMUtils.defineLazyGetter(this, "cache", function () { var dir = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile); dir.append("liberatorCache"); if (!dir.exists()) { dir.create(dir.DIRECTORY_TYPE, -1); } return dir; }); XPCOMUtils.defineLazyGetter(this, "version", function () { return Services.appinfo.version; }); function ChromeData() {} ChromeData.prototype = { contractID: "@mozilla.org/network/protocol;1?name=chrome-data", classID: Components.ID("{c1b67a07-18f7-4e13-b361-2edcc35a5a0d}"), classDescription: "Data URIs with chrome privileges", QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]), _xpcom_factory: { createInstance: function (outer, iid) { if (!ChromeData.instance) ChromeData.instance = new ChromeData(); if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION; return ChromeData.instance.QueryInterface(iid); } }, scheme: "chrome-data", defaultPort: -1, allowPort: function (port, scheme) false, protocolFlags: nsIProtocolHandler.URI_NORELATIVE | nsIProtocolHandler.URI_NOAUTH | nsIProtocolHandler.URI_IS_UI_RESOURCE, newURI: function (spec, charset, baseURI) { var uri = Cc["@mozilla.org/network/standard-url;1"] .createInstance(Ci.nsIStandardURL) .QueryInterface(Ci.nsIURI); uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, null); return uri; }, newChannel: function (uri) { try { if (uri.scheme == this.scheme) return makeChannel(uri.spec.replace(/^.*?:\/*(.*)(?:#.*)?/, "data:$1"), uri); } catch (e) {} return fakeChannel(); } }; function Liberator() { this.wrappedJSObject = this; const self = this; this.HELP_TAGS = {}; this.FILE_MAP = {}; this.OVERLAY_MAP = {}; } Liberator.prototype = { contractID: "@mozilla.org/network/protocol;1?name=liberator", classID: Components.ID("{9c8f2530-51c8-4d41-b356-319e0b155c44}"), classDescription: "Liberator utility protocol", QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]), _xpcom_factory: { createInstance: function (outer, iid) { if (!Liberator.instance) Liberator.instance = new Liberator(); if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION; return Liberator.instance.QueryInterface(iid); } }, init: function (obj) { for each (let prop in ["HELP_TAGS", "FILE_MAP", "OVERLAY_MAP"]) { this[prop] = this[prop].constructor(); for (let [k, v] in Iterator(obj[prop] || {})) this[prop][k] = v } }, scheme: "liberator", defaultPort: -1, allowPort: function (port, scheme) false, protocolFlags: 0 | nsIProtocolHandler.URI_IS_UI_RESOURCE | nsIProtocolHandler.URI_IS_LOCAL_RESOURCE, newURI: function (spec, charset, baseURI) { var uri = Cc["@mozilla.org/network/standard-url;1"] .createInstance(Ci.nsIStandardURL) .QueryInterface(Ci.nsIURI); uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, baseURI); if (uri.host !== "template") return uri; try { spec = uri.spec; //uri.init(uri.URLTYPE_STANDARD, this.defaultPort, uri.path.substr(1), charset, null); // xxx: uri = ioService.newURI(uri.path.replace(new RegExp("^/+"), ""), charset, null); // recursible when override while (uri.scheme === "chrome") { uri = Cc["@mozilla.org/chrome/chrome-registry;1"] .getService(Ci.nsIChromeRegistry) .convertChromeURL(uri); } var nest = Cc["@mozilla.org/network/util;1"].getService(Ci.nsINetUtil).newSimpleNestedURI(uri); nest.spec = spec; } catch (ex) { Cu.reportError(ex); } return nest; }, newChannel: function (uri) { try { if ((uri instanceof Ci.nsINestedURI)) { var m = (new RegExp("^/{2,}([^/]+)/([^?]+)")).exec(uri.path); if (m) { var host = m[1]; var path = m[2]; switch (host) { case "template": try { var nest = ioService.newURI(path, uri.charset, null); var channel = ioService.newChannelFromURI(nest); // xxx: support template if (0) return channel; // xxx: NG: Firefox 16, 17 // NG: Cu.import if (parseFloat(version) < 17) { var stream = Cc["@mozilla.org/scriptableinputstream;1"] .createInstance(Ci.nsIScriptableInputStream); var cstream = channel.open(); stream.init(cstream); var text = stream.read(-1); stream.close(); cstream.close(); stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream); stream.setData(convert(text), -1); var channel = Cc["@mozilla.org/network/input-stream-channel;1"] .createInstance(Ci.nsIInputStreamChannel); channel.contentStream = stream; channel.QueryInterface(Ci.nsIChannel); channel.setURI(uri); return channel; } var innerURI = uri.innerURI; var temp = cache.clone(); var path = nest.spec.replace(/[:\/]/g, "_"); var lastModifiedTime; if (innerURI.scheme === "resource") { innerURI = Cc["@mozilla.org/network/protocol;1?name=resource"] .getService(Ci.nsIResProtocolHandler).resolveURI(innerURI); innerURI = ioService.newURI(innerURI, null, null); } if (innerURI.scheme === "jar") { innerURI = innerURI.QueryInterface(Ci.nsIJARURI).JARFile; } if (innerURI.scheme === "file") { lastModifiedTime = innerURI.QueryInterface(Ci.nsIFileURL).file.lastModifiedTime; } else { Cu.reportError("do not support:" + innerURI.spec); } temp.append(path); if (!temp.exists() || temp.lastModifiedTime !== lastModifiedTime) { var stream = Cc["@mozilla.org/scriptableinputstream;1"] .createInstance(Ci.nsIScriptableInputStream); var cstream = channel.open(); stream.init(cstream); var text = stream.read(-1); stream.close(); cstream.close(); text = convert(text); var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream); Services.console.logStringMessage("create:" + temp.leafName); stream.init(temp, 0x2 | 0x8 | 0x20, 0644, 0); stream.write(text, text.length); stream.close(); temp.lastModifiedTime = lastModifiedTime; } else { Services.console.logStringMessage("use cache:" + uri.spec); } return ioService.newChannelFromURI(ioService.newFileURI(temp)); } catch (ex) { Cu.reportError(ex); } } } return fakeChannel(uri); } switch(uri.host) { case "help": let url = this.FILE_MAP[uri.path.replace(/^\/|#.*/g, "")]; return makeChannel(url, uri); case "help-overlay": url = this.OVERLAY_MAP[uri.path.replace(/^\/|#.*/g, "")]; return makeChannel(url, uri); case "help-tag": let tag = uri.path.substr(1); if (tag in this.HELP_TAGS) return redirect("liberator://help/" + this.HELP_TAGS[tag] + "#" + tag, uri); } } catch (e) { Cu.reportError(e); } return fakeChannel(uri); } }; var components = [ChromeData, Liberator]; if(XPCOMUtils.generateNSGetFactory) var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); else function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule(components); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. // Script to find regressions // // It should use as few liberator methods as possible, but fall back to standard mozilla/DOM methods // The reason is, we don't want to find regressions in the regressions script, and it should survive // massive changes in the internal liberator API, but just test for functionality of // user-visible commands/mappings // // NOTE: It is preferable to run this script in a clean profile or at least do NOT use // :mkvimperatorrc afterwards, as it can remove commands/mappings, etc. // // Usage: :[count]regr[essions] // When [count] is given, just run this test. TODO: move to :regressions [spec]? // all tests var skipTests = [":bmarks", "gg"]; ///////////////////////////////////////////////////////////////////////////////////////// // Put definitions here which might change due to internal liberator refactoring ///////////////////////////////////////////////////////////////////////////////////////// var doc; // document where we output status messages var multilineOutput = document.getElementById("liberator-multiline-output"); var singlelineOutput = document.getElementById("liberator-message"); ///////////////////////////////////////////////////////////////////////////////////////// // TESTS // // They are run in order, so you can specify commands which expect side effects of a // previous command ///////////////////////////////////////////////////////////////////////////////////////// // A series of Ex commands or mappings, each with a // function checking whether the command succeeded // If the string starts with a ":" it is executed as an Ex command, otherwise as a mapping // You can also mix commands and mappings let tests = [ { cmds: [":!dir"], verify: function () getMultilineOutput().length > 10 }, { cmds: [":abbr VIMP vimperator labs", ":abbr"], verify: function () getOutput().indexOf("vimperator labs") >= 0 }, { cmds: [":unabbr VIMP", ":abbr"], verify: function () getOutput().indexOf("vimperator labs") == -1 }, { cmds: [":bmarks"], verify: function () getMultilineOutput().length > 100 }, { cmds: [":echo \"test\""], verify: function () getSinglelineOutput() == "test" }, { cmds: [":qmark V http://test.vimperator.org", ":qmarks"], verify: function () getMultilineOutput().indexOf("test.vimperator.org") >= 0 }, { cmds: [":javascript liberator.echo('test', commandline.FORCE_MULTILINE)"], verify: function () getMultilineOutput() == "test" }, // { cmds: [":echomsg \"testmsg\""], // verify: function () getOutput() == "testmsg" }, // { cmds: [":echoerr \"testerr\""], // verify: function () getOutput() == "testerr" }, { cmds: ["gg", "<C-f>"], // NOTE: does not work when there is no page to scroll, we should load a large page before doing these tests verify: function () this._initialPos.y != getBufferPosition().y, init: function () this._initialPos = getBufferPosition() } // testing tab behavior ]; // these functions highly depend on the liberator API, so use Ex command tests whenever possible let functions = [ function () { return bookmarks.get("").length > 0 }, // will fail for people without bookmarks :( Might want to add one before function () { return history.get("").length > 0 } ]; ///////////////////////////////////////////////////////////////////////////////////////// // functions below should be as generic as possible, and not require being rewritten // even after doing major Vimperator refactoring ///////////////////////////////////////////////////////////////////////////////////////// function resetEnvironment() { multilineOutput.contentDocument.body.innerHTML = ""; singlelineOutput.value = ""; commandline.close(); modes.reset(); } function getOutput() multilineOutput.contentDocument.body.textContent || singlelineOutput.value; function getMultilineOutput() multilineOutput.contentDocument.body.textContent; function getSinglelineOutput() singlelineOutput.value; function getTabIndex() getBrowser().mTabContainer.selectedIndex; function getTabCount() getBrowser().mTabs.length; function getBufferPosition() { let win = window.content; return { x: win.scrollMaxX ? win.pageXOffset / win.scrollMaxX : 0, y: win.scrollMaxY ? win.pageYOffset / win.scrollMaxY : 0 } }; function getLocation() window.content.document.location.href; function echoLine(str, group) { if (!doc) return; doc.body.appendChild(util.xmlToDom( <div highlight={group} style="border: 1px solid gray; white-space: pre; height: 1.5em; line-height: 1.5em;">{str}</div>, doc)); } function echoMulti(str, group) { if (!doc) return; doc.body.appendChild(util.xmlToDom(<div class="ex-command-output" style="white-space: nowrap; border: 1px solid black; min-height: 1.5em;" highlight={group}>{template.maybeXML(str)}</div>, doc)); } commands.addUserCommand(["regr[essions]"], "Run regression tests", function (args) { // TODO: might need to increase the 'messages' option temporarily // TODO: count (better even range) support to just run test 34 of 102 // TODO: bang support to either: a) run commands like deleting bookmarks which // should only be done in a clean profile or b) run functions and not // just Ex command tests; Yet to be decided let updateOutputHeight = null; function init() { liberator.registerObserver("echoLine", echoLine); liberator.registerObserver("echoMultiline", echoMulti); liberator.open("chrome://liberator/content/buffer.xhtml", liberator.NEW_TAB); events.waitForPageLoad(); doc = content.document; doc.body.setAttributeNS(NS.uri, "highlight", "CmdLine"); updateOutputHeight = commandline.updateOutputHeight; commandline.updateOutputHeight = function (open) { let elem = document.getElementById("liberator-multiline-output"); if (open) elem.collapsed = false; elem.height = 0; }; } function cleanup() { liberator.unregisterObserver("echoLine", echoLine); liberator.unregisterObserver("echoMultiline", echoMulti); commandline.updateOutputHeight = updateOutputHeight; } function run() { let now = Date.now(); let totalTests = tests.length + functions.length; let successfulTests = 0; let skippedTests = 0; let currentTest = 0; init(); // TODO: might want to unify 'tests' and 'functions' handling // 1.) run commands and mappings tests outer: for (let [, test] in Iterator(tests)) { currentTest++; if (args.count >= 1 && currentTest != args.count) continue; let testDescription = util.clip(test.cmds.join(" -> "), 80); for (let [, cmd] in Iterator(test.cmds)) { if (skipTests.indexOf(cmd) != -1) { skippedTests++; liberator.echomsg("Skipping test " + currentTest + " of " + totalTests + ": " + testDescription); continue outer; } }; commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + testDescription, "Filter", commandline.APPEND_TO_MESSAGES); resetEnvironment(); if ("init" in test) test.init(); test.cmds.forEach(function (cmd) { if (cmd[0] == ":") liberator.execute(cmd); else events.feedkeys(cmd); }); if (!test.verify()) liberator.echoerr("Test " + currentTest + " failed: " + testDescription); else successfulTests++; } // 2.) Run function tests for (let [, func] in Iterator(functions)) { currentTest++; if (args.count >= 1 && currentTest != args.count) continue; commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + util.clip(func.toString().replace(/[\s\n]+/gm, " "), 80), "Filter", commandline.APPEND_TO_MESSAGES); resetEnvironment(); if (!func()) liberator.echoerr("Test " + currentTest + " failed!"); else successfulTests++; } cleanup(); let runTests = (args.count >= 1 ? 1 : totalTests) - skippedTests; XML.ignoreWhitespace = false; liberator.echomsg(<e4x> <span style="font-weight: bold">{successfulTests}</span> of <span style="font-weight: bold">{runTests}</span> tests successfully completed (<span style="font-weight: bold">{skippedTests}</span> tests skipped) in <span class="time-total">{((Date.now() - now) / 1000.0)}</span> msec </e4x>.*); liberator.execute(":messages"); } if (!args.bang) { liberator.echo(<e4x> <span style="font-weight: bold">Running tests should always be done in a new profile.</span><br/> It should not do any harm to your profile, but your current settings like options, abbreviations or mappings might not be in the same state as before running the tests. Just make sure, you don't :mkvimperatorrc, after running the tests.<br/><br/> <!--' vim. --> Use :regressions! to skip this prompt. </e4x>.*); commandline.input("Type 'yes' to run the tests: ", function (res) { if (res == "yes") run(); } ); return; } run(); }, { bang: true, argCount: "0", count: true }); // vim: set et sts=4 sw=4 :
JavaScript
// vim: set fdm=marker: var EXPORTED_SYMBOLS = ["raw", "safehtml", "tmpl", "xml", "e4x", "cooked"]; // {{{ escape function //var obj1 = {}; //var obj2 = {}; //var c; // //function $s(s) { // s = s.quote(); // return s.substring(1, s.length -1); //} //for (var i = 0, j = 0x7fff; i < j; i++) { // c = String.fromCharCode(i); // var xml = <>{c}</>.toXMLString(); // if (xml !== c) obj1[$s(c)] = xml; // xml = <a a={c}/>.@a.toXMLString(); // if (xml !== c) obj2[$s(c)] = xml; //} //alert(JSON.stringify([obj1, obj2], null, 1)); function createEscapeFunc(obj) { const c2c = obj; const re = new RegExp("[" + [c for (c in c2c)].join("") + "]", "g"); return function _escapeFunc(s) String(s).replace(re, function (c) c2c[c]); } var escapeHTML = createEscapeFunc({ //"\r": "\n", "&": "&amp;", "<": "&lt;", ">": "&gt;", "\u2028": "\n", "\u2029": "\n" }); var escapeAttribute = createEscapeFunc({ "\t": "&#x9;", "\n": "&#xA;", "\r": "&#xD;", "\"": "&quot;", "&": "&amp;", "<": "&lt;", "\u2028": "&#xA;", "\u2029": "&#xA;" }); function escapeBackQuote(s) { return String.replace(s, /`/g, "\\`"); } function encodeTmplXml(xml) { return "`" + String.replace(s, /`/g, "\\`") + "`"; } function encodeTmplText(text) { return "{" + String.replace(s, /}/g, "\\}") + "}"; } // }}} function TemplateSupportsXML() {} function TemplateXML(s) {this.value = s;} TemplateXML.prototype = new TemplateSupportsXML; TemplateXML.prototype.toString = function () this.value; function TemplateTmpl(s) {this.value = s;} //{{{ TemplateTmpl.prototype = new TemplateSupportsXML; TemplateTmpl.prototype.toString = function () this.value; TemplateTmpl.prototype.toXMLString = function () { var str = this.value; const whiteSpace = /^\s*/y; const tagToken = /^([^`"',\s\[\]\{\}\(\)]+)\s*(\[)?/y; const attrToken = /^\s*([^\s=]+)\s*=\s*(\S)/y; const attrSep = /^\s*(\s|])/y; const STATE = 0, NAME = 1, OPEN = 2; const TAG = {}, ROOT = {}, GROUP = {}; var offset = 0; var start = 0; var res = ""; var stack = []; var depth = 0; var state = [ROOT]; var m; label_root: while (1) { whiteSpace.lastIndex = offset; m = whiteSpace.exec(str); if (!m) throw SyntaxError("ws"); offset = whiteSpace.lastIndex; c = str[offset++]; if (!c) break; switch (c) { case "{": if (state[STATE] === TAG && state[OPEN]) { res += ">"; state[OPEN] = false; } start = offset; while (c = str[offset++]) { if (c === "\\") { res += str.substring(start, offset - 1); start = offset++; } else if (c === "}") { res += escapeHTML(str.substring(start, offset - 1)); continue label_root; } } throw SyntaxError("text"); case "`": if (state[STATE] === TAG && state[OPEN]) { res += ">"; state[OPEN] = false; } start = offset; while (c = str[offset++]) { if (c === "\\") { res += str.substring(start, offset - 1); start = offset++; } else if (c === "`") { res += str.substring(start, offset - 1); continue label_root; } } throw SyntaxError("xml"); case "(": if (state[STATE] === TAG && state[OPEN]) { res += ">"; state[OPEN] = false; } stack[depth++] = state; state = [GROUP]; break; case ")": do { switch (state[STATE]) { case TAG: if (state[OPEN]) { res += "/>"; state[OPEN] = false; } else { res += "</" + state[NAME] + ">"; } break; case GROUP: state = stack[--depth]; continue label_root; case ROOT: throw SyntaxError(")"); } } while (state = stack[--depth]); throw SyntaxError(")"); case ",": do { switch (state[STATE]) { case TAG: if (state[OPEN]) { res += "/>"; state[OPEN] = false; } else { res += "</" + state[NAME] + ">"; } break; case GROUP: case ROOT: continue label_root; } } while (state = stack[--depth]); throw SyntaxError(")"); default: if (state[STATE] === TAG && state[OPEN]) { res += ">"; state[OPEN] = false; } tagToken.lastIndex = offset - 1; m = tagToken.exec(str); if (!m) throw SyntaxError("tag"); offset = tagToken.lastIndex; res += "<" + m[1]; stack[depth++] = state; state = [TAG, m[1], true]; if (m[2]) { label_attr: while (1) { attrToken.lastIndex = offset; m = attrToken.exec(str); if (!m) throw new SyntaxError("attr"); offset = attrToken.lastIndex; res += " " + m[1] + "="; start = offset; close = m[2]; while (c = str[offset++]) { if (c === close) { res += close + str.substring(start, offset - 1) + close; attrSep.lastIndex = offset; m = attrSep.exec(str); if (!m) throw SyntaxError("attr sep"); offset = attrSep.lastIndex; if (m[1] === "]") { break label_attr; } continue label_attr; } } } } break; } } if (state[STATE] === TAG) res += state[OPEN] ? "/>" : "</" + state[NAME] + ">"; while (state = stack[--depth]) { if (state[STATE] === TAG) res += "</" + state[NAME] + ">"; } return res; };//}}} function templateTmpl(portion, args) // {{{ { var res = ""; const BODY = {}, ATTR1 = {}, ATTR2 = {}, TEXT = {}, XML = {}; var c; var raw = portion.raw; var i = 0, j = args.length; var depth = 0; var state = BODY, offset = 0; var str = raw[0], arg = args[0]; var res = str; label_root: while (1) { switch(state) { case BODY: while (c = str[offset++]) { switch (c) { case "[": state = ATTR1; continue label_root; case "`": state = XML; continue label_root; case "{": state = TEXT; continue label_root; case "(": depth++; break; case ")": if (--depth < 0) throw SyntaxError("depth"); break; } } if (i >= j) break label_root; else if (typeof arg === "xml") { res += "`" + arg.toXMLString().replace(/([\\`])/g, "\\$1", "g") + "`"; } else if (arg instanceof TemplateTmpl) { res += "(" + arg.value + ")"; } else if (arg instanceof TemplateXML) { res += "`" + arg.value.replace(/([\\`])/g, "\\$1", "g") + "`"; } else { res += "{" + String.replace(arg, /([\\}])/g, "\\$1") + "}"; } break; case ATTR1: while (c = str[offset++]) { if (c === "=") { state = ATTR2; continue label_root; } else if (c === "]") { state = BODY; continue label_root; } } if (i >= j) throw SyntaxError("attr left"); arg = String(arg); if (/[=\[\]!"#$%&']/.test(arg)) throw SyntaxError("substitude:" + i); res += arg; break; case ATTR2: c1 = str[offset++]; if (!c1) { if (i >= j) throw SyntaxError("attr right"); arg = String(arg); res += '"' + String.replace(arg, /"/g, '\\"', "g") + '"'; state = ATTR1; break; } else if (c1 === "{") c1 = "}"; while (c = str[offset++]) { if (c === "\\") offset++; else if (c === c1) { state = ATTR1; continue label_root; } } // do not support attribute's value nesting throw SyntaxError("attr2"); break; case TEXT: while (c = str[offset++]) { if (c === "\\") offset++; else if (c === "}") { state = BODY; continue label_root; } } if (i >= j) throw SyntaxError("text"); arg = String(arg); res += '{' + String.replace(arg, /}/g, '\\}', "g") + '}'; break; case XML: while (c = str[offset++]) { if (c === "\\") offset++; else if (c === "`") { state = BODY; continue label_root; } } // do not support xml nesting throw SyntaxError("xml"); break; default: throw SyntaxError("unknown state"); } str = raw[++i]; arg = args[i]; res += str; offset = 0; } if (depth !== 0) throw SyntaxError("depth"); return new TemplateTmpl(res); } // xxx: no check templateTmpl.raw = function templateTmplRaw(portion, args) { return new TemplateTmpl(templateRaw(portion, args)); }; templateTmpl.map = function templateTmplMap(data, fn) { var val, res = ""; for (var i = 0, j = data.length; i < j; i++) { val = fn(data[i]); if (val instanceof TemplateTmpl) res += "(" + val.value + ")"; else if (typeof val === "xml") res += encodeTmplXml(val.toXMLString()); else if (val instanceof TemplateXML) res += encodeTmplXml(val.value); else res += encodeTmplText(val); } return new TemplateTmpl(res); }; templateTmpl.is = function is(obj) { return obj instanceof TemplateTmpl; }; templateTmpl.isEmpty = function isEmpty() { return (value instanceof TemplateXML || value instanceof TemplateTmpl) && value.value === ""; }; templateTmpl["+="] = function (self, value) { if (!(self instanceof TemplateTmpl)) throw SyntaxError(); else if (value instanceof TemplateTmpl) self.value += "(" + value.value + ")"; else if (value instanceof TemplateXML) self.value += "`" + value.value.replace(/`/g, "\\`") + "`"; else if (typeof value === "xml") self.value += "`" + value.toXMLString().replace(/`/g, "\\`") + "`"; else self.value = "{" + String(value).replace(/}/g, "\\}") + "}"; return self; }; //}}} function templateXML(portion, args) // {{{ { var res = ""; const BODY = {}, ATTR1 = {}, ATTR2 = {}, TEXT = {}, XML = {}, CC = {}, TAG_OPEN = {} , TAG_CLOSE = {}; var c; var raw = portion.raw; var i = 0, j = args.length; const whiteSpace = /^\s*/y; var state = BODY, offset = 0; var str = raw[0], arg = args[0]; var res = str; var str2, close; var depth = 0; function DepthError() { throw SyntaxError("depth erro: " + [depth, offset, str.substr(offset - 8, 16), res.substr(-32), (new Error).stack]); } label_root: while (1) { switch(state) { case BODY: while (c = str[offset++]) { if (c === "<") { offset--; str2 = str.substr(offset, 16); if (!str2.lastIndexOf("<![CDATA[", 0)) { state = CC; close = "]]>"; offset += 9; continue label_root; } else if (!str2.lastIndexOf("<!--", 0)) { state = CC; close = "-->"; offset += 4; continue label_root; } else if (!str2.lastIndexOf("</", 0)) { if (--depth < 0) DepthError(); state = TAG_CLOSE; offset += 2; continue label_root; } else if (str2[0] === "<") { state = TAG_OPEN; offset++; if (/\s|>/.test(str[offset])) throw SyntaxError("tagname"); continue label_root; } throw SyntaxError("body: " + offset); } } if (i >= j) break label_root; else if (arg instanceof TemplateTmpl || typeof arg === "xml") { res += arg.toXMLString(); } else if (arg instanceof TemplateXML) { res += arg.value; } else if (arg instanceof TemplateSupportsXML) { res += (arg.toXMLString || arg.toString)(); } else { res += escapeHTML(arg); } break; case CC: offset = str.indexOf(close, offset); if (offset === -1) { if (i >= j) throw SyntaxError(close); res += escapeHTML(arg); break; } offset += close.length; state = BODY; continue label_root; case TAG_OPEN: while (c = str[offset++]) { if (!/\s/.test(c)) { state = ATTR1; continue label_root; } } if (i >= j) throw SyntaxError("tag"); arg = String(arg); //if (/\s/.test(arg)) throw SyntaxError("tagname"); res += arg; break; case TAG_CLOSE: while (c = str[offset++]) { if (c === ">") { state = BODY; continue label_root; } //else if (chk) throw SyntaxError("closetag"); } if (i >= j) throw SyntaxError("tag close"); arg = String(arg); //if (/\s/.test(arg)) throw SyntaxError("closetagname"); res += arg; break; case ATTR1: while (c = str[offset++]) { if (c === "=") { state = ATTR2; continue label_root; } else if (c === ">") { depth++; state = BODY; continue label_root; } else if (c === "/") { c = str[offset++]; if (c === ">") { state = BODY; continue label_root; } else throw SyntaxError("/"); } } if (i >= j) throw SyntaxError("attr left"); arg = String(arg); res += arg; break; case ATTR2: whiteSpace.lastIndex = offset; whiteSpace.exec(str); offset = whiteSpace.lastIndex; close = str[offset++]; if (!close) { if (i >= j) throw SyntaxError("attr right"); res += '"' + escapeAttribute(arg) + '"'; state = ATTR1; break; } else if (close === '"' || close === "'") { while (c = str[offset++]) { if (c === close) { state = ATTR1; continue label_root; } } } throw SyntaxError("attr2"); default: throw SyntaxError("unknown state"); } str = raw[++i]; arg = args[i]; res += str; offset = 0; } if (depth !== 0) DepthError(); return new TemplateXML(res); } templateXML.map = function templateXmlMap(data, fn) { var val, res = ""; for (var i = 0, j = data.length; i < j; i++) { val = fn(data[i]); if (val instanceof TemplateTmpl || typeof val === "xml") res += val.toXMLString(); else if (val instanceof TemplateXML) res += val.value; else res += val; } return new TemplateXML(res); } // xxx: xml check templateXML.raw = function templateXmlRaw(portion, args) { var str = templateRaw(portion, args); var ps = new DOMParser var doc = ps.parseFromString("<root>" + str + "</root>", "text/xml"); if (doc.documentElement.tagName === "parsererror") { throw SyntaxError(doc.documentElement.childNodes[0].data); } return new TemplateXML(str); }; templateXML.cdata = function templateXmlCDATA(portion, args) { return new TemplateXML("<![CDATA[" + templateRaw(portion, args).replace(/>/g, "&gt;") + "]]>"); }; templateXML["+="] = function (self, value) { if (!(self instanceof TemplateXML)) throw SyntaxError(); else if (value instanceof TemplateTmpl) self.value += value.toXMLString(); else if (value instanceof TemplateXML) self.value += value.value; else if (typeof value === "xml") self.value += value.toXMLString(); else self.value += escapeHTML(value); return self; }; templateXML.is = function is(obj) { return obj instanceof TemplateXML; }; templateXML.isEmpty = function (value) { return (value instanceof TemplateXML || value instanceof TemplateTmpl) && value.value === ""; }; //}}} function templateRaw(portion, args) { var raw = portion.raw; var i = 0, j = args.length, res = raw[0]; while (i < j) { res += args[i++]; res += raw[i]; } return res; } function templateCooked(portion, args) { var str = portion.cooked; var i = 0, j = args.length, res = str[0]; while (i < j) { res += args[i++]; res += str[i]; } return res; } function templateSafeHtml(portion, args) { var raw = portion.raw; var i = 0, j = args.length, res = raw[0]; while (i < j) { res += escapeHTML(args[i++]); res += raw[i]; } return res; } function templateE4X(portion, args) // e4x {{{ { try { return new XMLList(templateXML(portion, args).value); } catch (ex) { alert(ex.stack); throw ex; } } templateE4X.raw = function raw(portion, args) { return new XMLList(templateRaw(portion, args)); }; templateE4X.cdata = function cdata(portion, args) { return new XMLList("<![CDATA[" + templateRaw(portion, args).replace(/>/g, "&gt;") + "]]>"); }; templateE4X["+"] = function operatorPlus(lhs, rhs) { function toE4X(a) { if (a instanceof TemplateTmpl) return new XMLList(a.toXMLString()); else if (a instanceof TemplateXML) return new XMLList(a.toString()); else return a; } return toE4X(lhs) + toE4X(rhs); }; // xxx: xml object to E4X templateE4X.cast = function cast(obj) { if (obj instanceof TemplateTmpl) return new XMLList(obj.toXMLString()); else if (obj instanceof TemplateXML) return new XMLList(obj.value); else return obj; }; templateE4X["+="] = function (self, value) { if (typeof self !== "xml") throw SyntaxError(); self += templateE4X.cast(value); return self; }; //}}} var tmpl = templateTmpl; var xml = templateXML; var e4x = templateE4X; var raw = templateRaw; var cooked = templateCooked; var safehtml = templateSafeHtml;
JavaScript
/***** BEGIN LICENSE BLOCK ***** {{{ Copyright ©2008-2009 by Kris Maglione <maglione.k at Gmail> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. }}} ***** END LICENSE BLOCK *****/ var EXPORTED_SYMBOLS = ["storage", "Timer"]; const Cc = Components.classes; const Ci = Components.interfaces; const Cu = Components.utils; // XXX: does not belong here function Timer(minInterval, maxInterval, callback) { let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); this.doneAt = 0; this.latest = 0; this.notify = function (aTimer) { timer.cancel(); this.latest = 0; // minInterval is the time between the completion of the command and the next firing this.doneAt = Date.now() + minInterval; try { callback(this.arg); } finally { this.doneAt = Date.now() + minInterval; } }; this.tell = function (arg) { if (arguments.length > 0) this.arg = arg; let now = Date.now(); if (this.doneAt == -1) timer.cancel(); let timeout = minInterval; if (now > this.doneAt && this.doneAt > -1) timeout = 0; else if (this.latest) timeout = Math.min(timeout, this.latest - now); else this.latest = now + maxInterval; timer.initWithCallback(this, Math.max(timeout, 0), timer.TYPE_ONE_SHOT); this.doneAt = -1; }; this.reset = function () { timer.cancel(); this.doneAt = 0; }; this.flush = function () { if (this.doneAt == -1) this.notify(); }; } function getFile(name) { let file = storage.infoPath.clone(); file.append(name); return file; } function readFile(file) { let fileStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream); let stream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream); try { fileStream.init(file, -1, 0, 0); stream.init(fileStream, "UTF-8", 4096, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); // 4096 bytes buffering let hunks = []; let res = {}; while (stream.readString(4096, res) != 0) hunks.push(res.value); stream.close(); fileStream.close(); return hunks.join(""); } catch (e) {} } function writeFile(file, data) { if (!file.exists()) file.create(file.NORMAL_FILE_TYPE, 0600); let fileStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream); let stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream); fileStream.init(file, 0x20 | 0x08 | 0x02, 0600, 0); // PR_TRUNCATE | PR_CREATE | PR_WRITE stream.init(fileStream, "UTF-8", 0, 0); stream.writeString(data); stream.close(); fileStream.close(); } var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.liberator.datastore."); function getCharPref(name) { try { return prefService.getComplexValue(name, Ci.nsISupportsString).data; } catch (e) {} } function setCharPref(name, value) { var str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString); str.data = value; return prefService.setComplexValue(name, Ci.nsISupportsString, str); } function loadPref(name, store, type) { try { if (store) var pref = getCharPref(name); if (!pref && storage.infoPath) var file = readFile(getFile(name)); if (pref || file) var result = JSON.parse(pref || file); if (pref) { prefService.clearUserPref(name); savePref({ name: name, store: true, serial: pref }); } if (result instanceof type) return result; } catch (e) {} } function savePref(obj) { if (obj.privateData && storage.privateMode) return; if (obj.store && storage.infoPath) writeFile(getFile(obj.name), obj.serial); } var prototype = { OPTIONS: ["privateData"], fireEvent: function (event, arg) { storage.fireEvent(this.name, event, arg); }, save: function () { savePref(this); }, init: function (name, store, data, options) { this.__defineGetter__("store", function () store); this.__defineGetter__("name", function () name); for (let [k, v] in Iterator(options)) if (this.OPTIONS.indexOf(k) >= 0) this[k] = v; this.reload(); } }; function ObjectStore(name, store, load, options) { var object = {}; this.reload = function reload() { object = load() || {}; this.fireEvent("change", null); }; this.init.apply(this, arguments); this.__defineGetter__("serial", function () JSON.stringify(object)); this.set = function set(key, val) { var defined = key in object; var orig = object[key]; object[key] = val; if (!defined) this.fireEvent("add", key); else if (orig != val) this.fireEvent("change", key); }; this.remove = function remove(key) { var ret = object[key]; delete object[key]; this.fireEvent("remove", key); return ret; }; this.get = function get(val, default_) val in object ? object[val] : default_; this.clear = function () { object = {}; }; this.__iterator__ = function () Iterator(object); } ObjectStore.prototype = prototype; function ArrayStore(name, store, load, options) { var array = []; this.reload = function reload() { array = load() || []; this.fireEvent("change", null); }; this.init.apply(this, arguments); this.__defineGetter__("serial", function () JSON.stringify(array)); this.__defineGetter__("length", function () array.length); this.set = function set(index, value) { var orig = array[index]; array[index] = value; this.fireEvent("change", index); }; this.push = function push(value) { array.push(value); this.fireEvent("push", array.length); }; this.pop = function pop(value) { var ret = array.pop(); this.fireEvent("pop", array.length); return ret; }; this.truncate = function truncate(length, fromEnd) { var ret = array.length; if (array.length > length) { if (fromEnd) array.splice(0, array.length - length); array.length = length; this.fireEvent("truncate", length); } return ret; }; // XXX: Awkward. this.mutate = function mutate(aFuncName) { var funcName = aFuncName; arguments[0] = array; array = Array[funcName].apply(Array, arguments); this.fireEvent("change", null); }; this.get = function get(index) { return index >= 0 ? array[index] : array[array.length + index]; }; this.__iterator__ = function () Iterator(array); } ArrayStore.prototype = prototype; var keys = {}; var observers = {}; var timers = {}; var storage = { alwaysReload: {}, newObject: function newObject(key, constructor, params) { if (!params.reload && !params.store) { let enumerator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator).getEnumerator("navigator:browser"); params.reload = enumerator.hasMoreElements() && enumerator.getNext() && !enumerator.hasMoreElements(); } if (!(key in keys) || params.reload || this.alwaysReload[key]) { if (key in this && !(params.reload || this.alwaysReload[key])) throw Error(); let load = function () loadPref(key, params.store, params.type || Object); keys[key] = new constructor(key, params.store, load, params); timers[key] = new Timer(1000, 10000, function () storage.save(key)); this.__defineGetter__(key, function () keys[key]); } return keys[key]; }, newMap: function newMap(key, options) { return this.newObject(key, ObjectStore, options); }, newArray: function newArray(key, options) { return this.newObject(key, ArrayStore, options); }, addObserver: function addObserver(key, callback, ref) { if (ref) { if (!ref.liberatorStorageRefs) ref.liberatorStorageRefs = []; ref.liberatorStorageRefs.push(callback); var callbackRef = Cu.getWeakReference(callback); } else { callbackRef = { get: function () callback }; } this.removeDeadObservers(); if (!(key in observers)) observers[key] = []; if (!observers[key].some(function (o) o.callback.get() == callback)) observers[key].push({ ref: ref && Cu.getWeakReference(ref), callback: callbackRef }); }, removeObserver: function (key, callback) { this.removeDeadObservers(); if (!(key in observers)) return; observers[key] = observers[key].filter(function (elem) elem.callback.get() != callback); if (observers[key].length == 0) delete obsevers[key]; }, removeDeadObservers: function () { for (let [key, ary] in Iterator(observers)) { observers[key] = ary = ary.filter(function (o) o.callback.get() && (!o.ref || o.ref.get() && o.ref.get().liberatorStorageRefs)); if (!ary.length) delete observers[key]; } }, get observers() observers, fireEvent: function fireEvent(key, event, arg) { if (!(key in this)) return; this.removeDeadObservers(); // Safe, since we have our own Array object here. if (key in observers) for each (let observer in observers[key]) observer.callback.get()(key, event, arg); timers[key].tell(); }, load: function load(key) { if (this[key].store && this[key].reload) this[key].reload(); }, save: function save(key) { savePref(keys[key]); }, saveAll: function storeAll() { for each (let obj in keys) savePref(obj); }, _privateMode: false, get privateMode() this._privateMode, set privateMode(val) { if (!val && this._privateMode) for (let key in keys) this.load(key); return this._privateMode = Boolean(val); } }; // vim: set fdm=marker sw=4 sts=4 et ft=javascript:
JavaScript
var EXPORTED_SYMBOLS = ["convert"]; const Cu = Components.utils; // // STATE // ALL // 0 TYPE // TEMPLATE // 1 HAS_HANDLER // 2 RESULT // 3 RAW // 4 SUBSTITUDE // ROUND1 // 1 keyword function convert(str, options) { function fnRawEscape(str) { return ({ "\n": "\\n\\\n", "\r\n": "\\n\\\n", "\r": "\\n\\\n", '"': '\\"', "\\": '\\\\', })[str]; } const reRawEscape = /\r\n?|\n|"|\\/g; const reEOL = /\r\n|[\r\n]/g; //const TEMPLATE = {}, TEMPLATE_PORTION = {}, SQUARE = {}, ROUND = {}, CURLY = {}, ROUND1 = {}, ROOT = {}; const TEMPLATE = {s:"t"}, TEMPLATE_PORTION = {s: "tp"}, SQUARE = {s: "s["}, ROUND = {s:"s("}, CURLY = {s:"s{"}, ROUND1 = {s:"fn"}, ROUND1IN = {s: "in("}, ROOT = {s:"r"}; const TYPE = 0, HAS_HANDLER = 1, RESULT = 2, RAW = 3, SUBSTITUDE = 4; var c, c0, c1, m, q_str, i, j; var start = 0, offset = 0; var isOp = false; var whiteSpace = /^\s*/y; var op = "!\"#%&'()=-~^\\`@+;*:{[}]<>,?/"; var idToken = new RegExp("^[^\\" + op.split("").join("\\") + "\\s]+", "y"); var expressionToken = /^\s*\(/y; var reOpt = /^[igmy]*/y; var last = str.length; var stack = []; const BackSlash = '\\'; var RET = '\r'; var NL = '\n'; var BQ = '`'; var $ = '$'; var re; var depth = 0; var state = [ROOT, null]; //xxx: var raw, substitude, args, hasHandler, cooked; res = ""; root_loop: while (offset < last) { // white space whiteSpace.lastIndex = offset; m = whiteSpace.exec(str); if (!m) break; offset = whiteSpace.lastIndex; c = str[offset++]; if (!c) break; //xxx: goto goto_switch: while (1) { switch (c) { case "/": c0 = str[offset]; if (c0 === "/") { reEOL.lastIndex = offset; m = reEOL.exec(str); if (!m) break root_loop; offset = reEOL.lastIndex; continue root_loop; } else if (c0 === "*") { offset = str.indexOf("*/", offset + 1) + 2; if (offset === 1) break root_loop; continue root_loop; // xxx: } else if (isOp) { if (c0 === "=") { offset++; } isOp = false; } else { // RegExp Literal var x = offset; while (c0 = str[offset++]) { if (c0 === "\\") { offset++; //} else if (c0 === NL || c0 === RET) { // break root_loop; } else if (c0 === "/") { reOpt.lastIndex = offset; m = reOpt.exec(str); offset = reOpt.lastIndex; break; } else if (c0 === "[") { while (c1 = str[offset++]) { if (c1 === "\\") offset++; else if (c1 === "]") { break; } } } } isOp = true; } break; case "`": res += str.substring(start, offset - 1); start = offset; stack[depth++] = state; state = [TEMPLATE, isOp, res, [], []]; res = ""; //c = TEMPLATE_PORTION; //continue goto_switch; //break; case TEMPLATE_PORTION: start = offset; q_str = ""; while (c0 = str[offset++]) { if (c0 === "\\") offset++; else if (c0 === "`") { // end quansi literal res = state[RESULT]; hasHandler = state[HAS_HANDLER]; args = state[RAW]; substitude = state[SUBSTITUDE]; args[args.length] = q_str + str.substring(start, offset -1); if (hasHandler) { raw = args; //xxx: cooked is not implement cooked = []; for (i = 0, j = raw.length; i < j; i++) { cooked[i] = raw[i].replace(/(\\*)([\r\n]+|")/g, function (str, bs, c) { var n = bs.length; if (n % 2) { if (c !== '"') str = bs.substr(1); } else { if (c === '"') str = "\\" + str; else { str = bs; } } return str; }); raw[i] = raw[i].replace(reRawEscape, fnRawEscape); } substitude = substitude.length ? "(" + substitude.join("), (") + ")" : ""; res += '({\ raw: ["' + raw.join('", "') + '"],\ cooked: ["' + cooked.join('", "') + '"]' + '}, [' + substitude + '])'; } else { // default handler if (args.length === 1) { res += '"' + args[0].replace(reRawEscape, fnRawEscape) + '"'; } else { res += '("' + args[0].replace(reRawEscape, fnRawEscape) + '"'; for (i = 0, j = substitude.length; i < j; i++) { res += ' + (' + substitude[i] + ') + "' + args[i + 1].replace(reRawEscape, fnRawEscape) + '"'; } res += ")"; } } //end flush state = stack[--depth]; start = offset; isOp = true; continue root_loop; } else if (c0 === $) { c1 = str[offset]; // close TemplateLiteralPortion if (c1 === "{") // c1 === "{" { var args = state[RAW]; args[args.length] = q_str + str.substring(start, offset -1); offset++; start = offset; isOp = false; continue root_loop; } } } break root_loop; case "'": case '"': //string literal for (c0 = str[offset++]; offset < last && c0 !== c; c0 = str[offset++]) { if (c0 === BackSlash) offset++; } isOp = true; break; case ";": isOp = false; break; case ":": if (state[TYPE] === ROUND1) { state = stack[--depth]; } isOp = false; break; case "+": case "-": case "*": case "=": case ",": case "!": case "|": case "&": case ">": case "%": case "~": case "^": case "<": case "?": case ";": isOp = false; break; case "(": var aType = state[TYPE]; if (aType === ROUND1) { state[TYPE] = ROUND1IN; } else { stack[depth++] = state; state = [ROUND, offset]; } isOp = false; break; case ")": switch (state[TYPE]) { case ROUND: state = stack[--depth]; isOp = true; break; case ROUND1IN: state = stack[--depth]; isOp = false; break; default: break root_loop; throw SynstaxError("MissMatch:)"); break; } break; case "{": stack[depth++] = state; state = [CURLY, null, offset]; isOp = false; break; case "}": switch (state[TYPE]) { // Template's Substitution case TEMPLATE: args = state[SUBSTITUDE]; args[args.length] = res + str.substring(start, offset - 1); res = ""; c = TEMPLATE_PORTION; start = offset; continue goto_switch; case CURLY: state = stack[--depth]; isOp = false; break; default: break root_loop; throw SynstaxError("MissMatch:}"); } break; case "[": stack[depth++] = state; state = [SQUARE, null]; isOp = false; break; case "]": if (state[0] === SQUARE) { state = stack[--depth]; isOp = true; //xxx: error } else { break root_loop; } //throw SyntaxError(); break; default: //xxx: e4x attribute if (c === "@" && str[offset - 2] === ".") { if (str[offset++] === "*") { break; } } idToken.lastIndex = offset - 1; m = idToken.exec(str); if(!m) break root_loop; word = m[0]; if (state[TYPE] === ROUND1 && state[1] === "let") { state = stack[--depth]; } else { switch (word) { case "get": case "set": offset = idToken.lastIndex; goto_getset: while (1) { whiteSpace.lastIndex = offset; m = whiteSpace.exec(str); if (!m) break root_loop; offset = whiteSpace.lastIndex; c = str[offset++]; if (c === "/") { c = str[offset++]; if (c === "*") { // skip comment offset = str.indexOf("*/", offset) + 2; if (offset === 1) break root_loop; } else if (c === "/") { // skip line reEOL.lastIndex = offset; m = reEOL.exec(str); if (!m) break root_loop; offset = reEOL.lastIndex; } else { // c is divide continue goto_switch; } } else { if (op.indexOf(c) >= 0) { // get/set is variable name isOp = true; } else { // c is getter/setter name isOp = true; stack[depth++] = state; state = [ROUND1, word, offset]; } continue goto_switch; } } break; case "if": case "while": case "for": case "with": case "catch": case "function": case "let": offset = idToken.lastIndex; if (word === "if" && state[TYPE] === ROUND1IN && state[1] === "catch") { state = [ROUND, offset, state]; } else { stack[depth++] = state; state = [ROUND1, word, offset]; } isOp = false; break; case "delete": case "new": case "return": case "yield": case "in": case "instanceof": case "case": case "typeof": case "var": case "const": case "void": case "else": offset = idToken.lastIndex; isOp = false; break; default: offset = idToken.lastIndex; isOp = true; } } break; } break; } // goto_switch: while (1) } if (depth > 0) { reEOL.lastIndex = 0; let lineNumber = (str.substr(0, offset).match(reEOL)||[]).length + 1; Cu.reportError([lineNumber, str.substr(offset -16, 16).quote(), str.substr(offset, 16).quote()]); Cu.reportError(JSON.stringify(stack.slice(0, depth), null, 1)); // force build source stack[depth] = state; Cu.reportError(JSON.stringify(stack.slice(0, depth + 1), null, 1)); let rest = str.substring(start); while (state = stack[depth--]) { if (state[0] === TEMPLATE) { let [,,tag, raw, args] = state; raw = raw.map(function (r) '"' + r.replace(reRawEscape, fnRawEscape) + '"'); if (raw.length === args.length) { raw.push('`"' + rest.replace(reRawEscape, fnRawEscape) + '"`'); } else { args.push("`" + res + rest + "`"); res = ""; } rest = tag + "(({raw: [" + raw.join(", ") + "]}), [" + args.join(", ") + "])"; break; } } while (state = stack[depth--]) { if (state[0] === TEMPLATE) { let [,,tag, raw, args] = state; raw = raw.map(function (r) '"' + r.replace(reRawEscape, fnRawEscape) + '"'); args.push(rest); rest = tag + "(({raw: [" + raw.join(", ") + "]}), [" + args.join(", ") + "])"; } } return res + rest; } return res + str.substring(start); }
JavaScript
// Copyright (c) 2006-2011 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ // TODO: many methods do not work with Thunderbird correctly yet /** * @instance tabs */ const Tabs = Module("tabs", { requires: ["config"], init: function () { this.updateSelectionHistory([config.tabbrowser.mCurrentTab, null]); // used for the "gb" and "gB" mappings to remember the last :buffer[!] command this._lastBufferSwitchArgs = ""; this._lastBufferSwitchSpecial = true; }, _updateTabCount: function () { statusline.updateField("tabcount", true); }, _onTabSelect: function () { // TODO: is all of that necessary? // I vote no. --Kris modes.reset(); statusline.updateField("tabcount", true); this.updateSelectionHistory(); if (options["focuscontent"]) setTimeout(function () { liberator.focusContent(true); }, 10); // just make sure, that no widget has focus }, /** * @property {Object} The previously accessed tab or null if no tab * other than the current one has been accessed. */ get alternate() { var tab = this._alternates[1] ? this._alternates[1].get() : null; return (tab && tab.parentNode) ? tab : null; }, /** * @property {Iterator(Object)} A genenerator that returns all browsers * in the current window. */ get browsers() { let browsers = config.tabbrowser.browsers; for (let i = 0; i < browsers.length; i++) yield [i, browsers[i]]; }, /** * @property {number} The number of tabs in the current window. */ get count() config.tabbrowser.mTabs.length, /** * @property {Object} The local options store for the current tab. */ get options() { let store = this.localStore; if (!("options" in store)) store.options = {}; return store.options; }, /** * Returns the local state store for the tab at the specified * <b>tabIndex</b>. If <b>tabIndex</b> is not specified then the * current tab is used. * * @param {number} tabIndex * @returns {Object} */ // FIXME: why not a tab arg? Why this and the property? // : To the latter question, because this works for any tab, the // property doesn't. And the property is so oft-used that it's // convenient. To the former question, because I think this is mainly // useful for autocommands, and they get index arguments. --Kris getLocalStore: function (tabIndex) { let tab = this.getTab(tabIndex); if (!tab.liberatorStore) tab.liberatorStore = {}; return tab.liberatorStore; }, /** * @property {Object} The local state store for the currently selected * tab. */ get localStore() this.getLocalStore(), /** * @property {Object[]} The array of closed tabs for the current * session. */ get closedTabs() JSON.parse(services.get("sessionStore").getClosedTabData(window)), /** * Returns the index of <b>tab</b> or the index of the currently * selected tab if <b>tab</b> is not specified. This is a 0-based * index. * * @param {Object} tab A tab from the current tab list. * @returns {number} */ index: function (tab) { if (tab) return Array.indexOf(config.tabbrowser.mTabs, tab); else return config.tabbrowser.mTabContainer.selectedIndex; }, // TODO: implement filter /** * Returns an array of all tabs in the tab list. * * @returns {Object[]} */ // FIXME: why not return the tab element? // : unused? Remove me. get: function () { let buffers = []; for (let [i, browser] in this.browsers) { let title = browser.contentTitle || "(Untitled)"; let uri = browser.currentURI.spec; let number = i + 1; buffers.push([number, title, uri]); } return buffers; }, /** * Returns the index of the tab containing <b>content</b>. * * @param {Object} content Either a content window or a content * document. */ // FIXME: Only called once...necessary? getContentIndex: function (content) { for (let [i, browser] in this.browsers) { if (browser.contentWindow == content || browser.contentDocument == content) return i; } return -1; }, /** * Returns the tab at the specified <b>index</b> or the currently * selected tab if <b>index</b> is not specified. This is a 0-based * index. * * @param {number} index The index of the tab required. * @returns {Object} */ getTab: function (index) { if (index != undefined) return config.tabbrowser.mTabs[index]; else return config.tabbrowser.mCurrentTab; }, /** * Lists all tabs matching <b>filter</b>. * * @param {string} filter A filter matching a substring of the tab's * document title or URL. * @param {boolean} showAll */ list: function (filter, showAll) { completion.listCompleter("buffer", filter, null, completion.buffer[showAll ? "ALL" : "VISIBLE"]); }, /** * Moves a tab to a new position in the tab list. * * @param {Object} tab The tab to move. * @param {string} spec See {@link Tabs.indexFromSpec}. * @param {boolean} wrap Whether an out of bounds <b>spec</b> causes * the destination position to wrap around the start/end of the tab * list. */ move: function (tab, spec, wrap) { let index = Tabs.indexFromSpec(spec, wrap, false); index = tabs.getTab(index)._tPos; config.tabbrowser.moveTabTo(tab, index); }, /** * Removes the specified <b>tab</b> from the tab list. * * @param {Object} tab The tab to remove. * @param {number} count How many tabs to remove. * @param {number} orientation Focus orientation * 1 - Focus the tab to the right of the remove tab. * 0 - Focus the altanate tab of the remove tab. if alternate tab is none, same as 1 * -1 - Focus the tab to the left of the remove tab. * @param {number} quitOnLastTab Whether to quit if the tab being * deleted is the only tab in the tab list: * 1 - quit without saving session * 2 - quit and save session * @param {boolean} force Close even if the tab is an app tab. */ // FIXME: what is quitOnLastTab {1,2} all about then, eh? --djk remove: function (tab, count, orientation, quitOnLastTab, force) { let vTabs = config.tabbrowser.visibleTabs; let removeOrBlankTab = { Firefox: function (tab) { if (vTabs.length > 1) config.tabbrowser.removeTab(tab); else { let url = buffer.URL; if (url != "about:blank" || url != "about:newtab" || window.getWebNavigation().sessionHistory.count > 0) { liberator.open("", liberator.NEW_BACKGROUND_TAB); config.tabbrowser.removeTab(tab); } else liberator.beep(); } }, Thunderbird: function (tab) { if (config.tabbrowser.mTabs.length > 1 && !tab.hasAttribute("first-tab")) config.tabbrowser.closeTab(tab); else liberator.beep(); }, }[config.hostApplication] || function () {}; if (typeof count != "number" || count < 1) count = 1; if (quitOnLastTab >= 1 && config.tabbrowser.mTabs.length <= count) { if (liberator.windows.length > 1) window.close(); else liberator.quit(quitOnLastTab == 2); return; } if (!orientation) orientation = 0; let index = vTabs.indexOf(tab); // should close even if the tab is not visible such as ":tabclose arg" if (index < 0) { // XXX: should consider the count variable ? if (tab.pinned && !force) liberator.echoerr("Cannot close an app tab [" + tab.label + "]. Use :tabclose!"); else removeOrBlankTab(tab); return; } let start, end, selIndex = 0; if (orientation < 0) { start = Math.max(0, index - count + 1); end = index; } else { start = index; end = Math.min(index + count, vTabs.length) - 1; selIndex = end + 1; } if (!force) { for (; start <= end && vTabs[start].pinned; start++) liberator.echoerr("Cannot close an app tab [" + vTabs[start].label + "]. Use :tabclose!"); if (start > end) return; } if ((orientation < 0 && 0 < start - 1) || selIndex >= vTabs.length) selIndex = start - 1; let currentIndex = vTabs.indexOf(tabs.getTab()); if (start <= currentIndex && currentIndex <= end) { let selTab = vTabs[selIndex]; if (orientation == 0 && config.tabbrowser.mTabContainer.contains(this.alternate) && !this.alternate.hidden) // XXX: should be in the visible tabs ? { let lastTabIndex = vTabs.indexOf(this.alternate); if (lastTabIndex < start || end < lastTabIndex) selTab = this.alternate; } config.tabbrowser.mTabContainer.selectedItem = selTab; } for (let i = end; i >= start; i--) { removeOrBlankTab(vTabs[i]); vTabs.splice(i, 1); } }, /** * Removes all tabs from the tab list except the specified <b>tab</b>. * * @param {Object} tab The tab to keep. */ keepOnly: function (tab) { config.tabbrowser.removeAllTabsBut(tab); }, /** * Selects the tab at the position specified by <b>spec</b>. * * @param {string} spec See {@link Tabs.indexFromSpec} * @param {boolean} wrap Whether an out of bounds <b>spec</b> causes * the selection position to wrap around the start/end of the tab * list. * @param {boolean} allTabs */ select: function (spec, wrap, allTabs) { let index = Tabs.indexFromSpec(spec, wrap, allTabs); // FIXME: if (index == -1) liberator.beep(); else config.tabbrowser.mTabContainer.selectedIndex = index; }, /** * Reloads the specified tab. * * @param {Object} tab The tab to reload. * @param {boolean} bypassCache Whether to bypass the cache when * reloading. */ reload: function (tab, bypassCache) { if (bypassCache) { const flags = Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE; config.tabbrowser.getBrowserForTab(tab).reloadWithFlags(flags); } else config.tabbrowser.reloadTab(tab); }, /** * Reloads all tabs. * * @param {boolean} bypassCache Whether to bypass the cache when * reloading. */ reloadAll: function (bypassCache) { if (bypassCache) { for (let i = 0; i < config.tabbrowser.mTabs.length; i++) { try { this.reload(config.tabbrowser.mTabs[i], bypassCache); } catch (e) { // FIXME: can we do anything useful here without stopping the // other tabs from reloading? } } } else config.tabbrowser.reloadAllTabs(); }, /** * Stops loading the specified tab. * * @param {Object} tab The tab to stop loading. */ stop: function (tab) { if (config.stop) config.stop(tab); else tab.linkedBrowser.stop(); }, /** * Stops loading all tabs. */ stopAll: function () { for (let [, browser] in this.browsers) browser.stop(); }, /** * Returns tabs containing the specified <b>buffer</b>. * @param {string} buffer * @return {array} array of tabs */ getTabsFromBuffer: function (buffer) { if (!buffer || typeof buffer != "string") return []; if (buffer == "#") return [tabs.alternate]; let matches = buffer.match(/^(\d+):?/); if (matches) return [tabs.getTab(parseInt(matches[1], 10) - 1)]; else if (liberator.has("tabgroup")) { matches = buffer.match(/^(.+?)\.(\d+):?/); if (matches) { let [, groupName, tabNum] = matches; tabNum = parseInt(tabNum, 10); let group = tabGroup.getGroup(groupName); if (group) { let tabItem = group.getChild(tabNum - 1); if (tabItem) return [tabItem.tab]; } } } matches = []; let lowerBuffer = buffer.toLowerCase(); let first = tabs.index(); let nbrowsers = config.tabbrowser.browsers.length; for (let [i, ] in tabs.browsers) { let index = (i + first) % nbrowsers; let browser = config.tabbrowser.browsers[index]; let tab = tabs.getTab(index); let url = borwser.contentDocument.location.href; let title = tab.label.toLowerCase(); if (url == buffer) return [tab]; if (url.indexOf(buffer) >= 0 || title.indexOf(lowerBuffer) >= 0) matches.push(tab); } return matches; }, /** * Selects the tab containing the specified <b>buffer</b>. * * @param {string} buffer A string which matches the URL or title of a * buffer, if it is null, the last used string is used again. * @param {boolean} allowNonUnique Whether to select the first of * multiple matches. * @param {number} count If there are multiple matches select the * count'th match. * @param {boolean} reverse Whether to search the buffer list in * reverse order. * */ // FIXME: help! switchTo: function (buffer, allowNonUnique, count, reverse) { if (buffer == "") return; if (buffer != null) { // store this command, so it can be repeated with "B" this._lastBufferSwitchArgs = buffer; this._lastBufferSwitchSpecial = allowNonUnique; } else { buffer = this._lastBufferSwitchArgs; if (allowNonUnique === undefined || allowNonUnique == null) // XXX allowNonUnique = this._lastBufferSwitchSpecial; } if (!count || count < 1) count = 1; if (typeof reverse != "boolean") reverse = false; let tabItems = tabs.getTabsFromBuffer(buffer); if (tabItems.length == 0) liberator.echoerr("No matching buffer for: " + buffer); else if (tabItems.length == 1) config.tabbrowser.mTabContainer.selectedItem = tabItems[0]; else if (!allowNonUnique) liberator.echoerr("More than one match for: " + buffer); else { let length = tabItems.length; if (reverse) { index = length - count; while (index < 0) index += length; } else index = count % length; config.tabbrowser.mTabContainer.selectedItem = tabItems[index]; } }, /** * Clones the specified <b>tab</b> and append it to the tab list. * * @param {Object} tab The tab to clone. * @param {boolean} activate Whether to select the newly cloned tab. */ cloneTab: function (tab, activate) { let newTab = config.tabbrowser.addTab(); Tabs.copyTab(newTab, tab); if (activate) config.tabbrowser.mTabContainer.selectedItem = newTab; return newTab; }, /** * Detaches the specified <b>tab</b> and open it in a new window. If no * tab is specified the currently selected tab is detached. * * @param {Object} tab The tab to detach. */ detachTab: function (tab) { if (!tab) tab = config.tabbrowser.mTabContainer.selectedItem; services.get("ww") .openWindow(window, window.getBrowserURL(), null, "chrome,dialog=no,all", tab); }, /** * Selects the alternate tab. */ selectAlternateTab: function () { liberator.assert(tabs.alternate != null && tabs.getTab() != tabs.alternate, "No alternate page"); // NOTE: this currently relies on v.tabs.index() returning the // currently selected tab index when passed null let index = tabs.index(tabs.alternate); // TODO: since a tab close is more like a bdelete for us we // should probably reopen the closed tab when a 'deleted' // alternate is selected liberator.assert(index >= 0, "Alternate buffer does not exist"); // TODO: This should read "Buffer N does not exist" tabs.select(index, false, true); }, // NOTE: when restarting a session FF selects the first tab and then the // tab that was selected when the session was created. As a result the // alternate after a restart is often incorrectly tab 1 when there // shouldn't be one yet. /** * Sets the current and alternate tabs, updating the tab selection * history. * * @param {Array(Object)} tabs The current and alternate tab. * @see tabs#alternate */ updateSelectionHistory: function (tabs) { var tab1, tab2; if (tabs && tabs.length > 1) { tab1 = tabs[0] ? Cu.getWeakReference(tabs[0]) : null, tab2 = tabs[1] ? Cu.getWeakReference(tabs[1]) : null; } else { tab1 = Cu.getWeakReference(this.getTab()), tab2 = this._alternates[0]; } this._alternates = [tab1, tab2]; } }, { copyTab: function (to, from) { if (!from) from = config.tabbrowser.mTabContainer.selectedItem; let tabState = services.get("sessionStore").getTabState(from); services.get("sessionStore").setTabState(to, tabState); }, /** * @param spec can either be: * - an absolute integer * - "" for the current tab * - "+1" for the next tab * - "-3" for the tab, which is 3 positions left of the current * - "$" for the last tab * @param wrap * @param allTabs */ indexFromSpec: function (spec, wrap, allTabs) { let tabs = allTabs ? config.tabbrowser.mTabs : config.tabbrowser.visibleTabs; let position = allTabs ? config.tabbrowser.mTabContainer.selectedIndex : tabs.indexOf(config.tabbrowser.mCurrentTab); let length = tabs.length; let last = length - 1; if (spec === undefined || spec === "") return position; if (typeof spec === "number") position = spec; else if (spec === "$") position = last; else if (/^[+-]\d+$/.test(spec)) position += parseInt(spec, 10); else if (/^\d+$/.test(spec)) position = parseInt(spec, 10); else return -1; if (position > last) position = wrap ? position % length : last; else if (position < 0) position = wrap ? ((position % length) + length) % length : 0; if (config.hostApplication === "Firefox") return tabs[position]._tPos; return position; } }, { commands: function () { commands.add(["bd[elete]", "bw[ipeout]", "bun[load]", "tabc[lose]"], "Delete current buffer", function (args) { let special = args.bang; let count = args.count; let arg = args.literalArg; let orientation = 1; if (args["-select"] === "lastactive") { orientation = 0; } else if (args["-select"] === "left") { orientation = -1; } if (arg) { let removed = 0; let matches = arg.match(/^(\d+):?/); if (matches) { tabs.remove(tabs.getTab(parseInt(matches[1], 10) - 1), 1, orientation, 0, special); removed = 1; } else { let str = arg.toLowerCase(); let browsers = config.tabbrowser.browsers; for (let i = browsers.length - 1; i >= 0; i--) { let host, title, uri = browsers[i].currentURI.spec; if (browsers[i].currentURI.schemeIs("about")) { host = ""; title = "(Untitled)"; } else { host = browsers[i].currentURI.host; title = browsers[i].contentTitle; } [host, title, uri] = [host, title, uri].map(String.toLowerCase); if (host.indexOf(str) >= 0 || uri == str || (special && (title.indexOf(str) >= 0 || uri.indexOf(str) >= 0))) { tabs.remove(tabs.getTab(i), 1, orientation, 0, special); removed++; } } } if (removed == 1) liberator.echomsg("Removed tab: " + arg); else if (removed > 1) liberator.echomsg("Removed " + removed + " tabs"); else liberator.echoerr("No matching tab for: " + arg); } else // just remove the current tab tabs.remove(tabs.getTab(), Math.max(count, 1), orientation, 0, special); }, { argCount: "?", bang: true, count: true, options: [ [["-select", "-s"], commands.OPTION_STRING, null, [["lastactive", "Select last active tab"], ["left", "Select the tab to the left"], ["right", "Select the tab to the right"]]], ], completer: function (context) completion.buffer(context), literal: 0 }); commands.add(["keepa[lt]"], "Execute a command without changing the current alternate buffer", function (args) { let alternate = tabs.alternate; try { liberator.execute(args[0], null, true); } finally { tabs.updateSelectionHistory([tabs.getTab(), alternate]); } }, { argCount: "+", completer: function (context) completion.ex(context), literal: 0 }); commands.add(["tab"], "Execute a command and tell it to output in a new tab", function (args) { try { liberator.forceNewTab = true; liberator.execute(args.string, null, true); } finally { liberator.forceNewTab = false; } }, { argCount: "+", completer: function (context) completion.ex(context), literal: 0 }); commands.add(["tabd[o]", "bufd[o]"], "Execute a command in each tab", function (args) { for (let i = 0; i < tabs.count; i++) { tabs.select(i); liberator.execute(args.string, null, true); } }, { argCount: "1", completer: function (context) completion.ex(context), literal: 0 }); commands.add(["tabl[ast]", "bl[ast]"], "Switch to the last tab", function () tabs.select("$", false), { argCount: "0" }); // TODO: "Zero count" if 0 specified as arg commands.add(["tabp[revious]", "tp[revious]", "tabN[ext]", "tN[ext]", "bp[revious]", "bN[ext]"], "Switch to the previous tab or go [count] tabs back", function (args) { let count = args.count; let arg = args[0]; // count is ignored if an arg is specified, as per Vim if (arg) { if (/^\d+$/.test(arg)) tabs.select("-" + arg, true); else liberator.echoerr("Trailing characters"); } else if (count > 0) tabs.select("-" + count, true); else tabs.select("-1", true); }, { argCount: "?", count: true }); // TODO: "Zero count" if 0 specified as arg commands.add(["tabn[ext]", "tn[ext]", "bn[ext]"], "Switch to the next or [count]th tab", function (args) { let count = args.count; let arg = args[0]; if (arg || count > 0) { let index; // count is ignored if an arg is specified, as per Vim if (arg) { liberator.assert(/^\d+$/.test(arg), "Trailing characters"); index = arg - 1; } else index = count - 1; if (index < tabs.count) tabs.select(index, true); else liberator.beep(); } else tabs.select("+1", true); }, { argCount: "?", count: true }); commands.add(["tabr[ewind]", "tabfir[st]", "br[ewind]", "bf[irst]"], "Switch to the first tab", function () { tabs.select(0, false); }, { argCount: "0" }); if (config.hasTabbrowser) { // TODO: "Zero count" if 0 specified as arg, multiple args and count ranges? commands.add(["b[uffer]"], "Switch to a buffer", function (args) { let special = args.bang; let count = args.count; let arg = args.literalArg; if (arg && count > 0) { liberator.assert(/^\d+$/.test(arg), "Trailing characters"); tabs.switchTo(arg, special); } else if (count > 0) tabs.switchTo(count.toString(), special); else tabs.switchTo(arg, special); }, { argCount: "?", bang: true, count: true, completer: function (context) completion.buffer(context, completion.buffer.ALL), literal: 0 }); commands.add(["buffers", "files", "ls", "tabs"], "Show a list of all buffers", function (args) { tabs.list(args.literalArg, args.bang); }, { argCount: "?", bang: true, literal: 0 }); commands.add(["quita[ll]", "qa[ll]"], "Quit " + config.name, function (args) { liberator.quit(false, args.bang); }, { argCount: "0", bang: true }); commands.add(["reloada[ll]"], "Reload all tab pages", function (args) { tabs.reloadAll(args.bang); }, { argCount: "0", bang: true }); commands.add(["stopa[ll]"], "Stop loading all tab pages", function () { tabs.stopAll(); }, { argCount: "0" }); // TODO: add count support commands.add(["tabm[ove]"], "Move the current tab after tab N", function (args) { let arg = args[0]; // FIXME: tabmove! N should probably produce an error liberator.assert(!arg || /^([+-]?\d+)$/.test(arg), "Trailing characters"); // if not specified, move to after the last tab tabs.move(config.tabbrowser.mCurrentTab, arg || "$", args.bang); }, { argCount: "?", bang: true }); commands.add(["tabo[nly]"], "Close all other tabs", function () { tabs.keepOnly(config.tabbrowser.mCurrentTab); }, { argCount: "0" }); commands.add(["tabopen", "t[open]", "tabnew"], "Open one or more URLs in a new tab", function (args) { let special = args.bang; args = args.string; if (options.get("activate").has("all", "tabopen")) special = !special; let where = special ? liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB; if (args) liberator.open(args, { where: where }); else liberator.open("", { where: where }); }, { bang: true, completer: function (context) completion.url(context), literal: 0, privateData: true }); commands.add(["tabde[tach]"], "Detach current tab to its own window", function () { liberator.assert(tabs.count > 1, "Can't detach the last tab"); tabs.detachTab(null); }, { argCount: "0" }); commands.add(["tabdu[plicate]"], "Duplicate current tab", function (args) { let tab = tabs.getTab(); let activate = args.bang ? true : false; if (options.get("activate").has("tabopen", "all")) activate = !activate; for (let i in util.range(0, Math.max(1, args.count))) tabs.cloneTab(tab, activate); }, { argCount: "0", bang: true, count: true }); // TODO: match window by title too? // : accept the full :tabmove arg spec for the tab index arg? // : better name or merge with :tabmove? commands.add(["taba[ttach]"], "Attach the current tab to another window", function (args) { liberator.assert(args.length <= 2 && !args.some(function (i) !/^\d+$/.test(i)), "Trailing characters"); let [winIndex, tabIndex] = args.map(parseInt); let win = liberator.windows[winIndex - 1]; liberator.assert(win, "Window " + winIndex + " does not exist"); liberator.assert(win != window, "Cannot reattach to the same window"); let browser = win.getBrowser(); let dummy = browser.addTab("about:blank"); browser.stop(); // XXX: the implementation of DnD in tabbrowser.xml suggests // that we may not be guaranteed of having a docshell here // without this reference? browser.docShell; let last = browser.mTabs.length - 1; browser.moveTabTo(dummy, util.Math.constrain(tabIndex || last, 0, last)); browser.selectedTab = dummy; // required browser.swapBrowsersAndCloseOther(dummy, config.tabbrowser.mCurrentTab); }, { argCount: "+", completer: function (context, args) { if (args.completeArg == 0) { context.filters.push(function ({ item: win }) win != window); completion.window(context); } } }); } if (liberator.has("tabs_undo")) { commands.add(["u[ndo]"], "Undo closing of a tab", function (args) { if (args.length) args = args[0]; else args = args.count || 0; let m = /^(\d+)(:|$)/.exec(args || '1'); if (m) window.undoCloseTab(Number(m[1]) - 1); else if (args) { for (let [i, item] in Iterator(tabs.closedTabs)) if (item.state.entries[item.state.index - 1].url == args) { window.undoCloseTab(i); return; } liberator.echoerr("No matching closed tab: " + args); } }, { argCount: "?", completer: function (context) { context.anchored = false; context.compare = CompletionContext.Sort.unsorted; context.filters = [CompletionContext.Filter.textDescription]; context.keys = { text: function ([i, { state: s }]) (i + 1) + ": " + s.entries[s.index - 1].url, description: "[1].title", icon: "[1].image" }; context.completions = Iterator(tabs.closedTabs); }, count: true, literal: 0 }); commands.add(["undoa[ll]"], "Undo closing of all closed tabs", function (args) { for (let i in Iterator(tabs.closedTabs)) window.undoCloseTab(0); }, { argCount: "0" }); } if (liberator.has("session")) { commands.add(["wqa[ll]", "wq", "xa[ll]"], "Save the session and quit", function () { liberator.quit(true); }, { argCount: "0" }); } }, completion: function () { completion.addUrlCompleter("t", "Open tabs", completion.buffer); }, events: function () { let tabContainer = config.tabbrowser.mTabContainer; ["TabMove", "TabOpen", "TabClose"].forEach(function (event) { events.addSessionListener(tabContainer, event, this.closure._updateTabCount, false); }, this); events.addSessionListener(tabContainer, "TabSelect", this.closure._onTabSelect, false); }, mappings: function () { mappings.add([modes.NORMAL], ["g0", "g^"], "Go to the first tab", function (count) { tabs.select(0); }); mappings.add([modes.NORMAL], ["g$"], "Go to the last tab", function (count) { tabs.select("$"); }); mappings.add([modes.NORMAL], ["gt"], "Go to the next tab", function (count) { if (count != null) tabs.select(count - 1, false); else tabs.select("+1", true); }, { count: true }); mappings.add([modes.NORMAL], ["<C-n>", "<C-Tab>", "<C-PageDown>"], "Go to the next tab", function (count) { tabs.select("+" + (count || 1), true); }, { count: true }); mappings.add([modes.NORMAL], ["gT", "<C-p>", "<C-S-Tab>", "<C-PageUp>"], "Go to previous tab", function (count) { tabs.select("-" + (count || 1), true); }, { count: true }); if (config.hasTabbrowser) { mappings.add([modes.NORMAL], ["b"], "Open a prompt to switch buffers", function (count) { if (count != null) tabs.select(count - 1); else commandline.open("", "buffer! ", modes.EX); }, { count: true }); mappings.add([modes.NORMAL], ["B"], "Show buffer list", function () { tabs.list(false); commandline.show("buffers"); }); mappings.add([modes.NORMAL], ["d"], "Delete current tab and select the tab to the right", function (count) { tabs.remove(tabs.getTab(), count, 1, 0); }, { count: true }); mappings.add([modes.NORMAL], ["D"], "Delete current buffer and select the tab to the left", function (count) { tabs.remove(tabs.getTab(), count, -1, 0); }, { count: true }); mappings.add([modes.NORMAL], ["gb"], "Repeat last :buffer[!] command", function (count) { tabs.switchTo(null, null, count, false); }, { count: true }); mappings.add([modes.NORMAL], ["gB"], "Repeat last :buffer[!] command in reverse direction", function (count) { tabs.switchTo(null, null, count, true); }, { count: true }); // TODO: feature dependencies - implies "session"? if (liberator.has("tabs_undo")) { mappings.add([modes.NORMAL], ["u"], "Undo closing of a tab", function (count) { commands.get("undo").execute("", false, count); }, { count: true }); } mappings.add([modes.NORMAL], ["<C-^>", "<C-6>"], "Select the alternate tab or the [count]th tab", function (count) { if (count < 1) tabs.selectAlternateTab(); else tabs.switchTo(count.toString(), false); }, { count: true }); } }, options: function () { if (config.hasTabbrowser) { options.add(["activate", "act"], "Define when tabs are automatically activated", "stringlist", "addons,downloads,extoptions,help,homepage,quickmark,tabopen,paste", { completer: function (context) [ ["all", "All tabs created by any commands and mappings"], ["addons", ":addo[ns] command"], ["downloads", ":downl[oads] command"], ["extoptions", ":exto[ptions] command"], ["help", ":h[elp] command"], ["homepage", "gH mapping"], ["quickmark", "go and gn mappings"], ["tabopen", ":tabopen[!] command"], ["paste", "P and gP mappings"] ] }); options.add(["newtab"], "Define which commands should output in a new tab by default", "stringlist", "", { completer: function (context) [ ["all", "All commands"], ["addons", ":addo[ns] command"], ["downloads", ":downl[oads] command"], ["extoptions", ":exto[ptions] command"], ["help", ":h[elp] command"], ["javascript", ":javascript! or :js! command"], ["prefs", ":pref[erences]! or :prefs! command"] ] }); options.add(["popups", "pps"], "Where to show requested popup windows", "stringlist", "tab", { setter: function (value) { let [open, restriction] = [1, 0]; for (let opt of this.parseValues(value)) { if (opt == "tab") open = 3; else if (opt == "window") open = 2; else if (opt == "resized") restriction = 2; } options.safeSetPref("browser.link.open_newwindow", open, "See 'popups' option."); options.safeSetPref("browser.link.open_newwindow.restriction", restriction, "See 'popups' option."); return value; }, completer: function (context) [ ["tab", "Open popups in a new tab"], ["window", "Open popups in a new window"], ["resized", "Open resized popups in a new window"] ] }); options.add(["tabnumbers", "tn"], "Show small numbers at each tab to allow quicker selection", "boolean", false, { setter: function (value) { // TODO: Change this stuff for muttator if (value) styles.addSheet(true, "tabnumbers", "chrome://*", // we need to change the visible of the "new tab" buttons because the "inline" "new tab" button in the toolbar // gets moved just after the last app tab with tab numbers on "#TabsToolbar { counter-reset:tabnumber; } #TabsToolbar tab::after { counter-increment:tabnumber; content:counter(tabnumber); font:bold 0.84em monospace; cursor: default; } #TabsToolbar tab:not([pinned])::after { display:block; padding-bottom:0.4em; } .tabs-newtab-button { display: none !important; } #new-tab-button { visibility: visible !important; }" ); else styles.removeSheet(true, "tabnumbers"); return value; } }); } } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** * @scope modules * @instance marks */ const Marks = Module("marks", { requires: ["config", "storage"], init: function init() { this._localMarks = storage.newMap("local-marks", { store: true, privateData: true }); this._urlMarks = storage.newMap("url-marks", { store: false, privateData: true }); this._pendingJumps = []; }, /** * @property {Array} Returns all marks, both local and URL, in a sorted * array. */ get all() { // local marks let location = window.content.location.href; let lmarks = [i for (i in this._localMarkIter()) if (i[1].location == location)]; lmarks.sort(); // URL marks // FIXME: why does umarks.sort() cause a "Component is not available = // NS_ERROR_NOT_AVAILABLE" exception when used here? let umarks = [i for (i in this._urlMarks)]; umarks.sort(function (a, b) a[0].localeCompare(b[0])); return lmarks.concat(umarks); }, /** * Add a named mark for the current buffer, at its current position. * If mark matches [A-Z], it's considered a URL mark, and will jump to * the same position at the same URL no matter what buffer it's * selected from. If it matches [a-z'"], it's a local mark, and can * only be recalled from a buffer with a matching URL. * * @param {string} mark The mark name. * @param {boolean} silent Whether to output informative messages. */ // TODO: add support for frameset pages add: function (mark, silent) { let win = window.content; let doc = win.document; if (!doc.body) return; if (doc.body instanceof HTMLFrameSetElement) { if (!silent) liberator.echoerr("Marks support for frameset pages not implemented yet"); return; } let x = win.scrollMaxX ? win.pageXOffset / win.scrollMaxX : 0; let y = win.scrollMaxY ? win.pageYOffset / win.scrollMaxY : 0; let position = { x: x, y: y }; if (Marks.isURLMark(mark)) { this._urlMarks.set(mark, { location: win.location.href, position: position, tab: tabs.getTab() }); if (!silent) liberator.echomsg("Added URL mark: " + Marks.markToString(mark, this._urlMarks.get(mark))); } else if (Marks.isLocalMark(mark)) { // remove any previous mark of the same name for this location this._removeLocalMark(mark); if (!this._localMarks.get(mark)) this._localMarks.set(mark, []); let vals = { location: win.location.href, position: position }; this._localMarks.get(mark).push(vals); if (!silent) liberator.echomsg("Added local mark: " + Marks.markToString(mark, vals)); } }, /** * Remove the specified local marks. The <b>filter</b> is a list of * local marks. Ranges are supported. Eg. "ab c d e-k". * * @param {string} filter A string containing local marks to be removed. */ remove: function (filter) { if (!filter) { // :delmarks! only deletes a-z marks for (let [mark, ] in this._localMarks) this._removeLocalMark(mark); } else { let pattern = RegExp("[" + filter.replace(/\s+/g, "") + "]"); for (let [mark, ] in this._urlMarks) { if (pattern.test(mark)) this._removeURLMark(mark); } for (let [mark, ] in this._localMarks) { if (pattern.test(mark)) this._removeLocalMark(mark); } } }, /** * Jumps to the named mark. See {@link #add} * * @param {string} mark The mark to jump to. */ jumpTo: function (mark) { let ok = false; if (Marks.isURLMark(mark)) { let slice = this._urlMarks.get(mark); if (slice && slice.tab && slice.tab.linkedBrowser) { if (slice.tab.parentNode != config.browser.tabContainer) { this._pendingJumps.push(slice); // NOTE: this obviously won't work on generated pages using // non-unique URLs :( liberator.open(slice.location, liberator.NEW_TAB); return; } let index = tabs.index(slice.tab); if (index != -1) { tabs.select(index, false, true); let win = slice.tab.linkedBrowser.contentWindow; if (win.location.href != slice.location) { this._pendingJumps.push(slice); win.location.href = slice.location; return; } buffer.scrollToPercent(slice.position.x * 100, slice.position.y * 100); ok = true; } } } else if (Marks.isLocalMark(mark)) { let win = window.content; let slice = this._localMarks.get(mark) || []; for (let lmark of slice) { if (win.location.href == lmark.location) { buffer.scrollToPercent(lmark.position.x * 100, lmark.position.y * 100); ok = true; break; } } } if (!ok) liberator.echoerr("Mark not set: " + mark); }, /** * List all marks matching <b>filter</b>. * * @param {string} filter */ list: function (filter) { let marks = this.all; liberator.assert(marks.length > 0, "No marks set"); if (filter.length > 0) { marks = marks.filter(function (mark) filter.indexOf(mark[0]) >= 0); liberator.assert(marks.length > 0, "No matching marks for: " + filter.quote()); } let list = template.tabular( [ { header: "Mark", style: "padding-left: 2ex" }, { header: "Line", style: "text-align: right" }, { header: "Column", style: "text-align: right" }, { header: "File", highlight: "URL" }], ([mark[0], Math.round(mark[1].position.x * 100) + "%", Math.round(mark[1].position.y * 100) + "%", mark[1].location] for (mark of marks))); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); }, _onPageLoad: function _onPageLoad(event) { let win = event.originalTarget.defaultView; for (let [i, mark] in Iterator(this._pendingJumps)) { if (win && win.location.href == mark.location) { buffer.scrollToPercent(mark.position.x * 100, mark.position.y * 100); this._pendingJumps.splice(i, 1); return; } } }, _removeLocalMark: function _removeLocalMark(mark) { let localmark = this._localMarks.get(mark); if (localmark) { let win = window.content; for (let [i, lmark] in Iterator(localmark)) { if (lmark.location == win.location.href) { localmark.splice(i, 1); if (localmark.length == 0) this._localMarks.remove(mark); break; } } } }, _removeURLMark: function _removeURLMark(mark) { let urlmark = this._urlMarks.get(mark); if (urlmark) this._urlMarks.remove(mark); }, _localMarkIter: function _localMarkIter() { return ([m,val] for ([m, value] in marks._localMarks) for (val of value)); } }, { markToString: function markToString(name, mark) { return name + ", " + mark.location + ", (" + Math.round(mark.position.x * 100) + "%, " + Math.round(mark.position.y * 100) + "%)" + (("tab" in mark) ? ", tab: " + tabs.index(mark.tab) : ""); }, isLocalMark: function isLocalMark(mark) /^['`a-z]$/.test(mark), isURLMark: function isURLMark(mark) /^[A-Z0-9]$/.test(mark) }, { events: function () { let appContent = document.getElementById("appcontent"); if (appContent) events.addSessionListener(appContent, "load", this.closure._onPageLoad, true); }, mappings: function () { var myModes = config.browserModes; mappings.add(myModes, ["m"], "Set mark at the cursor position", function (arg) { liberator.assert(/^[a-zA-Z]$/.test(arg)); marks.add(arg); }, { arg: true }); mappings.add(myModes, ["'", "`"], "Jump to the mark in the current buffer", function (arg) { marks.jumpTo(arg); }, { arg: true }); }, commands: function () { commands.add(["delm[arks]"], "Delete the specified marks", function (args) { liberator.assert( args.bang || args.string, "Argument required"); liberator.assert(!args.bang || !args.string, "Invalid argument"); if (args.bang) { marks.remove(); } else { args = args.string; let matches = args.match(/((^|[^a-zA-Z])-|-($|[^a-zA-Z])|[^a-zA-Z -]).*/); // 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. let msg = matches ? "Invalid argument:" + matches[0] : ""; liberator.assert(!matches, msg); // check for illegal ranges - only allow a-z A-Z if (matches = args.match(/[a-zA-Z]-[a-zA-Z]/g)) { for (let match in values(matches)) { liberator.assert(/[a-z]-[a-z]|[A-Z]-[A-Z]/.test(match) && match[0] <= match[2], "Invalid argument: " + args.match(match + ".*")[0]); } } marks.remove(args); } }, { bang: true, completer: function (context) completion.mark(context) }); commands.add(["ma[rk]"], "Mark current location within the web page", function (args) { let mark = args[0]; liberator.assert(mark.length <= 1, "Trailing characters"); liberator.assert(/[a-zA-Z]/.test(mark), "Mark must be a letter or forward/backward quote"); marks.add(mark); }, { argCount: "1" }); commands.add(["marks"], "Show all location marks of current web page", function (args) { args = args.string; // ignore invalid mark characters unless there are no valid mark chars liberator.assert(!args || /[a-zA-Z]/.test(args), "No matching marks for: " + args.quote()); let filter = args.replace(/[^a-zA-Z]/g, ""); marks.list(filter); }); }, completion: function () { completion.mark = function mark(context) { function percent(i) Math.round(i * 100); // FIXME: Line/Column doesn't make sense with % context.title = ["Mark", "Line Column File"]; context.keys.description = function ([, m]) percent(m.position.y) + "% " + percent(m.position.x) + "% " + m.location; context.completions = marks.all; }; } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2009 by Kris Maglione <maglione.k at Gmail> // Copyright (c) 2009-2010 by Doug Kearns <dougkearns@gmail.com> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. // TODO: // - fix Sanitize autocommand // - add warning for TIMESPAN_EVERYTHING? // - respect privacy.clearOnShutdown et al or recommend VimperatorLeave autocommand? // - add support for :set sanitizeitems=all like 'eventignore'? // - integrate with the Clear Private Data dialog? const Sanitizer = Module("sanitizer", { requires: ["liberator"], init: function () { const self = this; liberator.loadScript("chrome://browser/content/sanitize.js", Sanitizer); this.__proto__.__proto__ = new Sanitizer.Sanitizer; // Good enough. Sanitizer.getClearRange = Sanitizer.Sanitizer.getClearRange; // XXX self.prefDomain = "privacy.cpd."; self.prefDomain2 = "extensions.liberator.privacy.cpd."; }, // Largely ripped from from browser/base/content/sanitize.js so we can override // the pref strategy without stepping on the global prefs namespace. sanitize: function () { const prefService = services.get("prefs"); let branch = prefService.getBranch(this.prefDomain); let branch2 = prefService.getBranch(this.prefDomain2); let errors = null; function prefSet(name) { try { return branch.getBoolPref(name); } catch (e) { return branch2.getBoolPref(name); } } for (let itemName in this.items) { let item = this.items[itemName]; if ("clear" in item && item.canClear && prefSet(itemName)) { liberator.echomsg("Sanitizing " + itemName + " items..."); // Some of these clear() may raise exceptions (see bug #265028) // to sanitize as much as possible, we catch and store them, // rather than fail fast. // Callers should check returned errors and give user feedback // about items that could not be sanitized try { item.clear(); } catch (e) { if (!errors) errors = {}; errors[itemName] = e; liberator.echoerr("Error sanitizing " + itemName + ": " + e); } } } return errors; }, get prefNames() util.Array.flatten([this.prefDomain, this.prefDomain2].map(options.allPrefs)) }, { argToPref: function (arg) ["commandLine", "offlineApps", "siteSettings"].filter(function (pref) pref.toLowerCase() == arg)[0] || arg, prefToArg: function (pref) pref.toLowerCase().replace(/.*\./, "") }, { commands: function () { commands.add(["sa[nitize]"], "Clear private data", function (args) { liberator.assert(!options['private'], "Cannot sanitize items in private mode"); let timespan = args["-timespan"] == undefined ? options["sanitizetimespan"] : args["-timespan"]; sanitizer.range = Sanitizer.getClearRange(timespan); if (args.bang) { liberator.assert(args.length == 0, "Trailing characters"); liberator.echomsg("Sanitizing all items in 'sanitizeitems'..."); let errors = sanitizer.sanitize(); if (errors) { for (let item in errors) liberator.echoerr("Error sanitizing " + item + ": " + errors[item]); } } else { liberator.assert(args.length > 0, "Argument required"); let items = [item for (item of args.map(Sanitizer.argToPref))]; for (let item of items) { if (!options.get("sanitizeitems").isValidValue(item)) { liberator.echoerr("Invalid data item: " + item); return; } } liberator.echomsg("Sanitizing " + args + " items..."); for (let item of items) { if (sanitizer.canClearItem(item)) { try { sanitizer.clearItem(item); } catch (e) { liberator.echoerr("Error sanitizing " + item + ": " + e); } } else liberator.echomsg("Cannot sanitize " + item); } } }, { argCount: "*", // FIXME: should be + and 0 bang: true, completer: function (context) { context.title = ["Privacy Item", "Description"]; context.completions = options.get("sanitizeitems").completer(); }, options: [ [["-timespan", "-t"], commands.OPTION_INT, function (arg) /^[0-4]$/.test(arg), function () options.get("sanitizetimespan").completer()] ] }); }, options: function () { const self = this; // add liberator-specific private items [ { name: "commandLine", action: function () { let stores = ["command", "search"]; if (self.range) { stores.forEach(function (store) { storage["history-" + store].mutate("filter", function (item) { let timestamp = item.timestamp * 1000; return timestamp < self.range[0] || timestamp > self.range[1]; }); }); } else stores.forEach(function (store) { storage["history-" + store].truncate(0); }); } }, { name: "macros", action: function () { storage["macros"].clear(); } }, { name: "marks", action: function () { storage["local-marks"].clear(); storage["url-marks"].clear(); } } ].forEach(function (item) { let pref = self.prefDomain2 + item.name; if (options.getPref(pref) == null) options.setPref(pref, false); self.items[item.name] = { canClear: true, clear: item.action }; }); // call Sanitize autocommand for (let [name, item] in Iterator(self.items)) { let arg = Sanitizer.prefToArg(name); if (item.clear) { let func = item.clear; item.clear = function () { autocommands.trigger("Sanitize", { name: arg }); item.range = sanitizer.range; func.call(item); }; } } options.add(["sanitizeitems", "si"], "The default list of private items to sanitize", "stringlist", "cache,commandline,cookies,formdata,history,marks,sessions", { setter: function (values) { for (let pref of sanitizer.prefNames) { options.setPref(pref, false); for (let value of this.parseValues(values)) { if (Sanitizer.prefToArg(pref) == value) { options.setPref(pref, true); break; } } } return values; }, getter: function () sanitizer.prefNames.filter(function (pref) options.getPref(pref)).map(Sanitizer.prefToArg).join(","), completer: function (value) [ ["cache", "Cache"], ["commandline", "Command-line history"], ["cookies", "Cookies"], ["downloads", "Download history"], ["formdata", "Saved form and search history"], ["history", "Browsing history"], ["macros", "Saved macros"], ["marks", "Local and URL marks"], ["offlineapps", "Offline website data"], ["passwords", "Saved passwords"], ["sessions", "Authenticated sessions"], ["sitesettings", "Site preferences"] ] }); options.add(["sanitizetimespan", "sts"], "The default sanitizer time span", "number", 1, { setter: function (value) { options.setPref("privacy.sanitize.timeSpan", value); return value; }, getter: function () options.getPref("privacy.sanitize.timeSpan", this.defaultValue), completer: function (value) [ ["0", "Everything"], ["1", "Last hour"], ["2", "Last two hours"], ["3", "Last four hours"], ["4", "Today"] ] }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * Creates a new completion context. * * @class A class to provide contexts for command completion. * Manages the filtering and formatting of completions, and keeps * track of the positions and quoting of replacement text. Allows for * the creation of sub-contexts with different headers and quoting * rules. * * @param {HTMLInputElement} input The editor for which completion is * intended. May be a {CompletionContext} when forking a context, * or a {string} when creating a new one. * @param {string} name The name of this context. Used when the * context is forked. * @param {number} offset The offset from the parent context. * @author Kris Maglione <maglione.k@gmail.com> * @constructor */ const CompletionContext = Class("CompletionContext", { init: function (input, name, offset) { if (!name) name = ""; let self = this; if (input instanceof this.constructor) { let parent = input; name = parent.name + "/" + name; this.contexts = parent.contexts; if (name in this.contexts) self = this.contexts[name]; else self.contexts[name] = this; /** * @property {CompletionContext} This context's parent. {null} when * this is a top-level context. */ self.parent = parent; ["filters", "keys", "title", "quote"].forEach(function (key) self[key] = parent[key] && util.cloneObject(parent[key])); ["anchored", "compare", "editor", "inputField", "_filter", "filterFunc", "keys", "_process", "top"].forEach(function (key) self[key] = parent[key]); self.__defineGetter__("value", function () this.top.value); self.offset = parent.offset; self.advance(offset); /** * @property {boolean} Specifies that this context is not finished * generating results. * @default false */ self.incomplete = false; self.message = null; /** * @property {boolean} Specifies that this context is waiting for the * user to press <Tab>. Useful when fetching completions could be * dangerous or slow, and the user has enabled autocomplete. */ self.waitingForTab = false; delete self._generate; delete self._ignoreCase; if (self != this) return self; ["_caret", "contextList", "maxItems", "onUpdate", "selectionTypes", "tabPressed", "updateAsync", "value"].forEach(function (key) { self.__defineGetter__(key, function () this.top[key]); self.__defineSetter__(key, function (val) this.top[key] = val); }); } else { if (typeof input == "string") this._value = input; else { this.inputField = input; this.editor = input.editor; } this.compare = function (a, b) String.localeCompare(a.text, b.text); /** * @property {function} This function is called when we close * a completion window with Esc or Ctrl-c. Usually this callback * is only needed for long, asynchronous completions */ this.cancel = null; /** * @property {function} The function used to filter the results. * @default Selects all results which match every predicate in the * {@link #filters} array. */ this.filterFunc = function (items) { let self = this; return this.filters. reduce(function (res, filter) res.filter(function (item) filter.call(self, item)), items); }; /** * @property {Array} An array of predicates on which to filter the * results. */ this.filters = [CompletionContext.Filter.text]; /** * @property {boolean} Specifies whether this context results must * match the filter at the beginning of the string. * @default true */ this.anchored = true; /** * @property {Object} A map of all contexts, keyed on their names. * Names are assigned when a context is forked, with its specified * name appended, after a '/', to its parent's name. May * contain inactive contexts. For active contexts, see * {@link #contextList}. */ this.contexts = { "": this }; /** * @property {Object} A mapping of keys, for {@link #getKey}. Given * { key: value }, getKey(item, key) will return values as such: * if value is a string, it will return item.item[value]. If it's a * function, it will return value(item.item). */ this.keys = { text: 0, description: 1, icon: "icon" }; /** * @property {number} This context's offset from the beginning of * {@link #editor}'s value. */ this.offset = offset || 0; /** * @property {function} A function which is called when any subcontext * changes its completion list. Only called when * {@link #updateAsync} is true. */ this.onUpdate = function () true; /** * @property {CompletionContext} The top-level completion context. */ this.top = this; this.__defineGetter__("incomplete", function () this.contextList.some(function (c) c.parent && c.incomplete)); this.__defineGetter__("waitingForTab", function () this.contextList.some(function (c) c.parent && c.waitingForTab)); this.reset(); } /** * @property {Object} A general-purpose store for functions which need to * cache data between calls. */ this.cache = {}; /** * @private * @property {Object} A cache for return values of {@link #generate}. */ this.itemCache = {}; /** * @property {string} A key detailing when the cached value of * {@link #generate} may be used. Every call to * {@link #generate} stores its result in {@link #itemCache}. * When itemCache[key] exists, its value is returned, and * {@link #generate} is not called again. */ this.key = ""; /** * @property {string} A message to be shown before any results. */ this.message = null; this.name = name || ""; /** @private */ this._completions = []; // FIXME /** * Returns a key, as detailed in {@link #keys}. * @function */ this.getKey = function (item, key) (typeof self.keys[key] == "function") ? self.keys[key].call(this, item.item) : key in self.keys ? item.item[self.keys[key]] : item.item[key]; return this; }, // Temporary /** * @property {Object} * * An object describing the results from all sub-contexts. Results are * adjusted so that all have the same starting offset. * * @deprecated */ get allItems() { try { let self = this; let minStart = Math.min.apply(Math, [context.offset for ([k, context] in Iterator(this.contexts)) if (context.items.length && context.hasItems)]); if (minStart == Infinity) minStart = 0; let items = this.contextList.map(function (context) { if (!context.hasItems) return []; let prefix = self.value.substring(minStart, context.offset); return context.items.map(function (item) ({ text: prefix + item.text, __proto__: item })); }); return { start: minStart, items: util.Array.flatten(items), longestSubstring: this.longestAllSubstring }; } catch (e) { liberator.echoerr(e); return { start: 0, items: [], longestAllSubstring: "" }; } }, // Temporary get allSubstrings() { let contexts = this.contextList.filter(function (c) c.hasItems && c.items.length); let minStart = Math.min.apply(Math, contexts.map(function (c) c.offset)); let lists = contexts.map(function (context) { let prefix = context.value.substring(minStart, context.offset); return context.substrings.map(function (s) prefix + s); }); let substrings = lists.reduce( function (res, list) res.filter(function (str) list.some(function (s) s.substr(0, str.length) == str)), lists.pop()); if (!substrings) // FIXME: How is this undefined? return []; return util.Array.uniq(Array.slice(substrings)); }, // Temporary get longestAllSubstring() { return this.allSubstrings.reduce(function (a, b) a.length > b.length ? a : b, ""); }, get caret() this._caret - this.offset, set caret(val) this._caret = val + this.offset, get compare() this._compare || function () 0, set compare(val) this._compare = val, get completions() this._completions || [], set completions(items) { // Accept a generator if ({}.toString.call(items) != '[object Array]') items = [x for (x in Iterator(items))]; delete this.cache.filtered; delete this.cache.filter; this.cache.rows = []; this.hasItems = items.length > 0; this._completions = items; let self = this; if (this.updateAsync && !this.noUpdate) liberator.callInMainThread(function () { self.onUpdate.call(self); }); }, get createRow() this._createRow || template.completionRow, // XXX set createRow(createRow) this._createRow = createRow, get filterFunc() this._filterFunc || util.identity, set filterFunc(val) this._filterFunc = val, get filter() this._filter != null ? this._filter : this.value.substr(this.offset, this.caret), set filter(val) { delete this._ignoreCase; return this._filter = val; }, get format() ({ anchored: this.anchored, title: this.title, keys: this.keys, process: this.process }), set format(format) { this.anchored = format.anchored, this.title = format.title || this.title; this.keys = format.keys || this.keys; this.process = format.process || this.process; }, get message() this._message || (this.waitingForTab ? "Waiting for <Tab>" : null), set message(val) this._message = val, get proto() { let res = {}; for (let i in Iterator(this.keys)) { let [k, v] = i; let _k = "_" + k; if (typeof v == "string" && /^[.[]/.test(v)) v = eval("(function (i) i" + v + ")"); if (typeof v == "function") res.__defineGetter__(k, function () _k in this ? this[_k] : (this[_k] = v(this.item))); else res.__defineGetter__(k, function () _k in this ? this[_k] : (this[_k] = this.item[v])); res.__defineSetter__(k, function (val) this[_k] = val); } return res; }, get regenerate() this._generate && (!this.completions || !this.itemCache[this.key] || this.cache.offset != this.offset), set regenerate(val) { if (val) delete this.itemCache[this.key]; }, get generate() !this._generate ? null : function () { if (this.offset != this.cache.offset) this.itemCache = {}; this.cache.offset = this.offset; if (!this.itemCache[this.key]) this.itemCache[this.key] = this._generate.call(this) || []; return this.itemCache[this.key]; }, set generate(arg) { this.hasItems = true; this._generate = arg; if (this.background && this.regenerate) { let lock = {}; this.cache.backgroundLock = lock; this.incomplete = true; let thread = this.getCache("backgroundThread", liberator.newThread); liberator.callAsync(thread, this, function () { if (this.cache.backgroundLock != lock) return; let items = this.generate(); if (this.cache.backgroundLock != lock) return; this.incomplete = false; this.completions = items; }); } }, // TODO: Is this actually broken anyway? get ignoreCase() { if ("_ignoreCase" in this) return this._ignoreCase; // smart case by default unless overriden above return this._ignoreCase = !/[A-Z]/.test(this.filter); }, set ignoreCase(val) this._ignoreCase = val, get items() { if (!this.hasItems || this.backgroundLock) return []; if (this.cache.filtered && this.cache.filter == this.filter) return this.cache.filtered; this.cache.rows = []; let items = this.completions; if (this.generate && !this.background) { // XXX this.noUpdate = true; this.completions = items = this.generate(); this.noUpdate = false; } this.cache.filter = this.filter; if (items == null) return items; let self = this; delete this._substrings; let proto = this.proto; let filtered = this.filterFunc(items.map(function (item) ({ __proto__: proto, item: item }))); if (this.maxItems) filtered = filtered.slice(0, this.maxItems); if (this.compare) filtered.sort(this.compare); let quote = this.quote; if (quote) filtered.forEach(function (item) { item.unquoted = item.text; item.text = quote[0] + quote[1](item.text) + quote[2]; }); return this.cache.filtered = filtered; }, get process() { // FIXME let self = this; let process = this._process; process = [process[0] || template.icon, process[1] || function (item, k) k]; let first = process[0]; let second = process[1]; let filter = this.filter; if (!this.anchored){ process[0] = function (item, text) first.call(self, item, template.highlightFilter(item.text, filter)); process[1] = function (item, text) second.call(self, item, item.description, filter); } return process; }, set process(process) { this._process = process; }, get substrings() { let items = this.items; if (items.length == 0 || !this.hasItems) return []; if (this._substrings) return this._substrings; let fixCase = this.ignoreCase ? String.toLowerCase : util.identity; let text = fixCase(items[0].unquoted || items[0].text); let filter = fixCase(this.filter); if (this.anchored) { var compare = function compare(text, s) text.substr(0, s.length) == s; var substrings = util.map(util.range(filter.length, text.length + 1), function (end) text.substring(0, end)); } else { var compare = function compare(text, s) text.indexOf(s) >= 0; substrings = []; let start = 0; let idx; let length = filter.length; while ((idx = text.indexOf(filter, start)) > -1 && idx < text.length) { for (let end in util.range(idx + length, text.length + 1)) substrings.push(text.substring(idx, end)); start = idx + 1; } } substrings = items.reduce( function (res, item) res.filter(function (str) compare(fixCase(item.unquoted || item.text), str)), substrings); let quote = this.quote; if (quote) substrings = substrings.map(function (str) quote[0] + quote[1](str)); return this._substrings = substrings; }, /** * Advances the context <b>count</b> characters. {@link #filter} is * advanced to match. If {@link #quote} is non-null, its prefix and suffix * are set to the null-string. * * This function is still imperfect for quoted strings. When * {@link #quote} is non-null, it adjusts the count based on the quoted * size of the <b>count</b>-character substring of the filter, which is * accurate so long as unquoting and quoting a string will always map to * the original quoted string, which is often not the case. * * @param {number} count The number of characters to advance the context. */ advance: function advance(count) { delete this._ignoreCase; if (this.quote) { count = this.quote[0].length + this.quote[1](this.filter.substr(0, count)).length; this.quote[0] = ""; this.quote[2] = ""; } this.offset += count; if (this._filter) this._filter = this._filter.substr(count); }, cancelAll: function () { for (let context of this.contextList) { if (context.cancel) context.cancel(); } }, /** * Gets a key from {@link #cache}, setting it to <b>defVal</b> if it * doesn't already exists. * * @param {string} key * @param defVal */ getCache: function (key, defVal) { if (!(key in this.cache)) this.cache[key] = defVal(); return this.cache[key]; }, getItems: function getItems(start, end) { let self = this; let items = this.items; let step = start > end ? -1 : 1; start = Math.max(0, start || 0); end = Math.min(items.length, end ? end : items.length); return util.map(util.range(start, end, step), function (i) items[i]); }, getRows: function getRows(start, end, doc) { let self = this; let items = this.items; let cache = this.cache.rows; let step = start > end ? -1 : 1; start = Math.max(0, start || 0); end = Math.min(items.length, end != null ? end : items.length); for (let i in util.range(start, end, step)) yield [i, cache[i] = cache[i] || util.xmlToDom(self.createRow(items[i]), doc)]; }, fork: function fork(name, offset, self, completer) { if (typeof completer == "string") completer = self[completer]; let context = CompletionContext(this, name, offset); this.contextList.push(context); if (completer) return completer.apply(self || this, [context].concat(Array.slice(arguments, arguments.callee.length))); return context; }, getText: function getText(item) { let text = item[self.keys["text"]]; if (self.quote) return self.quote(text); return text; }, highlight: function highlight(start, length, type) { try { // Gecko < 1.9.1 doesn't have repaintSelection this.selectionTypes[type] = null; const selType = Ci.nsISelectionController["SELECTION_" + type]; const editor = this.editor; let sel = editor.selectionController.getSelection(selType); if (length == 0) sel.removeAllRanges(); else { let range = editor.selection.getRangeAt(0).cloneRange(); range.setStart(range.startContainer, this.offset + start); range.setEnd(range.startContainer, this.offset + start + length); sel.addRange(range); } editor.selectionController.repaintSelection(selType); } catch (e) {} }, // FIXME _match: function _match(filter, str) { if (!filter) return true; let ignoreCase = this.ignoreCase; let filterArr = filter.split(" "); let self = this; let res = filterArr.filter(function(word) { if (!word) return false; if (ignoreCase) { word = word.toLowerCase(); str = str.toLowerCase(); } if (self.anchored) return str.substr(0, word.length) == word; // TODO: Why not just use indexOf() == 0 ? else return str.indexOf(word) > -1; }); return res.length == filterArr.length; }, match: function match(str) { return this._match(this.filter, str); }, reset: function reset() { let self = this; if (this.parent) throw Error(); // Not ideal. for (let type in this.selectionTypes) this.highlight(0, 0, type); /** * @property {[CompletionContext]} A list of active * completion contexts, in the order in which they were * instantiated. */ this.contextList = []; this.offset = 0; this.process = []; this.selectionTypes = {}; this.tabPressed = false; this.title = ["Completions"]; this.updateAsync = false; this.cancelAll(); if (this.editor) { this.value = this.editor.selection.focusNode.textContent; this._caret = this.inputField.selectionEnd; } else { this.value = this._value; this._caret = this.value.length; } //for (let key in (k for ([k, v] in Iterator(self.contexts)) if (v.offset > this.caret))) // delete this.contexts[key]; for (let [, context] in Iterator(this.contexts)) { context.hasItems = false; if (context != context.top) context.incomplete = false; } }, /** * Wait for all subcontexts to complete. * * @param {boolean} interruptible When true, the call may be interrupted * via <C-c>, in which case, "Interrupted" may be thrown. * @param {number} timeout The maximum time, in milliseconds, to wait. * If 0 or null, wait indefinately. */ wait: function wait(interruptable, timeout) { let end = Date.now() + timeout; while (this.incomplete && (!timeout || Date.now() > end)) liberator.threadYield(false, interruptable); return this.incomplete; } }, { Sort: { number: function (a, b) parseInt(b) - parseInt(a) || String.localeCompare(a, b), unsorted: null }, Filter: { text: function (item) { let text = Array.concat(item.text); for (let [i, str] in Iterator(text)) { if (this.match(String(str))) { item.text = String(text[i]); return true; } } return false; }, textDescription: function (item) { return CompletionContext.Filter.text.call(this, item) || this.match(item.description); }, textAndDescription: function (item) { return this.match(item.text + item.description); } } }); /** * @instance completion */ const Completion = Module("completion", { init: function () { }, get setFunctionCompleter() JavaScript.setCompleter, // Backward compatibility // FIXME _runCompleter: function _runCompleter(name, filter, maxItems, tags, keyword, contextFilter) { let context = CompletionContext(filter || ""); context.maxItems = maxItems; if (contextFilter) context.filters = [contextFilter]; let res = context.fork.apply(context, ["run", 0, this, name].concat(Array.slice(arguments, 3))); if (res) // FIXME return { items: res.map(function (i) ({ item: i })) }; context.wait(true); return context.allItems; }, runCompleter: function runCompleter(name, filter, maxItems, tags, keyword, contextFilter) { return this._runCompleter.apply(this, Array.slice(arguments)) .items.map(function (i) i.item); }, listCompleter: function listCompleter(name, filter, maxItems, tags, keyword, contextFilter) { let context = CompletionContext(filter || ""); context.maxItems = maxItems; if (contextFilter) context.filters = [contextFilter]; context.fork.apply(context, ["list", 0, completion, name].concat(Array.slice(arguments, 3))); context.wait(); for (let [key, context] in Iterator(context.contexts)) { if (key.startsWith("/list")) { let list = template.genericOutput("", xml`<div highlight="Completions"> ${ template.completionRow(context.title, "CompTitle") } ${ template.map2(xml, context.items, function (item) context.createRow(item), null, 100) } </div>`); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } } }, //////////////////////////////////////////////////////////////////////////////// ////////////////////// COMPLETION TYPES //////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////{{{ // filter a list of urls // // may consist of search engines, filenames, bookmarks and history, // depending on the 'complete' option // if the 'complete' argument is passed like "h", it temporarily overrides the complete option url: function url(context, complete) { let numLocationCompletions = 0; // how many async completions did we already return to the caller? let start = 0; let skip = 0; if (options["urlseparator"]) skip = context.filter.match("^.*" + options["urlseparator"]); // start after the last 'urlseparator' if (skip) context.advance(skip[0].length); if (typeof complete === "undefined") complete = options["complete"]; // Will, and should, throw an error if !(c in opts) Array.forEach(complete, function (c) { let completer = completion.urlCompleters[c]; context.fork.apply(context, [c, 0, completion, completer.completer].concat(completer.args)); }); }, urlCompleters: {}, addUrlCompleter: function addUrlCompleter(opt) { let completer = Completion.UrlCompleter.apply(null, Array.slice(arguments)); completer.args = Array.slice(arguments, completer.length); this.urlCompleters[opt] = completer; }, urls: function (context, tags) { let compare = String.localeCompare; let contains = String.indexOf; if (context.ignoreCase) { compare = util.compareIgnoreCase; contains = function (a, b) a && a.toLowerCase().indexOf(b.toLowerCase()) > -1; } if (tags) context.filters.push(function (item) tags. every(function (tag) (item.tags || []). some(function (t) !compare(tag, t)))); context.anchored = false; if (!context.title) context.title = ["URL", "Title"]; } //}}} }, { UrlCompleter: Struct("name", "description", "completer") }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
try { __liberator_eval_result = eval(__liberator_eval_string); } catch (e) { __liberator_eval_error = e; } // IMPORTANT: The eval statement *must* remain on the first line // in order for line numbering in any errors to remain correct. // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ //xxx: this.$$Namespace = function (prefix, uri) { return "XMLList" in window ? Namespace(prefix, uri) : { prefix: prefix, uri: uri, toString: function () { return this.uri; }, }; } const XHTML = $$Namespace("html", "http://www.w3.org/1999/xhtml"); const XUL = $$Namespace("xul", "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); const NS = $$Namespace("liberator", "http://vimperator.org/namespaces/liberator"); if ("XMLList" in window) eval("default xml namespace = XHTML"); delete this.$$Namespace; const Util = Module("util", { init: function () { this.Array = Util.Array; }, /** * Returns a shallow copy of <b>obj</b>. * * @param {Object} obj * @returns {Object} */ cloneObject: function cloneObject(obj) { if (obj instanceof Array) return obj.slice(); let newObj = {}; for (let [k, v] in Iterator(obj)) newObj[k] = v; return newObj; }, /** * Clips a string to a given length. If the input string is longer * than <b>length</b>, an ellipsis is appended. * * @param {string} str The string to truncate. * @param {number} length The length of the returned string. * @returns {string} */ clip: function clip(str, length) { return str.length <= length ? str : str.substr(0, length - 3) + "..."; }, /** * Compares two strings, case insensitively. Return values are as * in String#localeCompare. * * @param {string} a * @param {string} b * @returns {number} */ compareIgnoreCase: function compareIgnoreCase(a, b) String.localeCompare(a.toLowerCase(), b.toLowerCase()), /** * Returns an object representing a Node's computed CSS style. * * @param {Node} node * @returns {Object} */ computedStyle: function computedStyle(node) { while ((node instanceof Text || node instanceof Comment) && node.parentNode) node = node.parentNode; return node.ownerDocument.defaultView.getComputedStyle(node, null); }, /** * Copies a string to the system clipboard. If <b>verbose</b> is specified * the copied string is also echoed to the command line. * * @param {string} str * @param {boolean} verbose */ copyToClipboard: function copyToClipboard(str, verbose) { const clipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper); clipboardHelper.copyString(str); if (verbose) liberator.echomsg("Copied text to clipboard: " + str); }, /** * Converts any arbitrary string into an URI object. * * @param {string} str * @returns {Object} */ // FIXME: newURI needed too? createURI: function createURI(str) { const fixup = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup); return fixup.createFixupURI(str, fixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP); }, /** * Converts HTML special characters in <b>str</b> to the equivalent HTML * entities. * * @param {string} str * @returns {string} */ escapeHTML: function escapeHTML(str) { // XXX: the following code is _much_ slower than a simple .replace() // :history display went down from 2 to 1 second after changing // // var e = window.content.document.createElement("div"); // e.appendChild(window.content.document.createTextNode(str)); // return e.innerHTML; return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }, /** * Escapes Regular Expression special characters in <b>str</b>. * * @param {string} str * @returns {string} */ escapeRegex: function escapeRegex(str) { return str.replace(/([\\{}()[\].?*+])/g, "\\$1"); }, /** * Escapes quotes, newline and tab characters in <b>str</b>. The returned * string is delimited by <b>delimiter</b> or " if <b>delimiter</b> is not * specified. {@see String#quote}. * * @param {string} str * @param {string} delimiter * @returns {string} */ escapeString: function escapeString(str, delimiter) { if (delimiter == undefined) delimiter = '"'; return delimiter + str.replace(/([\\'"])/g, "\\$1").replace("\n", "\\n", "g").replace("\t", "\\t", "g") + delimiter; }, /** * Returns an XPath union expression constructed from the specified node * tests. An expression is built with node tests for both the null and * XHTML namespaces. See {@link Buffer#evaluateXPath}. * * @param nodes {Array(string)} * @returns {string} */ makeXPath: function makeXPath(nodes) { return util.Array(nodes).map(function (node) [node, "xhtml:" + node]).flatten() .map(function (node) "//" + node).join(" | "); }, /** * Memoize the lookup of a property in an object. * * @param {object} obj The object to alter. * @param {string} key The name of the property to memoize. * @param {function} getter A function of zero to two arguments which * will return the property's value. <b>obj</b> is * passed as the first argument, <b>key</b> as the * second. */ memoize: function memoize(obj, key, getter) { obj.__defineGetter__(key, function () { delete obj[key]; obj[key] = getter(obj, key); return obj[key]; }); }, /** * Split a string on literal occurrences of a marker. * * Specifically this ignores occurrences preceded by a backslash, or * contained within 'single' or "double" quotes. * * It assumes backslash escaping on strings, and will thus not count quotes * that are preceded by a backslash or within other quotes as starting or * ending quoted sections of the string. * * @param {string} str * @param {RegExp} marker */ splitLiteral: function splitLiteral(str, marker) { let results = []; let resep = RegExp(/^(([^\\'"]|\\.|'([^\\']|\\.)*'|"([^\\"]|\\.)*")*?)/.source + marker.source); let cont = true; while (cont) { cont = false; str = str.replace(resep, function (match, before) { cont = false; if (before) { results.push(before); cont = true; } return ""; }); } results.push(str); return results; }, /** * Converts <b>bytes</b> to a pretty printed data size string. * * @param {number} bytes The number of bytes. * @param {string} decimalPlaces The number of decimal places to use if * <b>humanReadable</b> is true. * @param {boolean} humanReadable Use byte multiples. * @returns {string} */ formatBytes: function formatBytes(bytes, decimalPlaces, humanReadable) { const unitVal = ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; let unitIndex = 0; let tmpNum = parseInt(bytes, 10) || 0; let strNum = [tmpNum + ""]; if (humanReadable) { while (tmpNum >= 1024) { tmpNum /= 1024; if (++unitIndex > (unitVal.length - 1)) break; } let decPower = Math.pow(10, decimalPlaces); strNum = ((Math.round(tmpNum * decPower) / decPower) + "").split(".", 2); if (!strNum[1]) strNum[1] = ""; while (strNum[1].length < decimalPlaces) // pad with "0" to the desired decimalPlaces) strNum[1] += "0"; } for (let u = strNum[0].length - 3; u > 0; u -= 3) // make a 10000 a 10,000 strNum[0] = strNum[0].substr(0, u) + "," + strNum[0].substr(u); if (unitIndex) // decimalPlaces only when > Bytes strNum[0] += "." + strNum[1]; return strNum[0] + " " + unitVal[unitIndex]; }, exportHelp: function (path) { const FILE = io.File(path); const PATH = FILE.leafName.replace(/\..*/, "") + "/"; const TIME = Date.now(); let zip = services.create("zipWriter"); zip.open(FILE, io.MODE_CREATE | io.MODE_WRONLY | io.MODE_TRUNCATE); function addURIEntry(file, uri) zip.addEntryChannel(PATH + file, TIME, 9, services.get("io").newChannel(uri, null, null), false); function addDataEntry(file, data) // Inideal to an extreme. addURIEntry(file, "data:text/plain;charset=UTF-8," + encodeURI(data)); let empty = util.Array.toObject( "area base basefont br col frame hr img input isindex link meta param" .split(" ").map(Array.concat)); let chrome = {}; for (let [file,] in Iterator(services.get("liberator:").FILE_MAP)) { liberator.open("liberator://help/" + file); events.waitForPageLoad(); let data = [ '<?xml version="1.0" encoding="UTF-8"?>\n', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n', ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n' ]; function fix(node) { switch(node.nodeType) { case Node.ELEMENT_NODE: if (node instanceof HTMLScriptElement) return; data.push("<"); data.push(node.localName); if (node instanceof HTMLHtmlElement) data.push(" xmlns=" + XHTML.uri.quote()); for (let { name: name, value: value } in util.Array.itervalues(node.attributes)) { if (name == "liberator:highlight") { name = "class"; value = "hl-" + value; } if (name == "href") { if (value.indexOf("liberator://help-tag/") == 0) value = services.get("io").newChannel(value, null, null).originalURI.path.substr(1); if (!/[#\/]/.test(value)) value += ".xhtml"; } if (name == "src" && value.indexOf(":") > 0) { chrome[value] = value.replace(/.*\//, "");; value = value.replace(/.*\//, ""); } data.push(" "); data.push(name); data.push('="'); data.push(xml`${value}`.toString()); data.push('"') } if (node.localName in empty) data.push(" />"); else { data.push(">"); if (node instanceof HTMLHeadElement) data.push(`<link rel="stylesheet" type="text/css" href="help.css"/>`/*toXMLString()*/); Array.map(node.childNodes, arguments.callee); data.push("</"); data.push(node.localName); data.push(">"); } break; case Node.TEXT_NODE: data.push(xml`${node.textContent}`.toString()); } } fix(content.document.documentElement); addDataEntry(file + ".xhtml", data.join("")); } let data = [h.selector.replace(/^\[.*?=(.*?)\]/, ".hl-$1").replace(/html\|/, "") + "\t{" + h.value + "}" for (h in highlight) if (/^Help|^Logo/.test(h.class))]; data = data.join("\n"); addDataEntry("help.css", data.replace(/chrome:[^ ")]+\//g, "")); let re = /(chrome:[^ ");]+\/)([^ ");]+)/g; while ((m = re.exec(data))) chrome[m[0]] = m[2]; for (let [uri, leaf] in Iterator(chrome)) addURIEntry(leaf, uri); zip.close(); }, /** * Sends a synchronous or asynchronous HTTP request to <b>url</b> and * returns the XMLHttpRequest object. If <b>callback</b> is specified the * request is asynchronous and the <b>callback</b> is invoked with the * object as its argument. * * @param {string} url * @param {function(XMLHttpRequest)} callback * @returns {XMLHttpRequest} */ httpGet: function httpGet(url, callback) { try { let xmlhttp = new XMLHttpRequest(); xmlhttp.mozBackgroundRequest = true; if (callback) { xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) callback(xmlhttp); }; } xmlhttp.open("GET", url, !!callback); xmlhttp.send(null); return xmlhttp; } catch (e) { // liberator.log("Error opening " + url + ": " + e); return null; } }, /** * Evaluates an XPath expression in the current or provided * document. It provides the xhtml, xhtml2 and liberator XML * namespaces. The result may be used as an iterator. * * @param {string} expression The XPath expression to evaluate. * @param {Document} doc The document to evaluate the expression in. * @default The current document. * @param {Node} elem The context element. * @default <b>doc</b> * @param {boolean} asIterator Whether to return the results as an * XPath iterator. */ evaluateXPath: function (expression, doc, elem, asIterator) { if (!doc) doc = window.content.document; if (!elem) elem = doc; if (isarray(expression)) expression = util.makeXPath(expression); let result = doc.evaluate(expression, elem, function lookupNamespaceURI(prefix) { return { xhtml: "http://www.w3.org/1999/xhtml", xhtml2: "http://www.w3.org/2002/06/xhtml2", liberator: NS.uri }[prefix] || null; }, asIterator ? XPathResult.ORDERED_NODE_ITERATOR_TYPE : XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); result.__iterator__ = asIterator ? function () { let elem; while ((elem = this.iterateNext())) yield elem; } : function () { for (let i = 0; i < this.snapshotLength; i++) yield this.snapshotItem(i); }; return result; }, /** * The identity function. * * @param {Object} k * @returns {Object} */ identity: function identity(k) k, /** * Returns the intersection of two rectangles. * * @param {Object} r1 * @param {Object} r2 * @returns {Object} */ intersection: function (r1, r2) ({ get width() this.right - this.left, get height() this.bottom - this.top, left: Math.max(r1.left, r2.left), right: Math.min(r1.right, r2.right), top: Math.max(r1.top, r2.top), bottom: Math.min(r1.bottom, r2.bottom) }), /** * Returns the array that results from applying <b>func</b> to each * property of <b>obj</b>. * * @param {Object} obj * @param {function} func * @returns {Array} */ map: function map(obj, func) { let ary = []; for (let i in Iterator(obj)) ary.push(func(i)); return ary; }, /** * Math utility methods. * @singleton */ Math: { /** * Returns the specified <b>value</b> constrained to the range <b>min</b> - * <b>max</b>. * * @param {number} value The value to constrain. * @param {number} min The minimum constraint. * @param {number} max The maximum constraint. * @returns {number} */ constrain: function constrain(value, min, max) Math.min(Math.max(min, value), max) }, /** * Converts a URI string into a URI object. * * @param {string} uri * @returns {nsIURI} */ // FIXME: createURI needed too? newURI: function (uri) { return services.get("io").newURI(uri, null, null); }, /** * Pretty print a JavaScript object. Use HTML markup to color certain items * if <b>color</b> is true. * * @param {Object} object The object to pretty print. * @param {boolean} color Whether the output should be colored. * @returns {string} */ objectToString: function objectToString(object, color) { if (object === null) return "null\n"; if (typeof object != "object") return false; const NAMESPACES = util.Array.toObject([ [NS, 'liberator'], [XHTML, 'html'], [XUL, 'xul'] ]); if (object instanceof Element) { let elem = object; if (elem.nodeType == elem.TEXT_NODE) return elem.data; function namespaced(node) { var ns = NAMESPACES[node.namespaceURI]; if (ns) return ns + ":" + node.localName; return node.localName.toLowerCase(); } try { let tag = xml`${`<${namespaced(elem)} `}${ template.map2(xml, elem.attributes, function (a) xml`${namespaced(a)}=${template.highlight(a.value, true)}`, " ")}${ !elem.firstChild || /^\s*$/.test(elem.firstChild) && !elem.firstChild.nextSibling ? "/>" : `>...</${namespaced(elem)}>`}`; return tag; } catch (e) { return {}.toString.call(elem); } } try { // for window.JSON var obj = String(object); } catch (e) { obj = "[Object]"; } obj = template.highlightFilter(util.clip(obj, 150), "\n", !color ? function () "^J" : function () xml`<span highlight="NonText">^J</span>`); let string = xml`<span highlight="Title Object">${obj}</span>::<br/>&#xa;`; let keys = []; try { // window.content often does not want to be queried with "var i in object" let hasValue = !("__iterator__" in object); if (modules.isPrototypeOf(object)) { object = Iterator(object); hasValue = false; } for (let i in object) { let value = xml`<![CDATA[<no value>]]>`; try { value = object[i]; } catch (e) {} if (!hasValue) { if (i instanceof Array && i.length == 2) [i, value] = i; else var noVal = true; } value = template.highlight(value, true, 150); let key = xml`<span highlight="Key">${i}</span>`; if (!isNaN(i)) i = parseInt(i); else if (/^[A-Z_]+$/.test(i)) i = ""; keys.push([i, xml`${key}${noVal ? "" : xml`: ${value}`}<br/>&#xa;`]); } } catch (e) {} function compare(a, b) { if (!isNaN(a[0]) && !isNaN(b[0])) return a[0] - b[0]; return String.localeCompare(a[0], b[0]); } xml["+="](string, template.map2(xml, keys.sort(compare), function (f) f[1])); return string; }, /** * A generator that returns the values between <b>start</b> and <b>end</b>, * in <b>step</b> increments. * * @param {number} start The interval's start value. * @param {number} end The interval's end value. * @param {boolean} step The value to step the range by. May be * negative. @default 1 * @returns {Iterator(Object)} */ range: function range(start, end, step) { if (!step) step = 1; if (step > 0) { for (; start < end; start += step) yield start; } else { while (start > end) yield start += step; } }, /** * An interruptible generator that returns all values between <b>start</b> * and <b>end</b>. The thread yields every <b>time</b> milliseconds. * * @param {number} start The interval's start value. * @param {number} end The interval's end value. * @param {number} time The time in milliseconds between thread yields. * @returns {Iterator(Object)} */ interruptibleRange: function interruptibleRange(start, end, time) { let endTime = Date.now() + time; while (start < end) { if (Date.now() > endTime) { liberator.threadYield(true, true); endTime = Date.now() + time; } yield start++; } }, /** * Reads a string from the system clipboard. * * This is same as Firefox's readFromClipboard function, but is needed for * apps like Thunderbird which do not provide it. * * @returns {string} */ readFromClipboard: function readFromClipboard() { let str; try { const clipboard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard); const transferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable); transferable.addDataFlavor("text/unicode"); if (clipboard.supportsSelectionClipboard()) clipboard.getData(transferable, clipboard.kSelectionClipboard); else clipboard.getData(transferable, clipboard.kGlobalClipboard); let data = {}; let dataLen = {}; transferable.getTransferData("text/unicode", data, dataLen); if (data) { data = data.value.QueryInterface(Ci.nsISupportsString); str = data.data.substring(0, dataLen.value / 2); } } catch (e) {} return str; }, /** * Returns an array of URLs parsed from <b>str</b>. * * Given a string like 'google bla, www.osnews.com' return an array * ['www.google.com/search?q=bla', 'www.osnews.com'] * * @param {string} str * @returns {string[]} */ stringToURLArray: function stringToURLArray(str) { let urls; if (options["urlseparator"]) urls = util.splitLiteral(str, RegExp("\\s*" + options["urlseparator"] + "\\s*")); else urls = [str]; return urls.map(function (url) { url = url.trim(); if (!url) return ""; if (url.substr(0, 5) != "file:") { try { // Try to find a matching file. let file = io.File(url); if (file.exists() && file.isReadable()) return services.get("io").newFileURI(file).spec; } catch (e) {} } // Look for a valid protocol let proto = url.match(/^([-\w]+):/); if (proto && Cc["@mozilla.org/network/protocol;1?name=" + proto[1]]) // Handle as URL, but remove spaces. Useful for copied/'p'asted URLs. return url.replace(/\s*\n+\s*/g, ""); // Ok, not a valid proto. If it looks like URL-ish (foo.com/bar), // let Gecko figure it out. if (!/^(["']).*\1$/.test(url) && /[.\/]/.test(url) && !/^\.|\s/.test(url) || /^[\w-.]+:\d+(?:\/|$)/.test(url)) return url; // TODO: it would be clearer if the appropriate call to // getSearchURL was made based on whether or not the first word was // indeed an SE alias rather than seeing if getSearchURL can // process the call usefully and trying again if it fails // check for a search engine match in the string, then try to // search for the whole string in the default engine let searchURL = bookmarks.getSearchURL(url, false) || bookmarks.getSearchURL(url, true); if (searchURL) return searchURL; // Hmm. No defsearch? Let the host app deal with it, then. return url; }).filter(function(url, i) i === 0 || url); }, /** * Converts an string, TemplateXML object or E4X literal to a DOM node. * * @param {String|TemplateXML|xml} node * @param {Document} doc * @param {Object} nodes If present, nodes with the "key" attribute are * stored here, keyed to the value thereof. * @returns {Node|DocumentFragment} */ xmlToDom: function xmlToDom(node, doc, nodes) { if (typeof node === "xml") return this.xmlToDomForE4X(node, doc, nodes); var dom = this.xmlToDomForTemplate(node, doc, nodes); //xxx: change highlight's namespace const str = "highlight"; var attr, list = (dom.nodeType === 11 ? dom : dom.parentNode).querySelectorAll("[highlight]"); for (let node of list) { attr = node.getAttribute(str); node.removeAttribute(str); node.setAttributeNS(NS, str, attr); } return dom; }, /** * Converts an E4X XML literal to a DOM node. * * @param {Node} node * @param {Document} doc * @param {Object} nodes * @returns {Node} * @deprecated * @see util.xmlToDom */ xmlToDomForE4X: function xmlToDomForE4X(node, doc, nodes) { if (node.length() != 1) { let domnode = doc.createDocumentFragment(); for each (let child in node) domnode.appendChild(arguments.callee(child, doc, nodes)); return domnode; } switch (node.nodeKind()) { case "text": return doc.createTextNode(String(node)); case "element": let domnode = doc.createElementNS(node.namespace(), node.localName()); for each (let attr in node.attributes()) domnode.setAttributeNS(attr.name() == "highlight" ? NS.uri : attr.namespace(), attr.name(), String(attr)); for each (let child in node.children()) domnode.appendChild(arguments.callee(child, doc, nodes)); if (nodes && node.attribute("key")) nodes[node.attribute("key")] = domnode; return domnode; default: return null; } }, /** * Converts an string of TemplateXML object to a DOM node. * * @param {String|TemplateXML} node * @param {Document} doc * @param {Object} nodes * @returns {Node|DocumentFragment} * @see util.xmlToDom */ xmlToDomForTemplate: function xmlToDomForTemplate(node, doc, nodes) { var range = doc.createRange(); var fragment = range.createContextualFragment( xml`<div xmlns:ns=${NS} xmlns:xul=${XUL} xmlns=${XHTML}>${node}</div>`.toString()); range.selectNodeContents(fragment.firstChild); var dom = range.extractContents(); range.detach(); if (nodes) { for (let elm of dom.querySelectorAll("[key]")) nodes[elm.getAttribute("key")] = elm; } return dom.childNodes.length === 1 ? dom.childNodes[0] : dom; }, /** * encoding dom * * @param {Node|Range|Selection|Document} node * @param {String} type example "text/plain", "text/html", "text/xml", "application/xhtml+xml" etc... * @param {Number} flags nsIDocumentEncoder.OutputXXXX * @returns {String} */ domToStr: let (Encoder = Components.Constructor("@mozilla.org/layout/documentEncoder;1?type=text/plain", "nsIDocumentEncoder", "init")) function domToStr(node, type, flags) { var doc, method; if (node instanceof Document) { doc = node; node = null; method = "setNode"; } else if (node instanceof Node) { doc = node.ownerDocument; method = "setNode"; } else if (node instanceof Range) { doc = node.startContainer; if (doc.ownerDocument) { doc = doc.ownerDocument; } method = "setRange"; } else if (node instanceof Selection) { // can not found document if (node.rangeCount === 0) { return ""; } doc = node.getRangeAt(0).startContainer; if (doc.ownerDocument) { doc = doc.ownerDocument; } method = "setSelection"; } else { return null; } var encoder = new Encoder(doc, type || "text/html", flags || 0); encoder[method](node); return encoder.encodeToString(); }, }, { // TODO: Why don't we just push all util.BuiltinType up into modules? --djk /** * Array utility methods. */ Array: Class("Array", Array, { init: function (ary) { return { __proto__: ary, __iterator__: function () this.iteritems(), __noSuchMethod__: function (meth, args) { var res = util.Array[meth].apply(null, [this.__proto__].concat(args)); if (util.Array.isinstance(res)) return util.Array(res); return res; }, toString: function () this.__proto__.toString(), concat: function () this.__proto__.concat.apply(this.__proto__, arguments), map: function () this.__noSuchMethod__("map", Array.slice(arguments)) }; } }, { isinstance: function isinstance(obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }, /** * Converts an array to an object. As in lisp, an assoc is an * array of key-value pairs, which maps directly to an object, * as such: * [["a", "b"], ["c", "d"]] -> { a: "b", c: "d" } * * @param {Array[]} assoc * @... {string} 0 - Key * @... 1 - Value */ toObject: function toObject(assoc) { let obj = {}; assoc.forEach(function ([k, v]) { obj[k] = v; }); return obj; }, /** * Compacts an array, removing all elements that are null or undefined: * ["foo", null, "bar", undefined] -> ["foo", "bar"] * * @param {Array} ary * @returns {Array} */ compact: function compact(ary) ary.filter(function (item) item != null), /** * Flattens an array, such that all elements of the array are * joined into a single array: * [["foo", ["bar"]], ["baz"], "quux"] -> ["foo", ["bar"], "baz", "quux"] * * @param {Array} ary * @returns {Array} */ flatten: function flatten(ary) Array.prototype.concat.apply([], ary), /** * Returns an Iterator for an array's values. * * @param {Array} ary * @returns {Iterator(Object)} */ itervalues: function itervalues(ary) { let length = ary.length; for (let i = 0; i < length; i++) yield ary[i]; }, /** * Returns an Iterator for an array's indices and values. * * @param {Array} ary * @returns {Iterator([{number}, {Object}])} */ iteritems: function iteritems(ary) { let length = ary.length; for (let i = 0; i < length; i++) yield [i, ary[i]]; }, /** * Filters out all duplicates from an array. If * <b>unsorted</b> is false, the array is sorted before * duplicates are removed. * * @param {Array} ary * @param {boolean} unsorted * @returns {Array} */ uniq: function uniq(ary, unsorted) [...new Set(unsorted ? ary : ary.sort())], }) }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2009 by Kris Maglione <maglione.k@gmail.com> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** * @class ModuleBase * The base class for all modules. */ const ModuleBase = Class("ModuleBase", { /** * @property {[string]} A list of module prerequisites which * must be initialized before this module is loaded. */ requires: [], toString: function () "[module " + this.constructor.name + "]" }); /** * @constructor Module * * Constructs a new ModuleBase class and makes arrangements for its * initialization. Arguments marked as optional must be either * entirely elided, or they must have the exact type specified. * Loading semantics are as follows: * * - A module is guaranteed not to be initialized before any of its * prerequisites as listed in its {@see ModuleBase#requires} member. * - A module is considered initialized once it's been instantiated, * its {@see Class#init} method has been called, and its * instance has been installed into the top-level {@see modules} * object. * - Once the module has been initialized, its module-dependent * initialization functions will be called as described hereafter. * @param {string} name The module's name as it will appear in the * top-level {@see modules} object. * @param {ModuleBase} base The base class for this module. * @optional * @param {Object} prototype The prototype for instances of this * object. The object itself is copied and not used as a prototype * directly. * @param {Object} classProperties The class properties for the new * module constructor. * @optional * @param {Object} moduleInit The module initialization functions * for the new module. Each function is called as soon as the named module * has been initialized, but after the module itself. The constructors are * guaranteed to be called in the same order that the dependent modules * were initialized. * @optional * * @returns {function} The constructor for the resulting module. */ function Module(name, prototype, classProperties, moduleInit) { var base = ModuleBase; if (callable(prototype)) base = Array.splice(arguments, 1, 1)[0]; const module = Class(name, base, prototype, classProperties); module.INIT = moduleInit || {}; module.requires = prototype.requires || []; Module.list.push(module); Module.constructors[name] = module; return module; } Module.list = []; Module.constructors = {}; window.addEventListener("load", function onload() { window.removeEventListener("load", onload, false); function dump(str) window.dump(String.replace(str, /\n?$/, "\n").replace(/^/m, Config.prototype.name.toLowerCase() + ": ")); const start = Date.now(); const deferredInit = { load: [] }; const seen = new Set(); const loaded = []; function load(module, prereq) { try { if (module.name in modules) return; if (seen.has(module.name)) throw Error("Module dependency loop"); seen.add(module.name); for (let dep of module.requires) load(Module.constructors[dep], module.name); dump("Load" + (isstring(prereq) ? " " + prereq + " dependency: " : ": ") + module.name); modules[module.name] = module(); loaded.push(module.name); function init(mod, module) function () module.INIT[mod].call(modules[module.name], modules[mod]); for (let mod of loaded) { try { if (mod in module.INIT) init(mod, module)(); delete module.INIT[mod]; } catch (e) { if (modules.liberator) liberator.echoerr(e); } } for (let mod of Object.keys(module.INIT)) { deferredInit[mod] = deferredInit[mod] || []; deferredInit[mod].push(init(mod, module)); } for (let fn of deferredInit[module.name] || []) fn(); } catch (e) { dump("Loading " + (module && module.name) + ": " + e + "\n"); if (e.stack) dump(e.stack); } } Module.list.forEach(load); deferredInit["load"].forEach(call); for (let module of Module.list) delete module.INIT; dump("Loaded in " + (Date.now() - start) + "ms\n"); }, false); window.addEventListener("unload", function onunload() { window.removeEventListener("unload", onunload, false); for (let [, mod] in iter(modules)) if (mod instanceof ModuleBase && "destroy" in mod) mod.destroy(); }, false); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // Copyright (c) 2008-2010 by Martin Stubenschrott <stubenschrott@vimperator.org> // // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * @constant * @property {string} The default highlighting rules. They have the * form: * rule ::= selector space space+ css * selector ::= group * | group "," css-selector * | group "," css-selector "," scope * group ::= groupname * | groupname css-selector */ // <css> Highlights.prototype.CSS = ` Boolean color: red; Function color: navy; Null color: blue; Number color: blue; Object color: maroon; String color: green; Mapping color: magenta; Key font-weight: bold; Enabled color: green; Disabled color: red; Normal color: black; background: white; ErrorMsg color: white; background: red; font-weight: bold; InfoMsg color: magenta; background: white; ModeMsg color: white; background: green; border-radius: 1px; padding: 0px 5px; MoreMsg color: green; background: white; WarningMsg color: red; background: white; Message white-space: normal; min-width: 100%; padding-left: 2em; text-indent: -2em; display: block; NonText color: blue; min-height: 16px; padding-left: 2px; Preview color: gray; Prompt background: url("chrome://liberator/skin/prompt.png"); width: 10px; background-position: center; background-repeat: no-repeat; PromptText color: white; background: purple; CmdOutput white-space: pre; CmdLine background: white; color: black; transition: all 0.25s; CmdLine>* font-family: monospace; ContentSeparator border-top: 1px dotted gray; display: -moz-box; CompGroup CompGroup:not(:first-of-type) margin-top: 1ex; CompTitle font-weight: bold; background: linear-gradient(to top, #DBDBDB 19%, #D9D9D9, #E7E7E7 100%); CompTitle>* color: #333; border-top: 1px solid gray; border-bottom: 1px solid #BBB; padding: 1px 0.5ex; text-shadow: 1px 1px 0px #E0E0E0; CompMsg font-style: italic; margin-left: 16px; CompItem CompItem[selected] background: #FFEC8B; box-shadow: 0px 0px 1px #CC0; CompItem>* height: 18px; min-height: 18px; padding: 0 0.5ex; CompIcon width: 16px; min-width: 16px; display: inline-block; margin-right: .5ex; CompIcon>img max-width: 16px; max-height: 16px; vertical-align: middle; CompResult width: 500px; max-width: 500px; overflow: hidden; CompDesc width: 500px; max-width: 500px; color: gray; Indicator color: blue; Filter border-radius: 2px; background: #ffec8b; border: 1px solid orange; Keyword color: red; Tag color: blue; LineNr color: orange; background: white; Question color: green; background: white; font-weight: bold; StatusLine color: gray; background: transparent; font-weight: normal; TabNumber font-weight: bold; margin: 0px; padding-right: .3ex; Title color: magenta; background: white; font-weight: bold; URL text-decoration: none; color: green; URL:hover text-decoration: underline; cursor: pointer; FrameIndicator,,* { background-color: red; opacity: 0.5; z-index: 999; position: fixed; top: 0; bottom: 0; left: 0; right: 0; } Bell border: none; background-color: black; Hint,,* { font-family: monospace; font-size: 10px; font-weight: bold; text-transform: uppercase; color: white; background-color: red; border-color: ButtonShadow; border-width: 0px; border-style: solid; padding: 0px 1px 0px 1px; } Hint::after,,* content: attr(number); HintElem,,* background-color: yellow; color: black; HintActive,,* background-color: #88FF00; color: black; HintImage,,* opacity: .5; Help font-size: 8pt; line-height: 1.4em; font-family: -moz-fixed; HelpArg color: #6A97D4; HelpOptionalArg color: #6A97D4; HelpBody display: block; margin: 1em auto; max-width: 100ex; HelpBorder,*,liberator://help/* border-color: silver; border-width: 0px; border-style: solid; HelpCode display: block; white-space: pre; margin-left: 2em; font-family: Terminus, Fixed, monospace; HelpDefault margin-right: 1ex; white-space: pre; HelpDescription display: block; HelpEm,html|em,liberator://help/* font-weight: bold; font-style: normal; HelpEx display: inline-block; color: #527BBD; font-weight: bold; HelpExample display: block; margin: 1em 0; HelpExample::before content: "Example: "; font-weight: bold; HelpInfo display: block; width: 20em; margin-left: auto; HelpInfoLabel display: inline-block; width: 6em; color: magenta; font-weight: bold; vertical-align: text-top; HelpInfoValue display: inline-block; width: 14em; text-decoration: none; vertical-align: text-top; HelpItem display: block; margin: 1em 1em 1em 10em; clear: both; HelpKey color: #102663; HelpLink,html|a,liberator://help/* text-decoration: none; HelpLink[href]:hover text-decoration: underline; HelpList,html|ul,liberator://help/* display: block; list-style: outside disc; HelpOrderedList,html|ol,liberator://help/* display: block; list-style: outside decimal; HelpListItem,html|li,liberator://help/* display: list-item; HelpNote color: red; font-weight: bold; HelpOpt color: #106326; HelpOptInfo display: inline-block; margin-bottom: 1ex; HelpParagraph,html|p,liberator://help/* display: block; margin: 1em 0em; HelpParagraph:first-child margin-top: 0; HelpSpec display: block; margin-left: -10em; float: left; clear: left; color: #FF00FF; HelpString display: inline-block; color: green; font-weight: normal; vertical-align: text-top; HelpString::before content: '"'; HelpString::after content: '"'; HelpHead,html|h1,liberator://help/* { display: block; margin: 1em 0; padding-bottom: .2ex; border-bottom-width: 1px; font-size: 2em; font-weight: bold; color: #527BBD; clear: both; } HelpSubhead,html|h2,liberator://help/* { display: block; margin: 1em 0; padding-bottom: .2ex; border-bottom-width: 1px; font-size: 1.2em; font-weight: bold; color: #527BBD; clear: both; } HelpSubsubhead,html|h3,liberator://help/* { display: block; margin: 1em 0; padding-bottom: .2ex; font-size: 1.1em; font-weight: bold; color: #527BBD; clear: both; } HelpTOC HelpTOC>ol ol margin-left: -1em; HelpTab,html|dl,liberator://help/* display: table; width: 100%; margin: 1em 0; border-bottom-width: 1px; border-top-width: 1px; padding: .5ex 0; table-layout: fixed; HelpTabColumn,html|column,liberator://help/* display: table-column; HelpTabColumn:first-child width: 25%; HelpTabTitle,html|dt,liberator://help/* display: table-cell; padding: .1ex 1ex; font-weight: bold; HelpTabDescription,html|dd,liberator://help/* display: table-cell; padding: .1ex 1ex; border-width: 0px; HelpTabRow,html|dl>html|tr,liberator://help/* display: table-row; HelpTag display: inline-block; color: #999; margin-left: 1ex; font-size: 8pt; font-weight: bold; HelpTags display: block; float: right; clear: right; HelpTopic color: #102663; HelpType margin-right: 2ex; HelpWarning color: red; font-weight: bold; Logo `; /** * A class to manage highlighting rules. The parameters are the * standard parameters for any {@link Storage} object. * * @author Kris Maglione <maglione.k@gmail.com> */ function Highlights(name, store) { let self = this; let highlight = {}; let styles = storage.styles; const Highlight = Struct("class", "selector", "filter", "default", "value", "base"); Highlight.defaultValue("filter", function () this.base ? this.base.filter : ["chrome://liberator/*", "liberator:*", "file://*"].concat(config.styleableChrome).join(",")); Highlight.defaultValue("selector", function () self.selector(this.class)); Highlight.defaultValue("value", function () this.default); Highlight.defaultValue("base", function () { let base = this.class.match(/^(\w*)/)[0]; return base != this.class && base in highlight ? highlight[base] : null; }); Highlight.prototype.toString = function () "Highlight(" + this.class + ")\n\t" + [k + ": " + util.escapeString(v || "undefined") for ([k, v] in this)].join("\n\t"); function keys() [k for ([k, v] in Iterator(highlight))].sort(); this.__iterator__ = function () (highlight[v] for (v of keys())); this.get = function (k) highlight[k]; this.set = function (key, newStyle, force, append) { let [, class_, selectors] = key.match(/^([a-zA-Z_-]+)(.*)/); if (!(class_ in highlight)) return "Unknown highlight keyword: " + class_; let style = highlight[key] || Highlight(key); styles.removeSheet(true, style.selector); if (append) newStyle = (style.value || "").replace(/;?\s*$/, "; " + newStyle); if (/^\s*$/.test(newStyle)) newStyle = null; if (newStyle == null) { if (style.default == null) { delete highlight[style.class]; styles.removeSheet(true, style.selector); return null; } newStyle = style.default; force = true; } let css = newStyle.replace(/(?:!\s*important\s*)?(?:;?\s*$|;)/g, "!important;") .replace(";!important;", ";", "g"); // Seeming Spidermonkey bug if (!/^\s*(?:!\s*important\s*)?;*\s*$/.test(css)) { css = style.selector + " { " + css + " }"; let error = styles.addSheet(true, "highlight:" + style.class, style.filter, css, true); if (error) return error; } style.value = newStyle; highlight[style.class] = style; return null; }; /** * Gets a CSS selector given a highlight group. * * @param {string} class */ this.selector = function (class_) { let [, hl, rest] = class_.match(/^(\w*)(.*)/); let pattern = "[liberator|highlight~=" + hl + "]" if (highlight[hl] && highlight[hl].class != class_) pattern = highlight[hl].selector; return pattern + rest; }; /** * Clears all highlighting rules. Rules with default values are * reset. */ this.clear = function () { for (let [k, v] in Iterator(highlight)) this.set(k, null, true); }; /** * Bulk loads new CSS rules. * * @param {string} css The rules to load. See {@link Highlights#css}. */ this.loadCSS = function (css) { css.replace(/^(\s*\S*\s+)\{((?:.|\n)*?)\}\s*$/gm, function (_, _1, _2) _1 + " " + _2.replace(/\n\s*/g, " ")) .split("\n").filter(function (s) /\S/.test(s)) .forEach(function (style) { style = Highlight.apply(Highlight, Array.slice(style.match(/^\s*((?:[^,\s]|\s\S)+)(?:,((?:[^,\s]|\s\S)+)?)?(?:,((?:[^,\s]|\s\S)+))?\s*(.*)$/), 1)); if (/^[>+ ]/.test(style.selector)) style.selector = self.selector(style.class) + style.selector; let old = highlight[style.class]; highlight[style.class] = style; if (old && old.value != old.default) style.value = old.value; }); for (let [class_, hl] in Iterator(highlight)) { if (hl.value == hl.default) this.set(class_); } }; this.loadCSS(this.CSS); } /** * Manages named and unnamed user style sheets, which apply to both * chrome and content pages. The parameters are the standard * parameters for any {@link Storage} object. * * @author Kris Maglione <maglione.k@gmail.com> */ function Styles(name, store) { // Can't reference liberator or Components inside Styles -- // they're members of the window object, which disappear // with this window. const self = this; const util = modules.util; const sleep = liberator.sleep; const storage = modules.storage; const ios = services.get("io"); const sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService); const namespace = "@namespace html " + XHTML.uri.quote() + ";\n" + "@namespace xul " + XUL.uri.quote() + ";\n" + "@namespace liberator " + NS.uri.quote() + ";\n"; const Sheet = Struct("name", "id", "sites", "css", "system", "agent"); Sheet.prototype.__defineGetter__("fullCSS", function wrapCSS() { let filter = this.sites; let css = this.css; if (filter[0] == "*") return namespace + css; let selectors = filter.map(function (part) (/[*]$/.test(part) ? "url-prefix" : /[\/:]/.test(part) ? "url" : "domain") + '("' + part.replace(/"/g, "%22").replace(/[*]$/, "") + '")') .join(", "); return namespace + "/* Liberator style #" + this.id + " */ @-moz-document " + selectors + "{\n" + css + "\n}\n"; }); Sheet.prototype.__defineGetter__("enabled", function () this._enabled); Sheet.prototype.__defineSetter__("enabled", function (on) { this._enabled = Boolean(on); if (on) { self.registerSheet(cssUri(this.fullCSS)); if (this.agent) self.registerSheet(cssUri(this.fullCSS), true); } else { self.unregisterSheet(cssUri(this.fullCSS)); self.unregisterSheet(cssUri(this.fullCSS), true); } }); let cssUri = function (css) "chrome-data:text/css," + window.encodeURIComponent(css); let userSheets = []; let systemSheets = []; let userNames = {}; let systemNames = {}; let id = 0; this.__iterator__ = function () Iterator(userSheets.concat(systemSheets)); this.__defineGetter__("systemSheets", function () Iterator(systemSheets)); this.__defineGetter__("userSheets", function () Iterator(userSheets)); this.__defineGetter__("systemNames", function () Iterator(systemNames)); this.__defineGetter__("userNames", function () Iterator(userNames)); /** * Add a new style sheet. * * @param {boolean} system Declares whether this is a system or * user sheet. System sheets are used internally by * @liberator. * @param {string} name The name given to the style sheet by * which it may be later referenced. * @param {string} filter The sites to which this sheet will * apply. Can be a domain name or a URL. Any URL ending in * "*" is matched as a prefix. * @param {string} css The CSS to be applied. */ this.addSheet = function (system, name, filter, css, agent) { let sheets = system ? systemSheets : userSheets; let names = system ? systemNames : userNames; if (name && name in names) this.removeSheet(system, name); let sheet = Sheet(name, id++, filter.split(",").filter(util.identity), String(css), system, agent); try { sheet.enabled = true; } catch (e) { return e.echoerr || e; } sheets.push(sheet); if (name) names[name] = sheet; return null; }; /** * Get a sheet with a given name or index. * * @param {boolean} system * @param {string or number} sheet The sheet to retrieve. Strings indicate * sheet names, while numbers indicate indices. */ this.get = function get(system, sheet) { let sheets = system ? systemSheets : userSheets; let names = system ? systemNames : userNames; if (typeof sheet === "number") return sheets[sheet]; return names[sheet]; }; /** * Find sheets matching the parameters. See {@link #addSheet} * for parameters. * * @param {boolean} system * @param {string} name * @param {string} filter * @param {string} css * @param {number} index */ this.findSheets = function (system, name, filter, css, index) { let sheets = system ? systemSheets : userSheets; let names = system ? systemNames : userNames; // Grossly inefficient. let matches = [k for ([k, v] in Iterator(sheets))]; if (index) matches = String(index).split(",").filter(function (i) i in sheets); if (name) matches = matches.filter(function (i) sheets[i] == names[name]); if (css) matches = matches.filter(function (i) sheets[i].css == css); if (filter) matches = matches.filter(function (i) sheets[i].sites.indexOf(filter) >= 0); return matches.map(function (i) sheets[i]); }; /** * Remove a style sheet. See {@link #addSheet} for parameters. * In cases where <b>filter</b> is supplied, the given filters * are removed from matching sheets. If any remain, the sheet is * left in place. * * @param {boolean} system * @param {string} name * @param {string} filter * @param {string} css * @param {number} index */ this.removeSheet = function (system, name, filter, css, index) { let self = this; if (arguments.length == 1) { var matches = [system]; system = matches[0].system; } let sheets = system ? systemSheets : userSheets; let names = system ? systemNames : userNames; if (filter && filter.indexOf(",") > -1) return filter.split(",").reduce( function (n, f) n + self.removeSheet(system, name, f, index), 0); if (filter == undefined) filter = ""; if (!matches) matches = this.findSheets(system, name, filter, css, index); if (matches.length == 0) return null; for (let sheet of matches.reverse()) { sheet.enabled = false; if (name) delete names[name]; if (sheets.indexOf(sheet) > -1) sheets.splice(sheets.indexOf(sheet), 1); /* Re-add if we're only changing the site filter. */ if (filter) { let sites = sheet.sites.filter(function (f) f != filter); if (sites.length) this.addSheet(system, name, sites.join(","), css, sheet.agent); } } return matches.length; }; /** * Register a user style sheet at the given URI. * * @param {string} uri The URI of the sheet to register. * @param {boolean} agent If true, sheet is registered as an agent sheet. * @param {boolean} reload Whether to reload any sheets that are * already registered. */ this.registerSheet = function (uri, agent, reload) { if (reload) this.unregisterSheet(uri, agent); uri = ios.newURI(uri, null, null); if (reload || !sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET)) sss.loadAndRegisterSheet(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET); }; /** * Unregister a sheet at the given URI. * * @param {string} uri The URI of the sheet to unregister. */ this.unregisterSheet = function (uri, agent) { uri = ios.newURI(uri, null, null); if (sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET)) sss.unregisterSheet(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET); }; } Module("styles", { requires: ["config", "liberator", "storage", "util"], init: function () { let (array = util.Array) { update(Styles.prototype, { get sites() array([v.sites for ([k, v] in this.userSheets)]).flatten().uniq().__proto__, completeSite: function (context, content) { context.anchored = false; try { context.fork("current", 0, this, function (context) { context.title = ["Current Site"]; context.completions = [ [content.location.host, "Current Host"], [content.location.href, "Current URL"] ]; }); } catch (e) {} context.fork("others", 0, this, function (context) { context.title = ["Site"]; context.completions = [[s, ""] for (s of styles.sites)]; }); } }); } return storage.newObject("styles", Styles, { store: false }); } }, { }, { commands: function () { commands.add(["sty[le]"], "Add or list user styles", function (args) { let [filter, css] = args; let name = args["-name"]; if (!css) { let list = Array.concat([i for (i in styles.userNames)], [i for (i in styles.userSheets) if (!i[1].name)]); let str = template.tabular([{ header: "", style: "min-width: 1em; text-align: center; font-weight: bold;", highlight: "Disabled" }, "Name", "Filter", "CSS"], ([sheet.enabled ? "" : "\u00d7", key, sheet.sites.join(","), sheet.css] for ([key, sheet] of list) if ((!filter || sheet.sites.indexOf(filter) >= 0) && (!name || sheet.name == name)))); commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } else { if ("-append" in args) { let sheet = styles.get(false, name); if (sheet) { filter = sheet.sites.concat(filter).join(","); css = sheet.css + " " + css; } } let err = styles.addSheet(false, name, filter, css); if (err) liberator.echoerr(err); } }, { bang: true, completer: function (context, args) { let compl = []; if (args.completeArg == 0) styles.completeSite(context, content); else if (args.completeArg == 1) { let sheet = styles.get(false, args["-name"]); if (sheet) context.completions = [[sheet.css.replace(/\n+/g, " "), "Current Value"]]; } }, hereDoc: true, literal: 1, options: [[["-name", "-n"], commands.OPTION_STRING, null, function () [[k, v.css] for ([k, v] in Iterator(styles.userNames))]], [["-append", "-a"], commands.OPTION_NOARG]], serial: function () [ { command: this.name, bang: true, options: sty.name ? { "-name": sty.name } : {}, arguments: [sty.sites.join(",")], literalArg: sty.css } for ([k, sty] in styles.userSheets) ] }); [ { name: ["stylee[nable]", "stye[nable]"], desc: "Enable a user style sheet", action: function (sheet) sheet.enabled = true, filter: function (sheet) !sheet.enabled }, { name: ["styled[isable]", "styd[isable]"], desc: "Disable a user style sheet", action: function (sheet) sheet.enabled = false, filter: function (sheet) sheet.enabled }, { name: ["stylet[oggle]", "styt[oggle]"], desc: "Toggle a user style sheet", action: function (sheet) sheet.enabled = !sheet.enabled }, { name: ["dels[tyle]"], desc: "Remove a user style sheet", action: function (sheet) styles.removeSheet(sheet) } ].forEach(function (cmd) { commands.add(cmd.name, cmd.desc, function (args) { styles.findSheets(false, args["-name"], args[0], args.literalArg, args["-index"]) .forEach(cmd.action); }, { completer: function (context) { context.completions = styles.sites.map(function (site) [site, ""]); }, literal: 1, options: [[["-index", "-i"], commands.OPTION_INT, null, function (context) { context.compare = CompletionContext.Sort.number; return [[i, `${sheet.sites.join(",")}: ${sheet.css.replace("\n", "\\n")}`] for ([i, sheet] in styles.userSheets) if (!cmd.filter || cmd.filter(sheet))]; }], [["-name", "-n"], commands.OPTION_STRING, null, function () [[name, sheet.css] for ([name, sheet] in Iterator(styles.userNames)) if (!cmd.filter || cmd.filter(sheet))]]] }); }); }, completion: function () { JavaScript.setCompleter(["get", "addSheet", "removeSheet", "findSheets"].map(function (m) styles[m]), [ // Prototype: (system, name, filter, css, index) null, function (context, obj, args) args[0] ? styles.systemNames : styles.userNames, function (context, obj, args) styles.completeSite(context, content), null, function (context, obj, args) args[0] ? styles.systemSheets : styles.userSheets ]); } }); Module("highlight", { requires: ["config", "styles"], init: function () { const self = storage.newObject("highlight", Highlights, { store: false }); if (self.CSS != Highlights.prototype.CSS) { self.CSS = Highlights.prototype.CSS; self.loadCSS(self.CSS); } return self; } }, { }, { commands: function () { commands.add(["colo[rscheme]"], "Load a color scheme", function (args) { let scheme = args[0]; if (scheme == "default") highlight.clear(); else liberator.assert(io.sourceFromRuntimePath(["colors/" + scheme + ".vimp"]), "No such color scheme: " + scheme); autocommands.trigger("ColorScheme", { name: scheme }); }, { argCount: "1", completer: function (context) { context.title = ["Extra Completions"]; context.completions = [ ["default", "Clear all highlights"] ]; context.fork("colorScheme", 0, completion, "colorScheme"); } }); commands.add(["hi[ghlight]"], "Set the style of certain display elements", function (args) { let style = ` ; display: inline-block !important; position: static !important; margin: 0px !important; padding: 0px !important; width: 3em !important; min-width: 3em !important; max-width: 3em !important; height: 1em !important; min-height: 1em !important; max-height: 1em !important; overflow: hidden !important; `; let clear = args[0] == "clear"; if (clear) args.shift(); let [key, css] = args; liberator.assert(!(clear && css), "Trailing characters"); if (!css && !clear) { // List matching keys let str = template.tabular(["Key", { header: "Sample", style: "text-align: center" }, "CSS"], ([h.class, xml`<span style=${h.value + style}>XXX</span>`, template.highlightRegexp(h.value, /\b[-\w]+(?=:)/g, function (str) xml`<span style="font-weight: bold;">${str}</span>`)] for (h in highlight) if (!key || h.class.indexOf(key) > -1))); commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); return; } if (!key && clear) highlight.clear(); else { let error = highlight.set(key, css, clear, "-append" in args); if (error) liberator.echoerr(error); } }, { // TODO: add this as a standard highlight completion function? completer: function (context, args) { // Complete a highlight group on :hi clear ... if (args.completeArg > 0 && args[0] == "clear") args.completeArg = args.completeArg > 1 ? -1 : 0; if (args.completeArg == 0) context.completions = [[v.class, v.value] for (v in highlight)]; else if (args.completeArg == 1) { let hl = highlight.get(args[0]); if (hl) context.completions = [[hl.value.replace(/\n+/g, " "), "Current Value"], [hl.default || "", "Default Value"]]; } }, hereDoc: true, literal: 1, options: [[["-append", "-a"], commands.OPTION_NOARG]], serial: function () [ { command: this.name, arguments: [v.class], literalArg: v.value } for (v in highlight) if (v.value != v.default) ] }); }, completion: function () { completion.colorScheme = function colorScheme(context) { context.title = ["Color Scheme", "Runtime Path"]; context.keys = { text: function (f) f.leafName.replace(/\.vimp$/, ""), description: ".parent.path" }; context.completions = util.Array.flatten( io.getRuntimeDirectories("colors").map( function (dir) dir.readDirectory().filter( function (file) /\.vimp$/.test(file.leafName)))) }; completion.highlightGroup = function highlightGroup(context) { context.title = ["Highlight Group", "Value"]; context.completions = [[v.class, v.value] for (v in highlight)]; }; } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * @instance browser */ const Browser = Module("browser", { }, { // TODO: support 'nrformats'? -> probably not worth it --mst incrementURL: function (count) { let matches = buffer.URL.match(/(.*?)(\d+)(\D*)$/); liberator.assert(matches); let [, pre, number, post] = matches; let newNumber = parseInt(number, 10) + count; let newNumberStr = String(newNumber > 0 ? newNumber : 0); if (number.match(/^0/)) { // add 0009<C-a> should become 0010 while (newNumberStr.length < number.length) newNumberStr = "0" + newNumberStr; } liberator.open(pre + newNumberStr + post); } }, { options: function () { options.add(["encoding", "enc"], "Sets the current buffer's character encoding", "string", "UTF-8", { scope: Option.SCOPE_LOCAL, getter: function () config.browser.docShell.QueryInterface(Ci.nsIDocCharset).charset, setter: function (val) { if (options["encoding"] == val) return val; // Stolen from browser.jar/content/browser/browser.js, more or less. try { config.browser.docShell.QueryInterface(Ci.nsIDocCharset).charset = val; PlacesUtils.history.setCharsetForURI(getWebNavigation().currentURI, val); getWebNavigation().reload(Ci.nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE); } catch (e) { liberator.echoerr(e); } return null; }, completer: function (context) completion.charset(context) }); // only available in FF 3.5-19 // TODO: remove when FF ESR's version is over 20. privateBrowsing will be per-window from FF 20+ // XXX: on Fx20, nsIPrivateBrowsingService exists yet but has no properties let pb = services.get("privateBrowsing"); if (pb && "privateBrowsingEnabled" in pb) { options.add(["private", "pornmode"], "Set the 'private browsing' option", "boolean", false, { setter: function (value) services.get("privateBrowsing").privateBrowsingEnabled = value, getter: function () services.get("privateBrowsing").privateBrowsingEnabled }); let services = modules.services; // Storage objects are global to all windows, 'modules' isn't. storage.newObject("private-mode", function () { ({ init: function () { services.get("obs").addObserver(this, "private-browsing", false); services.get("obs").addObserver(this, "quit-application", false); this.private = services.get("privateBrowsing").privateBrowsingEnabled; }, observe: function (subject, topic, data) { if (topic == "private-browsing") { if (data == "enter") storage.privateMode = true; else if (data == "exit") storage.privateMode = false; storage.fireEvent("private-mode", "change", storage.privateMode); } else if (topic == "quit-application") { services.get("obs").removeObserver(this, "quit-application"); services.get("obs").removeObserver(this, "private-browsing"); } } }).init(); }, { store: false }); storage.addObserver("private-mode", function (key, event, value) { autocommands.trigger("PrivateMode", { state: value }); }, window); } options.add(["urlseparator"], "Set the separator regex used to separate multiple URL args", "string", ",\\s"); }, mappings: function () { mappings.add([modes.NORMAL], ["y"], "Yank current location to the clipboard", function () { var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL); util.copyToClipboard(url, true); }); // opening websites mappings.add([modes.NORMAL], ["o"], "Open one or more URLs", function () { commandline.open("", "open ", modes.EX); }); mappings.add([modes.NORMAL], ["O"], "Open one or more URLs, based on current location", function () { var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL); commandline.open("", "open " + url, modes.EX); }); mappings.add([modes.NORMAL], ["t"], "Open one or more URLs in a new tab", function () { commandline.open("", "tabopen ", modes.EX); }); mappings.add([modes.NORMAL], ["T"], "Open one or more URLs in a new tab, based on current location", function () { var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL); commandline.open("", "tabopen " + url, modes.EX); }); mappings.add([modes.NORMAL], ["w"], "Open one or more URLs in a new window", function () { commandline.open("", "winopen ", modes.EX); }); mappings.add([modes.NORMAL], ["W"], "Open one or more URLs in a new window, based on current location", function () { var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL); commandline.open("", "winopen " + url, modes.EX); }); mappings.add([modes.NORMAL], ["<C-a>"], "Increment last number in URL", function (count) { Browser.incrementURL(Math.max(count, 1)); }, { count: true }); mappings.add([modes.NORMAL], ["<C-x>"], "Decrement last number in URL", function (count) { Browser.incrementURL(-Math.max(count, 1)); }, { count: true }); mappings.add([modes.NORMAL], ["~"], "Open home directory", function () { liberator.open("~"); }); mappings.add([modes.NORMAL], ["gh"], "Open homepage", function () { BrowserHome(); }); mappings.add([modes.NORMAL], ["gH"], "Open homepage in a new tab", function () { let homepages = gHomeButton.getHomePage(); homepages = homepages.replace(/\|/g, options["urlseparator"] || ", "); // we use a different url seperator than Firefox liberator.open(homepages, { from: "homepage", where: liberator.NEW_TAB }); }); mappings.add([modes.NORMAL], ["gu"], "Go to parent directory", function (count) { function getParent(url, count) { function getParentPath(path) { if (!path) return; path = path.replace(/\/$/, "").replace(/^\/+/, ""); if (path.indexOf("#") > 0) return path.replace(/#.*/, ""); if (path.indexOf("?") > 0) return path.replace(/\?.*/, ""); path = path.replace(/\/+$/, ""); if (path.indexOf("/") > 0) return path.replace(/\/[^\/]*$/,"/"); } function getParentHost(host) { if (!/\./.test(host) || /^[0-9+.:]+$/.test(host)) return host; let hostSuffix = ""; let x = host.lastIndexOf(":"); if (x > 0) { hostSuffix = host.substr(x); host = host.substr(0, x); } hostSuffix = host.substr(host.length - 6) + hostSuffix; host = host.substr(0, host.length - 6); return host.replace(/[^.]*\./, "") + hostSuffix; } let parent = url; let regexp = new RegExp("([a-z]+:///?)([^/]*)(/.*)"); let [, scheme, host, path] = regexp.exec(url); path = path.replace(/\/$/, "").replace(/^\/+/, ""); for (let i = 0; i < count; i++) { if (path) { if (path = getParentPath(path)) parent = scheme + host + "/" + path; else parent = scheme + host + "/"; } else { host = getParentHost(host); parent = scheme + host + "/"; } } return parent; } if (count < 1) count = 1; let url = getParent(buffer.URL, count); if (url == buffer.URL) liberator.beep(); else liberator.open(url); }, { count: true }); mappings.add([modes.NORMAL], ["gU"], "Go to the root of the website", function () { let uri = content.document.location; liberator.assert(!/(about|mailto):/.test(uri.protocol)); // exclude these special protocols for now liberator.open(uri.protocol + "//" + (uri.host || "") + "/"); }); }, commands: function () { commands.add(["downl[oads]", "dl"], "Show progress of current downloads", function () { liberator.open("chrome://mozapps/content/downloads/downloads.xul", { from: "downloads"}); }, { argCount: "0" }); commands.add(["o[pen]"], "Open one or more URLs in the current tab", function (args) { args = args.string; if (args) liberator.open(args); else liberator.open(""); }, { completer: function (context) completion.url(context), literal: 0, privateData: true }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * A class representing key mappings. Instances are created by the * {@link Mappings} class. * * @param {number[]} modes The modes in which this mapping is active. * @param {string[]} keys The key sequences which are bound to * <b>action</b>. * @param {string} description A short one line description of the key mapping. * @param {function} action The action invoked by each key sequence. * @param {Object} extraInfo An optional extra configuration hash. The * following properties are supported. * arg - see {@link Map#arg} * count - see {@link Map#count} * motion - see {@link Map#motion} * route - see {@link Map#route} * noremap - see {@link Map#noremap} * rhs - see {@link Map#rhs} * silent - see {@link Map#silent} * matchingUrls - see {@link Map#matchingUrls} * @optional * @private */ const Map = Class("Map", { init: function (modes, keys, description, action, extraInfo) { modes = Array.concat(modes).map(function (m) isobject(m) ? m.mask : m); this.modes = modes; this.names = keys.map(events.canonicalKeys); this.action = action; this.description = description; if (extraInfo) update(this, extraInfo); if (this.matchingUrls) this.matchingUrls = this.matchingUrls instanceof RegExp ? this.matchingUrls : RegExp(this.matchingUrls); }, /** @property {number[]} All of the modes for which this mapping applies. */ modes: null, /** @property {string[]} All of this mapping's names (key sequences). */ names: null, /** @property {function (number)} The function called to execute this mapping. */ action: null, /** @property {string} This mapping's description, as shown in :usage. */ description: "", /** @property {boolean} Whether this mapping accepts an argument. */ arg: false, /** @property {boolean} Whether this mapping accepts a count. */ count: false, /** * @property {boolean} Whether the mapping accepts a motion mapping * as an argument. */ motion: false, /** * @property {boolean} Whether the mapping's key events should be * propagated to the host application. */ // TODO: I'm not sure this is the best name but it reflects that which it replaced. --djk route: false, /** @property {boolean} Whether the RHS of the mapping should expand mappings recursively. */ noremap: false, /** @property {boolean} Whether any output from the mapping should be echoed on the command line. */ silent: false, /** @property {string} The literal RHS expansion of this mapping. */ rhs: null, /** @property {RegExp} URL matching pattern for URL local mapping. */ matchingUrls: null, /** * @property {boolean} Specifies whether this is a user mapping. User * mappings may be created by plugins, or directly by users. Users and * plugin authors should create only user mappings. */ user: false, /** * Returns whether this mapping can be invoked by a key sequence matching * <b>name</b>. * * @param {string} name The name to query. * @returns {boolean} */ hasName: function (name) this.names.indexOf(name) >= 0, /** * Execute the action for this mapping. * * @param {string} motion The motion argument if accepted by this mapping. * E.g. "w" for "dw" * @param {number} count The associated count. E.g. "5" for "5j" * @default -1 * @param {string} argument The normal argument if accepted by this * mapping. E.g. "a" for "ma" */ execute: function (motion, count, argument) { let args = []; if (this.motion) args.push(motion); if (this.count) args.push(count); if (this.arg) args.push(argument); let self = this; function repeat() self.action.apply(self, args); if (this.names[0] != ".") // FIXME: Kludge. mappings.repeat = repeat; return liberator.trapErrors(repeat); }, /** * Returns true if same mapping. * * @param {Mapping} * @returns {boolean} */ equals: function (map) { return this.rhs == map.rhs && this.names[0] == map.names && this.matchingUrls == map.matchingUrls; } }); /** * @instance mappings */ const Mappings = Module("mappings", { requires: ["modes"], init: function () { this._main = []; // default mappings this._user = []; // user created mappings }, _matchingUrlsTest: function (map, patternOrUrl) { if (!patternOrUrl) return !map.matchingUrls; if (patternOrUrl instanceof RegExp) return map.matchingUrls && (patternOrUrl.toString() == map.matchingUrls.toString()); return !map.matchingUrls || map.matchingUrls.test(patternOrUrl); }, _addMap: function (map) { let where = map.user ? this._user : this._main; map.modes.forEach(function (mode) { if (!(mode in where)) where[mode] = []; // URL local mappings should be searched first. where[mode][map.matchingUrls ? 'unshift' : 'push'](map); }); }, _getMap: function (mode, cmd, patternOrUrl, stack) { let maps = stack[mode] || []; for (let map of maps) { if (map.hasName(cmd) && this._matchingUrlsTest(map, patternOrUrl)) return map; } return null; }, _removeMap: function (mode, cmd, patternOrUrl) { let maps = this._user[mode] || []; let names; for (let [i, map] in Iterator(maps)) { if (!this._matchingUrlsTest(map, patternOrUrl)) continue; for (let [j, name] in Iterator(map.names)) { if (name == cmd) { map.names.splice(j, 1); if (map.names.length == 0) maps.splice(i, 1); return; } } } }, _expandLeader: function (keyString) keyString.replace(/<Leader>/gi, mappings.getMapLeader()), // Return all mappings present in all @modes _mappingsIterator: function (modes, stack) { modes = modes.slice(); return (map for (map of stack[modes.shift()]) if (modes.every(function (mode) stack[mode].some( function (m) map.equals(m))))) }, // NOTE: just normal mode for now /** @property {Iterator(Map)} @private */ __iterator__: function () this._mappingsIterator([modes.NORMAL], this._main), // used by :mkvimperatorrc to save mappings /** * Returns a user-defined mappings iterator for the specified * <b>mode</b>. * * @param {number} mode The mode to return mappings from. * @returns {Iterator(Map)} */ getUserIterator: function (mode) this._mappingsIterator(mode, this._user), addMode: function (mode) { if (!(mode in this._user || mode in this._main)) { this._main[mode] = []; this._user[mode] = []; } }, /** * Adds a new default key mapping. * * @param {number[]} modes The modes that this mapping applies to. * @param {string[]} keys The key sequences which are bound to * <b>action</b>. * @param {string} description A description of the key mapping. * @param {function} action The action invoked by each key sequence. * @param {Object} extra An optional extra configuration hash. * @optional * @returns {Map} */ add: function (modes, keys, description, action, extra) { let map = Map(modes, keys, description, action, extra); this._addMap(map); return map; }, /** * Adds a new user-defined key mapping. * * @param {number[]} modes The modes that this mapping applies to. * @param {string[]} keys The key sequences which are bound to * <b>action</b>. * @param {string} description A description of the key mapping. * @param {function} action The action invoked by each key sequence. * @param {Object} extra An optional extra configuration hash (see * {@link Map#extraInfo}). * @optional * @returns {Map} */ addUserMap: function (modes, keys, description, action, extra) { keys = keys.map(this._expandLeader); extra = extra || {}; extra.user = true; let map = Map(modes, keys, description || "User defined mapping", action, extra); // remove all old mappings to this key sequence for (let name of map.names) { for (let mode of map.modes) this._removeMap(mode, name, map.matchingUrls); } this._addMap(map); return map; }, /** * Returns the map from <b>mode</b> named <b>cmd</b>. * * @param {number} mode The mode to search. * @param {string} cmd The map name to match. * @param {RegExp|string} URL matching pattern or URL. * @returns {Map} */ get: function (mode, cmd, patternOrUrl) { mode = mode || modes.NORMAL; return this._getMap(mode, cmd, patternOrUrl, this._user) || this._getMap(mode, cmd, patternOrUrl, this._main); }, /** * Returns the default map from <b>mode</b> named <b>cmd</b>. * * @param {number} mode The mode to search. * @param {string} cmd The map name to match. * @param {RegExp|string} URL matching pattern or URL. * @returns {Map} */ getDefault: function (mode, cmd, patternOrUrl) { mode = mode || modes.NORMAL; return this._getMap(mode, cmd, patternOrUrl, this._main); }, /** * Returns an array of maps with names starting with but not equal to * <b>prefix</b>. * * @param {number} mode The mode to search. * @param {string} prefix The map prefix string to match. * @param {RegExp|string} URL matching pattern or URL. * @returns {Map[]} */ getCandidates: function (mode, prefix, patternOrUrl) { let mappings = this._user[mode].concat(this._main[mode]); let matches = []; for (let map of mappings) { if (!this._matchingUrlsTest(map, patternOrUrl)) continue; for (let name of map.names) { if (name.startsWith(prefix) && name.length > prefix.length) { // for < only return a candidate if it doesn't look like a <c-x> mapping if (prefix != "<" || !/^<.+>/.test(name)) matches.push(map); } } } return matches; }, /* * Returns the map leader string used to replace the special token * "<Leader>" when user mappings are defined. * * @returns {string} */ // FIXME: property getMapLeader: function () { let leaderRef = liberator.variableReference("mapleader"); return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\"; }, /** * Returns whether there is a user-defined mapping <b>cmd</b> for the * specified <b>mode</b>. * * @param {number} mode The mode to search. * @param {string} cmd The candidate key mapping. * @param {RegExp|string} URL matching pattern or URL. * @returns {boolean} */ hasMap: function (mode, cmd, patternOrUrl) let (self = this) this._user[mode].some(function (map) map.hasName(cmd) && self._matchingUrlsTest(map, patternOrUrl)), /** * Remove the user-defined mapping named <b>cmd</b> for <b>mode</b>. * * @param {number} mode The mode to search. * @param {string} cmd The map name to match. * @param {RegExp|string} URL matching pattern or URL. */ remove: function (mode, cmd, patternOrUrl) { this._removeMap(mode, cmd, patternOrUrl); }, /** * Remove all user-defined mappings for <b>mode</b>. * * @param {number} mode The mode to remove all mappings from. */ removeAll: function (mode) { this._user[mode] = []; }, /** * Lists all user-defined mappings matching <b>filter</b> for the * specified <b>modes</b>. * * @param {number[]} modes An array of modes to search. * @param {string} filter The filter string to match. * @param {RegExp|string} URL matching pattern or URL. */ list: function (modes, filter, urlPattern) { let maps = this._mappingsIterator(modes, this._user); if (filter) maps = [map for (map of maps) if (map.names[0] == filter)]; if (urlPattern) maps = [map for (map of maps) if (this._matchingUrlsTest(map, urlPattern))]; // build results let displayMaps = []; for (map of maps) { let modes = ""; map.modes.forEach(function (mode) { for (let m in modules.modes.mainModes) if (mode == m.mask)// && modeSign.indexOf(m.char) == -1) //modeSign += (modeSign ? "" : ",") + m.name; modes += (modes ? ", " : "") + m.name; }); let option = xml``; var add = function (lhs, rhs) xml`${lhs}${rhs}`; if (map.silent) option = add(option, xml`<span highlight="Keyword">silent</span>`); if (map.noremap) { if (map.silent) option = add(option, `, `); option = add(option, xml`<span highlight="Keyword">noremap</span>`); } displayMaps.push([map.names, map.rhs || "function () { ... }", modes, option, map.matchingUrls]); } if (displayMaps.length == 0) { liberator.echomsg("No mapping found"); return; } let list = template.tabular([{ header: "Mapping", highlight: "Mapping" }, "Expression", { header: "Modes", highlight: "ModeMsg" }, "Options", "URLs"], displayMaps); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } }, { }, { commands: function () { function addMapCommands(ch, modes, modeDescription) { // 0 args -> list all maps // 1 arg -> list the maps starting with args // 2 args -> map arg1 to arg* function map(args, modes, noremap) { let urls = args['-urls']; if (!args.length) { mappings.list(modes, null, urls && RegExp(urls)); return; } let [lhs, rhs] = args; if (!rhs) // list the mapping mappings.list(modes, mappings._expandLeader(lhs), urls && RegExp(urls)); else { // this matches Vim's behaviour if (/^<Nop>$/i.test(rhs)) noremap = true; mappings.addUserMap(modes, [lhs], "User defined mapping", function (count) { events.feedkeys((count || "") + this.rhs, this.noremap, this.silent); }, { count: true, rhs: events.canonicalKeys(mappings._expandLeader(rhs)), noremap: !!noremap, silent: "<silent>" in args, matchingUrls: urls }); } } modeDescription = modeDescription ? " in " + modeDescription + " mode" : ""; // :map, :noremap => NORMAL + VISUAL modes function isMultiMode(map, cmd) { return map.modes.indexOf(modules.modes.NORMAL) >= 0 && map.modes.indexOf(modules.modes.VISUAL) >= 0 && /^[nv](nore)?map$/.test(cmd); } function regexpValidator(expr) { try { RegExp(expr); return true; } catch (e) {} return false; } function urlsCompleter (modes, current) { return function () { let completions = util.Array.uniq([ m.matchingUrls.source for (m in mappings.getUserIterator(modes)) if (m.matchingUrls) ]).map(function (re) [re, re]); if (current) { if (buffer.URL) completions.unshift([util.escapeRegex(buffer.URL), "Current buffer URL"]); if (content.document && content.document.domain) completions.unshift([util.escapeRegex(content.document.domain), "Current buffer domain"]); } return completions; }; } const opts = { completer: function (context, args) completion.userMapping(context, args, modes), options: [ [["<silent>", "<Silent>"], commands.OPTION_NOARG], [["-urls", "-u"], commands.OPTION_STRING, regexpValidator, urlsCompleter(modes, true)], ], literal: 1, serial: function () { function options (map) { let opts = {}; if (map.silent) opts["<silent>"] = null; if (map.matchingUrls) opts["-urls"] = map.matchingUrls.source; return opts; } let noremap = this.name.indexOf("noremap") > -1; return [ { command: this.name, options: options(map), arguments: [map.names[0]], literalArg: map.rhs } for (map in mappings._mappingsIterator(modes, mappings._user)) if (map.rhs && map.noremap == noremap && !isMultiMode(map, this.name)) ]; } }; commands.add([ch ? ch + "m[ap]" : "map"], "Map a key sequence" + modeDescription, function (args) { map(args, modes, false); }, opts); commands.add([ch + "no[remap]"], "Map a key sequence without remapping keys" + modeDescription, function (args) { map(args, modes, true); }, opts); commands.add([ch + "mapc[lear]"], "Remove all mappings" + modeDescription, function () { modes.forEach(function (mode) { mappings.removeAll(mode); }); }, { argCount: "0" }); commands.add([ch + "unm[ap]"], "Remove a mapping" + modeDescription, function (args) { let lhs = events.canonicalKeys(args[0]); let urls = args["-urls"] && RegExp(args["-urls"]); let found = false; for (let mode of modes) { if (mappings.hasMap(mode, lhs, urls)) { mappings.remove(mode, lhs, urls); found = true; } } if (!found) liberator.echoerr("No such mapping: " + lhs); }, { argCount: "1", options: [ [["-urls", "-u"], commands.OPTION_STRING, regexpValidator, urlsCompleter(modes)], ], completer: function (context, args) completion.userMapping(context, args, modes) }); } addMapCommands("", [modes.NORMAL, modes.VISUAL], ""); for (let mode in modes.mainModes) if (mode.char && !commands.get(mode.char + "map")) addMapCommands(mode.char, [m.mask for (m in modes.mainModes) if (m.char == mode.char)], [mode.disp.toLowerCase()]); }, completion: function () { JavaScript.setCompleter(this.get, [ null, function (context, obj, args) { let mode = args[0]; return [ [name, map.description] for (map of mappings._user[mode].concat(mappings._main[mode])) for (name of map.names)]; } ]); completion.userMapping = function userMapping(context, args, modes) { // FIXME: have we decided on a 'standard' way to handle this clash? --djk modes = modes || [modules.modes.NORMAL]; let urls = args["-urls"] && RegExp(args["-urls"]); if (args.completeArg == 0) { let maps = [ [m.names[0], ""] for (m in mappings.getUserIterator(modes)) if (mappings._matchingUrlsTest(m, urls)) ]; context.completions = maps; } }; }, modes: function () { for (let mode in modes) { this._main[mode] = []; this._user[mode] = []; } } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** @instance hints */ const Hints = Module("hints", { requires: ["config"], init: function () { this._hintMode = null; this._submode = ""; // used for extended mode, can be "o", "t", "y", etc. this._hintString = ""; // the typed string part of the hint is in this string this._hintNumber = 0; // only the numerical part of the hint this._usedTabKey = false; // when we used <Tab> to select an element this._prevInput = ""; // record previous user input type, "text" || "number" this._extendedhintCount = null; // for the count argument of Mode#action (extended hint only) this._pageHints = []; this._validHints = []; // store the indices of the "hints" array with valid elements this._tabNavigation = {}; // for navigating between valid hints when TAB key is pressed this._activeTimeout = null; // needed for hinttimeout > 0 this._canUpdate = false; // keep track of the documents which we generated the hints for // this._docs = { doc: document, start: start_index in hints[], end: end_index in hints[] } this._docs = []; const Mode = Hints.Mode; Mode.defaultValue("tags", function () function () options.hinttags); function extended() options.extendedhinttags; function images() "//*[@src]"; this._hintModes = { ";": Mode("Focus hint", function (elem) buffer.focusElement(elem), extended), "?": Mode("Show information for hint", function (elem) buffer.showElementInfo(elem), extended), s: Mode("Save link", function (elem) buffer.saveLink(elem, true)), S: Mode("Save object", function (elem) buffer.saveLink(elem, true), images), a: Mode("Save link with prompt", function (elem) buffer.saveLink(elem, false)), A: Mode("Save object with prompt", function (elem) buffer.saveLink(elem, false), images), f: Mode("Focus frame", function (elem) Buffer.focusedWindow = elem.ownerDocument.defaultView, function () util.makeXPath(["body"])), o: Mode("Follow hint", function (elem) buffer.followLink(elem, liberator.CURRENT_TAB)), t: Mode("Follow hint in a new tab", function (elem) buffer.followLink(elem, liberator.NEW_TAB)), b: Mode("Follow hint in a background tab", function (elem) buffer.followLink(elem, liberator.NEW_BACKGROUND_TAB)), w: Mode("Follow hint in a new window", function (elem) buffer.followLink(elem, liberator.NEW_WINDOW), extended), F: Mode("Open multiple hints in tabs", followAndReshow), O: Mode("Generate an ':open URL' using hint", function (elem, loc) commandline.open("", "open " + loc, modes.EX)), T: Mode("Generate a ':tabopen URL' using hint", function (elem, loc) commandline.open("", "tabopen " + loc, modes.EX)), W: Mode("Generate a ':winopen URL' using hint", function (elem, loc) commandline.open("", "winopen " + loc, modes.EX)), v: Mode("View hint source", function (elem, loc) buffer.viewSource(loc, false), extended), V: Mode("View hint source in external editor", function (elem, loc) buffer.viewSource(loc, true), extended), y: Mode("Yank hint location", function (elem, loc) util.copyToClipboard(loc, true)), Y: Mode("Yank hint description", function (elem) util.copyToClipboard(elem.textContent || "", true), extended), c: Mode("Open context menu", function (elem) buffer.openContextMenu(elem), extended), i: Mode("Show media object", function (elem) liberator.open(elem.src), images), I: Mode("Show media object in a new tab", function (elem) liberator.open(elem.src, liberator.NEW_TAB), images), x: Mode("Show hint's title or alt text", function (elem) liberator.echo(elem.title ? "title: " + elem.title : "alt: " + elem.alt), function() "//*[@title or @alt]") }; /** * Follows the specified hint and then reshows all hints. Used to open * multiple hints in succession. * * @param {Node} elem The selected hint. */ function followAndReshow(elem) { buffer.followLink(elem, liberator.NEW_BACKGROUND_TAB); // TODO: Maybe we find a *simple* way to keep the hints displayed rather than // showing them again, or is this short flash actually needed as a "usability // feature"? --mst hints.show("F"); } }, /** * Reset hints, so that they can be cleanly used again. */ _reset: function () { statusline.updateField("input", ""); this._hintString = ""; this._hintNumber = 0; this._usedTabKey = false; this._prevInput = ""; this._pageHints = []; this._validHints = []; this._tabNavigation = {}; this._canUpdate = false; this._docs = []; hints.escNumbers = false; if (this._activeTimeout) clearTimeout(this._activeTimeout); this._activeTimeout = null; }, /** * Display the current status to the user. */ _updateStatusline: function () { statusline.updateField("input", (hints.escNumbers ? mappings.getMapLeader() : "") + (this._hintNumber ? this._num2chars(this._hintNumber) : "")); }, /** * Get a hint for "input", "textarea" and "select". * * Tries to use <label>s if possible but does not try to guess that a * neighbouring element might look like a label. Only called by * {@link #_generate}. * * If it finds a hint it returns it, if the hint is not the caption of the * element it will return showText=true. * * @param {Object} elem The element used to generate hint text. * @param {Document} doc The containing document. * * @returns [text, showText] */ _getInputHint: function (elem, doc) { // <input type="submit|button|reset"/> Always use the value // <input type="radio|checkbox"/> Use the value if it is not numeric or label or name // <input type="password"/> Never use the value, use label or name // <input type="text|file"/> <textarea/> Use value if set or label or name // <input type="image"/> Use the alt text if present (showText) or label or name // <input type="hidden"/> Never gets here // <select/> Use the text of the selected item or label or name let type = elem.type; if (elem instanceof HTMLInputElement && /(submit|button|reset)/.test(type)) return [elem.value, false]; else { for (let option of options["hintinputs"].split(",")) { switch (option) { case "value": if (elem instanceof HTMLSelectElement) { if (elem.selectedIndex >= 0) return [elem.item(elem.selectedIndex).text.toLowerCase(), false]; } else if (type == "image") { if (elem.alt) return [elem.alt.toLowerCase(), true]; } else if (elem.value && type != "password") { // radio's and checkboxes often use internal ids as values - maybe make this an option too... if (! ((type == "radio" || type == "checkbox") && !isNaN(elem.value))) return [elem.value.toLowerCase(), (type == "radio" || type == "checkbox")]; } break; case "label": if (elem.id) { // TODO: (possibly) do some guess work for label-like objects let label = util.evaluateXPath(["label[@for=" + elem.id.quote() + "]"], doc).snapshotItem(0); if (label) return [label.textContent.toLowerCase(), true]; } break; case "name": return [elem.name.toLowerCase(), true]; } } } return ["", false]; }, /** * Gets the actual offset of an imagemap area. * * Only called by {@link #_generate}. * * @param {Object} elem The <area> element. * @param {number} leftPos The left offset of the image. * @param {number} topPos The top offset of the image. * @returns [leftPos, topPos] The updated offsets. */ _getAreaOffset: function (elem, leftPos, topPos) { try { // Need to add the offset to the area element. // Always try to find the top-left point, as per liberator default. let shape = elem.getAttribute("shape").toLowerCase(); let coordStr = elem.getAttribute("coords"); // Technically it should be only commas, but hey coordStr = coordStr.replace(/\s+[;,]\s+/g, ",").replace(/\s+/g, ","); let coords = coordStr.split(",").map(Number); if ((shape == "rect" || shape == "rectangle") && coords.length == 4) { leftPos += coords[0]; topPos += coords[1]; } else if (shape == "circle" && coords.length == 3) { leftPos += coords[0] - coords[2] / Math.sqrt(2); topPos += coords[1] - coords[2] / Math.sqrt(2); } else if ((shape == "poly" || shape == "polygon") && coords.length % 2 == 0) { let leftBound = Infinity; let topBound = Infinity; // First find the top-left corner of the bounding rectangle (offset from image topleft can be noticably suboptimal) for (let i = 0; i < coords.length; i += 2) { leftBound = Math.min(coords[i], leftBound); topBound = Math.min(coords[i + 1], topBound); } let curTop = null; let curLeft = null; let curDist = Infinity; // Then find the closest vertex. (we could generalise to nearest point on an edge, but I doubt there is a need) for (let i = 0; i < coords.length; i += 2) { let leftOffset = coords[i] - leftBound; let topOffset = coords[i + 1] - topBound; let dist = Math.sqrt(leftOffset * leftOffset + topOffset * topOffset); if (dist < curDist) { curDist = dist; curLeft = coords[i]; curTop = coords[i + 1]; } } // If we found a satisfactory offset, let's use it. if (curDist < Infinity) return [leftPos + curLeft, topPos + curTop]; } } catch (e) {} // badly formed document, or shape == "default" in which case we don't move the hint return [leftPos, topPos]; }, // the containing block offsets with respect to the viewport _getContainerOffsets: function (doc) { try { var body = doc.body || doc.documentElement; } catch (e) { return [null, null]; } // TODO: getComputedStyle returns null for Facebook channel_iframe doc - probable Gecko bug. let style = util.computedStyle(body); if (style && /^(absolute|fixed|relative)$/.test(style.position)) { let rect = body.getClientRects()[0]; return [-rect.left, -rect.top]; } else return [doc.defaultView.scrollX, doc.defaultView.scrollY]; }, /** * Returns true if element is visible. * * Only called by {@link #_generate}. */ _isVisible: function (elem, screen) { let doc = elem.ownerDocument; let win = doc.defaultView; // TODO: for iframes, this calculation is wrong let rect = elem.getBoundingClientRect(); if (!rect || rect.top > screen.bottom || rect.bottom < screen.top || rect.left > screen.right || rect.right < screen.left) return false; rect = elem.getClientRects()[0]; if (!rect) return false; let computedStyle = doc.defaultView.getComputedStyle(elem, null); if (computedStyle.getPropertyValue("visibility") != "visible" || computedStyle.getPropertyValue("display") == "none") return false; return true; }, /** * Generate the hints in a window. * * Pushes the hints into the pageHints object, but does not display them. * * @param {Window} win The window for which to generate hints. * @default config.browser.contentWindow */ _generate: function (win, screen) { if (!win) win = config.browser.contentWindow; if (!screen) screen = {top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth}; let doc = win.document; let baseNodeAbsolute = util.xmlToDom(xml`<span highlight="Hint"/>`, doc); let res = util.evaluateXPath(this._hintMode.tags(), doc, null, true); let fragment = util.xmlToDom(xml`<div highlight="hints" style="position:fixed;top:0;left:0px;"/>`, doc); let pageHints = this._pageHints; let start = this._pageHints.length; let elem; let that = this; function makeHint (elem) { let rect = elem.getClientRects()[0]; let hint = { elem: elem, showText: false }; if (elem instanceof HTMLInputElement || elem instanceof HTMLSelectElement || elem instanceof HTMLTextAreaElement) [hint.text, hint.showText] = that._getInputHint(elem, doc); else hint.text = elem.textContent.toLowerCase(); hint.span = baseNodeAbsolute.cloneNode(true); let leftPos = rect.left > screen.left ? rect.left : screen.left; let topPos = rect.top > screen.top ? rect.top : screen.top; if (elem instanceof HTMLAreaElement) [leftPos, topPos] = that._getAreaOffset(elem, leftPos, topPos); hint.span.style.left = leftPos + "px"; hint.span.style.top = topPos + "px"; fragment.appendChild(hint.span); pageHints[pageHints.length] = hint; } while (elem = res.iterateNext()) { let rect = elem.getBoundingClientRect(); // If the rect has a zero dimension, it may contain // floated children. In that case, the children's rects // are most probably where the hints should be at. if (rect.width == 0 || rect.height == 0) { let hasFloatChild = false; for (let i = 0; i < elem.childNodes.length; i++) { if (elem.childNodes[i].nodeType != 1) // nodeType 1: elem_NODE continue; // getComputedStyle returns null, if the owner frame is not visible. let computedStyle = doc.defaultView.getComputedStyle(elem.childNodes[i], null); if (computedStyle && computedStyle.getPropertyValue('float') != 'none' && this._isVisible(elem.childNodes[i], screen)) { makeHint(elem.childNodes[i]); hasFloatChild = true; break; } } if (hasFloatChild) continue; } if (this._isVisible(elem, screen)) makeHint(elem); } let body = (doc instanceof XULDocument) ? doc.documentElement : doc.body || util.evaluateXPath(["body"], doc).snapshotItem(0); if (body) { body.appendChild(fragment); this._docs.push({ doc: doc, start: start, end: this._pageHints.length - 1 }); } // also _generate hints for frames for (let frame in util.Array.itervalues(win.frames)) { elem = frame.frameElement; if (!this._isVisible(elem, screen)) continue; let rect = elem.getBoundingClientRect(); this._generate(frame,{ top : Math.max(0, screen.top - rect.top), left : Math.max(0, screen.left - rect.left), bottom : Math.min(frame.innerHeight, screen.bottom - rect.top), right : Math.min(frame.innerWidth, screen.right - rect.left) }); } return true; }, /** * Update the activeHint. * * By default highlights it green instead of yellow. * * @param {number} newId The hint to make active. * @param {number} oldId The currently active hint. */ _showActiveHint: function (newId, oldId) { let oldElem = this._validHints[oldId - 1]; if (oldElem) this._setClass(oldElem, false); let newElem = this._validHints[newId - 1]; if (newElem) this._setClass(newElem, true); }, /** * Toggle the highlight of a hint. * * @param {Object} elem The element to toggle. * @param {boolean} active Whether it is the currently active hint or not. */ _setClass: function (elem, active) { let prefix = (elem.getAttributeNS(NS.uri, "class") || "") + " "; if (active) elem.setAttributeNS(NS.uri, "highlight", prefix + "HintActive"); else elem.setAttributeNS(NS.uri, "highlight", prefix + "HintElem"); }, /** * Display the hints in pageHints that are still valid. */ _showHints: function () { let hintnum = 1; let validHint = this._hintMatcher(this._hintString.toLowerCase()); let activeHint = this._hintNumber || 1; this._validHints = []; this._tabNavigation = {}; let firstHint = null; let lastHint = null; let prevHint = null; let activeHintChars = this._num2chars(activeHint); for (let { doc, start, end } of this._docs) { if (!(doc instanceof Node)) continue; let [offsetX, offsetY] = this._getContainerOffsets(doc); if (offsetX === null && offsetY === null) continue; inner: for (let i in (util.interruptibleRange(start, end + 1, 500))) { let hint = this._pageHints[i]; let valid = validHint(hint.text); let hintnumchars = this._num2chars(hintnum); let display = valid && ( this._hintNumber == 0 || hintnumchars.indexOf(String(activeHintChars)) == 0 ); hint.span.style.display = (display ? "" : "none"); if (hint.imgSpan) hint.imgSpan.style.display = (display ? "" : "none"); if (!valid || !display) { hint.elem.removeAttributeNS(NS.uri, "highlight"); if (valid) { this._validHints.push(hint.elem); hintnum++; } continue inner; } if (hint.text == "" && hint.elem.firstChild && hint.elem.firstChild instanceof HTMLImageElement) { if (!hint.imgSpan) { let rect = hint.elem.firstChild.getBoundingClientRect(); if (!rect) continue; hint.imgSpan = util.xmlToDom(xml`<span highlight="Hint" liberator:class="HintImage" xmlns:liberator=${NS}/>`, doc); hint.imgSpan.style.left = (rect.left + offsetX) + "px"; hint.imgSpan.style.top = (rect.top + offsetY) + "px"; hint.imgSpan.style.width = (rect.right - rect.left) + "px"; hint.imgSpan.style.height = (rect.bottom - rect.top) + "px"; hint.span.parentNode.appendChild(hint.imgSpan); } this._setClass(hint.imgSpan, activeHint == hintnum); } hint.span.setAttribute("number", hint.showText ? hintnumchars + ": " + hint.text.substr(0, 50) : hintnumchars); if (hint.imgSpan) hint.imgSpan.setAttribute("number", hintnumchars); else this._setClass(hint.elem, activeHint == hintnum); this._validHints.push(hint.elem); // Set up tab navigation for valid hints firstHint = (firstHint ) ? firstHint : hintnum ; lastHint = hintnum; prevHint = (prevHint) ? prevHint : hintnum; this._tabNavigation[hintnum] = {prev: prevHint, next:prevHint}; this._tabNavigation[prevHint].next = hintnum; prevHint = hintnum; hintnum++; } } this._tabNavigation[firstHint].prev = lastHint; this._tabNavigation[lastHint].next = firstHint; if (config.browser.markupDocumentViewer.authorStyleDisabled) { let css = []; // FIXME: Broken for imgspans. for (let { doc } of this._docs) { for (let elem in util.evaluateXPath(" {//*[@liberator:highlight and @number]", doc)) { let group = elem.getAttributeNS(NS.uri, "highlight"); css.push(highlight.selector(group) + "[number=" + elem.getAttribute("number").quote() + "] { " + elem.style.cssText + " }"); } } styles.addSheet(true, "hint-positions", "*", css.join("\n")); } return true; }, /** * Remove all hints from the document, and reset the completions. * * Lingers on the active hint briefly to confirm the selection to the user. * * @param {number} timeout The number of milliseconds before the active * hint disappears. */ _removeHints: function (timeout) { let firstElem = this._validHints[0] || null; for (let { doc, start, end } of this._docs) { if (!(doc instanceof Node)) continue; let result = util.evaluateXPath("//*[@liberator:highlight='hints']", doc, null, true); let hints = new Array(); let elem; // Lucas de Vries: Deleting elements while iterating creates // problems, therefore store the items in a temporary array first. while (elem = result.iterateNext()) hints.push(elem); while (elem = hints.pop()) elem.parentNode.removeChild(elem); for (let i in util.range(start, end + 1)) { let hint = this._pageHints[i]; if (!timeout || hint.elem != firstElem) hint.elem.removeAttributeNS(NS.uri, "highlight"); } // animate the disappearance of the first hint if (timeout && firstElem) setTimeout(function () { firstElem.removeAttributeNS(NS.uri, "highlight"); }, timeout); } styles.removeSheet(true, "hint-positions"); this._reset(); }, _num2chars: function (num) { let hintchars = options["hintchars"]; let chars = ""; let base = hintchars.length; do { chars = hintchars[((num % base))] + chars; num = Math.floor(num / base); } while (num > 0); return chars; }, _chars2num: function (chars) { let num = 0; let hintchars = options["hintchars"]; let base = hintchars.length; for (let i = 0, l = chars.length; i < l; ++i) { num = base * num + hintchars.indexOf(chars[i]); } return num; }, _isHintNumber: function (key) options["hintchars"].indexOf(key) >= 0, /** * Finish hinting. * * Called when there are one or zero hints in order to possibly activate it * and, if activated, to clean up the rest of the hinting system. * * @param {boolean} followFirst Whether to force the following of the first * link (when 'followhints' is 1 or 2) * */ _processHints: function (followFirst) { if (this._validHints.length == 0) { liberator.beep(); return false; } // This "followhints" option is *too* confusing. For me, and // presumably for users, too. --Kris if (options["followhints"] > 0) { if (!followFirst) return false; // no return hit; don't examine uniqueness // OK. return hit. But there's more than one hint, and // there's no tab-selected current link. Do not follow in mode 2 liberator.assert(options["followhints"] != 2 || this._validHints.length == 1 || this._hintNumber) } if (!followFirst) { let firstHref = this._validHints[0].getAttribute("href") || null; if (firstHref) { if (this._validHints.some(function (e) e.getAttribute("href") != firstHref)) return false; } else if (this._validHints.length > 1) return false; } let timeout = followFirst || events.feedingKeys ? 0 : 500; let activeIndex = (this._hintNumber ? this._hintNumber - 1 : 0); let elem = this._validHints[activeIndex]; this._removeHints(timeout); if (timeout == 0) // force a possible mode change, based on whether an input field has focus events.onFocusChange(); this.setTimeout(function () { if (modes.extended & modes.HINTS) modes.reset(); this._hintMode.action(elem, elem.href || "", this._extendedhintCount); }, timeout); return true; }, _checkUnique: function () { if (this._hintNumber == 0) return; liberator.assert(this._hintNumber <= this._validHints.length); // if we write a numeric part like 3, but we have 45 hints, only follow // the hint after a timeout, as the user might have wanted to follow link 34 if (this._hintNumber > 0 && this._hintNumber * options["hintchars"].length <= this._validHints.length) { let timeout = options["hinttimeout"]; if (timeout > 0) this._activeTimeout = this.setTimeout(function () { this._processHints(true); }, timeout); } else // we have a unique hint this._processHints(true); }, /** * Handle user input. * * Will update the filter on displayed hints and follow the final hint if * necessary. * * @param {Event} event The keypress event. */ _onInput: function (event) { this._prevInput = "text"; // clear any timeout which might be active after pressing a number if (this._activeTimeout) { clearTimeout(this._activeTimeout); this._activeTimeout = null; } this._hintNumber = 0; this._hintString = commandline.command; this._updateStatusline(); this._showHints(); if (this._validHints.length == 1) this._processHints(false); }, /** * Get the hintMatcher according to user preference. * * @param {string} hintString The currently typed hint. * @returns {hintMatcher} */ _hintMatcher: function (hintString) { //{{{ /** * Divide a string by a regular expression. * * @param {RegExp|string} pat The pattern to split on. * @param {string} str The string to split. * @returns {Array(string)} The lowercased splits of the splitting. */ function tokenize(pat, str) str.split(pat).map(String.toLowerCase); /** * Get a hint matcher for hintmatching=contains * * The hintMatcher expects the user input to be space delimited and it * returns true if each set of characters typed can be found, in any * order, in the link. * * @param {string} hintString The string typed by the user. * @returns {function(String):boolean} A function that takes the text * of a hint and returns true if all the (space-delimited) sets of * characters typed by the user can be found in it. */ function containsMatcher(hintString) { //{{{ let tokens = tokenize(/\s+/, hintString); return function (linkText) { linkText = linkText.toLowerCase(); return tokens.every(function (token) indexOf(linkText, token) >= 0); }; } //}}} /** * Get a hintMatcher for hintmatching=firstletters|wordstartswith * * The hintMatcher will look for any division of the user input that * would match the first letters of words. It will always only match * words in order. * * @param {string} hintString The string typed by the user. * @param {boolean} allowWordOverleaping Whether to allow non-contiguous * words to match. * @returns {function(String):boolean} A function that will filter only * hints that match as above. */ function wordStartsWithMatcher(hintString, allowWordOverleaping) { //{{{ let hintStrings = tokenize(/\s+/, hintString); let wordSplitRegex = RegExp(options["wordseparators"]); /** * Match a set of characters to the start of words. * * What the **** does this do? --Kris * This function matches hintStrings like 'hekho' to links * like 'Hey Kris, how are you?' -> [HE]y [K]ris [HO]w are you * --Daniel * * @param {string} chars The characters to match. * @param {Array(string)} words The words to match them against. * @param {boolean} allowWordOverleaping Whether words may be * skipped during matching. * @returns {boolean} Whether a match can be found. */ function charsAtBeginningOfWords(chars, words, allowWordOverleaping) { function charMatches(charIdx, chars, wordIdx, words, inWordIdx, allowWordOverleaping) { let matches = (chars[charIdx] == words[wordIdx][inWordIdx]); if ((matches == false && allowWordOverleaping) || words[wordIdx].length == 0) { let nextWordIdx = wordIdx + 1; if (nextWordIdx == words.length) return false; return charMatches(charIdx, chars, nextWordIdx, words, 0, allowWordOverleaping); } if (matches) { let nextCharIdx = charIdx + 1; if (nextCharIdx == chars.length) return true; let nextWordIdx = wordIdx + 1; let beyondLastWord = (nextWordIdx == words.length); let charMatched = false; if (beyondLastWord == false) charMatched = charMatches(nextCharIdx, chars, nextWordIdx, words, 0, allowWordOverleaping); if (charMatched) return true; if (charMatched == false || beyondLastWord == true) { let nextInWordIdx = inWordIdx + 1; if (nextInWordIdx == words[wordIdx].length) return false; return charMatches(nextCharIdx, chars, wordIdx, words, nextInWordIdx, allowWordOverleaping); } } return false; } return charMatches(0, chars, 0, words, 0, allowWordOverleaping); } /** * Check whether the array of strings all exist at the start of the * words. * * i.e. ['ro', 'e'] would match ['rollover', 'effect'] * * The matches must be in order, and, if allowWordOverleaping is * false, contiguous. * * @param {Array(string)} strings The strings to search for. * @param {Array(string)} words The words to search in. * @param {boolean} allowWordOverleaping Whether matches may be * non-contiguous. * @returns {boolean} Whether all the strings matched. */ function stringsAtBeginningOfWords(strings, words, allowWordOverleaping) { let strIdx = 0; for (let word of words) { if (word.length == 0) continue; let str = strings[strIdx]; if (str.length == 0 || indexOf(word, str) == 0) strIdx++; else if (!allowWordOverleaping) return false; if (strIdx == strings.length) return true; } for (; strIdx < strings.length; strIdx++) { if (strings[strIdx].length != 0) return false; } return true; } return function (linkText) { if (hintStrings.length == 1 && hintStrings[0].length == 0) return true; let words = tokenize(wordSplitRegex, linkText); if (hintStrings.length == 1) return charsAtBeginningOfWords(hintStrings[0], words, allowWordOverleaping); else return stringsAtBeginningOfWords(hintStrings, words, allowWordOverleaping); }; } //}}} let indexOf = String.indexOf; if (options.get("hintmatching").has("transliterated")) indexOf = Hints.indexOf; switch (options.get("hintmatching").values[0]) { case "contains" : return containsMatcher(hintString); case "wordstartswith": return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ true); case "firstletters" : return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ false); case "custom" : return liberator.plugins.customHintMatcher(hintString); default : liberator.echoerr("Invalid hintmatching type: " + hintMatching); } return null; }, //}}} /** * Creates a new hint mode. * * @param {string} mode The letter that identifies this mode. * @param {string} prompt The description to display to the user * about this mode. * @param {function(Node)} action The function to be called with the * element that matches. * @param {function():string} tags The function that returns an * XPath expression to decide which elements can be hinted (the * default returns options.hinttags). * @optional */ addMode: function (mode, prompt, action, tags) { this._hintModes[mode] = Hints.Mode.apply(Hints.Mode, Array.slice(arguments, 1)); }, /** * Updates the display of hints. * * @param {string} minor Which hint mode to use. * @param {string} filter The filter to use. * @param {Object} win The window in which we are showing hints. */ show: function (minor, filter, win) { this._hintMode = this._hintModes[minor]; liberator.assert(this._hintMode); commandline.input(this._hintMode.prompt, null, { onChange: this.closure._onInput }); modes.extended = modes.HINTS; this._submode = minor; this._hintString = filter || ""; this._hintNumber = 0; this._usedTabKey = false; this._prevInput = ""; this._canUpdate = false; this._generate(win); // get all keys from the input queue liberator.threadYield(true); this._canUpdate = true; this._showHints(); if (this._validHints.length == 0) { liberator.beep(); modes.reset(); } else if (this._validHints.length == 1) this._processHints(false); else // Ticket #185 this._checkUnique(); }, /** * start an extended hint mode * * @param {string} filter The filter to use. * @param {Object} win The window in which we are showing hints. */ startExtendedHint: function (filter, win) { commandline.input(";", function onSubmit (str) { if (str in hints._hintModes) setTimeout(function(){ hints.show(str, filter, win); }, 0); }, { promptHighlight: "Normal", completer: function (context) { context.compare = function () 0; context.completions = [[k, v.prompt] for ([k, v] in Iterator(hints._hintModes))]; }, onChange: function (str) { if (str in hints._hintModes) { hints.show(str, filter, win); if (commandline._completionList.visible()) commandline._completionList.hide(); } }, }); }, /** * Cancel all hinting. */ hide: function () { this._removeHints(0); }, /** * Handle a hint mode event. * * @param {Event} event The event to handle. */ onEvent: function (event) { let key = events.toString(event); let followFirst = false; // clear any timeout which might be active after pressing a number if (this._activeTimeout) { clearTimeout(this._activeTimeout); this._activeTimeout = null; } switch (key) { case "<Return>": followFirst = true; break; case "<Tab>": case "<S-Tab>": this._usedTabKey = true; if (this._hintNumber == 0) this._hintNumber = 1; let oldId = this._hintNumber; if (key == "<Tab>") this._hintNumber = this._tabNavigation[this._hintNumber].next; else this._hintNumber = this._tabNavigation[this._hintNumber].prev; this._showActiveHint(this._hintNumber, oldId); this._updateStatusline(); return; case "<BS>": if (this._hintNumber > 0 && !this._usedTabKey) { this._hintNumber = Math.floor(this._hintNumber / 10); if (this._hintNumber == 0) this._prevInput = "text"; } else { this._usedTabKey = false; this._hintNumber = 0; liberator.beep(); return; } break; case mappings.getMapLeader(): hints.escNumbers = !hints.escNumbers; if (hints.escNumbers && this._usedTabKey) // this._hintNumber not used normally, but someone may wants to toggle this._hintNumber = 0; // <tab>s ? this._reset. Prevent to show numbers not entered. this._updateStatusline(); return; default: if (this._isHintNumber(key)) { this._prevInput = "number"; let oldHintNumber = this._hintNumber; if (this._hintNumber == 0 || this._usedTabKey) { this._usedTabKey = false; this._hintNumber = this._chars2num(key); } else this._hintNumber = this._chars2num(this._num2chars(this._hintNumber) + key); this._updateStatusline(); if (!this._canUpdate) return; if (this._docs.length == 0) { this._generate(); this._showHints(); } this._showActiveHint(this._hintNumber, oldHintNumber || 1); liberator.assert(this._hintNumber != 0); this._checkUnique(); } } this._updateStatusline(); if (this._canUpdate) { if (this._docs.length == 0 && this._hintString.length > 0) this._generate(); this._showHints(); this._processHints(followFirst); } } // FIXME: add resize support // window.addEventListener("resize", onResize, null); // function onResize(event) // { // if (event) // doc = event.originalTarget; // else // doc = window.content.document; // } //}}} }, { indexOf: (function () { const table = [ [0x00c0, 0x00c6, ["A"]], [0x00c7, 0x00c7, ["C"]], [0x00c8, 0x00cb, ["E"]], [0x00cc, 0x00cf, ["I"]], [0x00d1, 0x00d1, ["N"]], [0x00d2, 0x00d6, ["O"]], [0x00d8, 0x00d8, ["O"]], [0x00d9, 0x00dc, ["U"]], [0x00dd, 0x00dd, ["Y"]], [0x00e0, 0x00e6, ["a"]], [0x00e7, 0x00e7, ["c"]], [0x00e8, 0x00eb, ["e"]], [0x00ec, 0x00ef, ["i"]], [0x00f1, 0x00f1, ["n"]], [0x00f2, 0x00f6, ["o"]], [0x00f8, 0x00f8, ["o"]], [0x00f9, 0x00fc, ["u"]], [0x00fd, 0x00fd, ["y"]], [0x00ff, 0x00ff, ["y"]], [0x0100, 0x0105, ["A", "a"]], [0x0106, 0x010d, ["C", "c"]], [0x010e, 0x0111, ["D", "d"]], [0x0112, 0x011b, ["E", "e"]], [0x011c, 0x0123, ["G", "g"]], [0x0124, 0x0127, ["H", "h"]], [0x0128, 0x0130, ["I", "i"]], [0x0132, 0x0133, ["IJ", "ij"]], [0x0134, 0x0135, ["J", "j"]], [0x0136, 0x0136, ["K", "k"]], [0x0139, 0x0142, ["L", "l"]], [0x0143, 0x0148, ["N", "n"]], [0x0149, 0x0149, ["n"]], [0x014c, 0x0151, ["O", "o"]], [0x0152, 0x0153, ["OE", "oe"]], [0x0154, 0x0159, ["R", "r"]], [0x015a, 0x0161, ["S", "s"]], [0x0162, 0x0167, ["T", "t"]], [0x0168, 0x0173, ["U", "u"]], [0x0174, 0x0175, ["W", "w"]], [0x0176, 0x0178, ["Y", "y", "Y"]], [0x0179, 0x017e, ["Z", "z"]], [0x0180, 0x0183, ["b", "B", "B", "b"]], [0x0187, 0x0188, ["C", "c"]], [0x0189, 0x0189, ["D"]], [0x018a, 0x0192, ["D", "D", "d", "F", "f"]], [0x0193, 0x0194, ["G"]], [0x0197, 0x019b, ["I", "K", "k", "l", "l"]], [0x019d, 0x01a1, ["N", "n", "O", "O", "o"]], [0x01a4, 0x01a5, ["P", "p"]], [0x01ab, 0x01ab, ["t"]], [0x01ac, 0x01b0, ["T", "t", "T", "U", "u"]], [0x01b2, 0x01d2, ["V", "Y", "y", "Z", "z", "D", "L", "N", "A", "a", "I", "i", "O", "o"]], [0x01d3, 0x01dc, ["U", "u"]], [0x01de, 0x01e1, ["A", "a"]], [0x01e2, 0x01e3, ["AE", "ae"]], [0x01e4, 0x01ed, ["G", "g", "G", "g", "K", "k", "O", "o", "O", "o"]], [0x01f0, 0x01f5, ["j", "D", "G", "g"]], [0x01fa, 0x01fb, ["A", "a"]], [0x01fc, 0x01fd, ["AE", "ae"]], [0x01fe, 0x0217, ["O", "o", "A", "a", "A", "a", "E", "e", "E", "e", "I", "i", "I", "i", "O", "o", "O", "o", "R", "r", "R", "r", "U", "u", "U", "u"]], [0x0253, 0x0257, ["b", "c", "d", "d"]], [0x0260, 0x0269, ["g", "h", "h", "i", "i"]], [0x026b, 0x0273, ["l", "l", "l", "l", "m", "n", "n"]], [0x027c, 0x028b, ["r", "r", "r", "r", "s", "t", "u", "u", "v"]], [0x0290, 0x0291, ["z"]], [0x029d, 0x02a0, ["j", "q"]], [0x1e00, 0x1e09, ["A", "a", "B", "b", "B", "b", "B", "b", "C", "c"]], [0x1e0a, 0x1e13, ["D", "d"]], [0x1e14, 0x1e1d, ["E", "e"]], [0x1e1e, 0x1e21, ["F", "f", "G", "g"]], [0x1e22, 0x1e2b, ["H", "h"]], [0x1e2c, 0x1e8f, ["I", "i", "I", "i", "K", "k", "K", "k", "K", "k", "L", "l", "L", "l", "L", "l", "L", "l", "M", "m", "M", "m", "M", "m", "N", "n", "N", "n", "N", "n", "N", "n", "O", "o", "O", "o", "O", "o", "O", "o", "P", "p", "P", "p", "R", "r", "R", "r", "R", "r", "R", "r", "S", "s", "S", "s", "S", "s", "S", "s", "S", "s", "T", "t", "T", "t", "T", "t", "T", "t", "U", "u", "U", "u", "U", "u", "U", "u", "U", "u", "V", "v", "V", "v", "W", "w", "W", "w", "W", "w", "W", "w", "W", "w", "X", "x", "X", "x", "Y", "y"]], [0x1e90, 0x1e9a, ["Z", "z", "Z", "z", "Z", "z", "h", "t", "w", "y", "a"]], [0x1ea0, 0x1eb7, ["A", "a"]], [0x1eb8, 0x1ec7, ["E", "e"]], [0x1ec8, 0x1ecb, ["I", "i"]], [0x1ecc, 0x1ee3, ["O", "o"]], [0x1ee4, 0x1ef1, ["U", "u"]], [0x1ef2, 0x1ef9, ["Y", "y"]], [0x2071, 0x2071, ["i"]], [0x207f, 0x207f, ["n"]], [0x249c, 0x24b5, "a"], [0x24b6, 0x24cf, "A"], [0x24d0, 0x24e9, "a"], [0xfb00, 0xfb06, ["ff", "fi", "fl", "ffi", "ffl", "st", "st"]], [0xff21, 0xff3a, "A"], [0xff41, 0xff5a, "a"], ].map(function (a) { if (typeof a[2] == "string") a[3] = function (chr) String.fromCharCode(this[2].charCodeAt(0) + chr - this[0]); else a[3] = function (chr) this[2][(chr - this[0]) % this[2].length]; return a; }); function translate(chr) { var m, c = chr.charCodeAt(0); var n = table.length; var i = 0; while (n) { m = Math.floor(n / 2); var t = table[i + m]; if (c >= t[0] && c <= t[1]) return t[3](c); if (c < t[0] || m == 0) n = m; else { i += m; n = n - m; } } return chr; } return function indexOf(dest, src) { var end = dest.length - src.length; if (src.length == 0) return 0; outer: for (var i = 0; i < end; i++) { var j = i; for (var k = 0; k < src.length;) { var s = translate(dest[j++]); for (var l = 0; l < s.length; l++, k++) { if (s[l] != src[k]) continue outer; if (k == src.length - 1) return i; } } } return -1; } })(), Mode: Struct("prompt", "action", "tags") }, { mappings: function () { var myModes = config.browserModes; mappings.add(myModes, ["f"], "Start QuickHint mode", function () { hints.show("o"); }); // At the moment, "F" calls // buffer.followLink(clicked_element, DO_WHAT_FIREFOX_DOES_WITH_CNTRL_CLICK) // It is not clear that it shouldn't be: // buffer.followLink(clicked_element, !DO_WHAT_FIREFOX_DOES_WITH_CNTRL_CLICK) // In fact, it might be nice if there was a "dual" to F (like H and // gH, except that gF is already taken). --tpp // // Likewise, it might be nice to have a liberator.NEW_FOREGROUND_TAB // and then make liberator.NEW_TAB always do what a Ctrl+Click // does. --tpp mappings.add(myModes, ["F"], "Start QuickHint mode, but open link in a new tab", function () { hints.show(options.getPref("browser.tabs.loadInBackground") ? "b" : "t"); }); mappings.add(myModes, [";"], "Start an extended hint mode", function (count) { hints._extendedhintCount = count; hints.startExtendedHint(); }, { count: true }); }, options: function () { const DEFAULT_HINTTAGS = util.makeXPath(["input[not(@type='hidden')]", "a", "area", "iframe", "textarea", "button", "select"]) + " | //*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @role='link'or @role='button' or @role='checkbox' or @role='combobox' or @role='listbox' or @role='listitem' or @role='menuitem' or @role='menuitemcheckbox' or @role='menuitemradio' or @role='option' or @role='radio' or @role='scrollbar' or @role='slider' or @role='spinbutton' or @role='tab' or @role='textbox' or @role='treeitem' or @tabindex]" + (config.name == "Muttator" ? " | //xhtml:div[@class='wrappedsender']/xhtml:div[contains(@class,'link')]" : ""); function checkXPath(val) { try { util.evaluateXPath(val, document.implementation.createDocument("", "", null)); return true; } catch (e) { return false; } } options.add(["extendedhinttags", "eht"], "XPath string of hintable elements activated by ';'", "string", DEFAULT_HINTTAGS, { validator: checkXPath, scope: Option.SCOPE_BOTH }); options.add(["hinttags", "ht"], "XPath string of hintable elements activated by 'f' and 'F'", "string", DEFAULT_HINTTAGS, { validator: checkXPath, scope: Option.SCOPE_BOTH }); options.add(["hinttimeout", "hto"], "Timeout before automatically following a non-unique numerical hint", "number", 0, { validator: function (value) value >= 0 }); options.add(["followhints", "fh"], // FIXME: this description isn't very clear but I can't think of a // better one right now. "Change the behaviour of <Return> in hint mode", "number", 0, { completer: function () [ ["0", "Follow the first hint as soon as typed text uniquely identifies it. Follow the selected hint on <Return>."], ["1", "Follow the selected hint on <Return>."], ["2", "Follow the selected hint on <Return> only it's been <Tab>-selected."] ] }); options.add(["hintmatching", "hm"], "How links are matched", "stringlist", "contains", { completer: function (context) [ ["contains", "The typed characters are split on whitespace. The resulting groups must all appear in the hint."], ["wordstartswith", "The typed characters are split on whitespace. The resulting groups must all match the beginings of words, in order."], ["firstletters", "Behaves like wordstartswith, but all groups much match a sequence of words."], ["custom", "Delegate to a custom function: liberator.plugins.customHintMatcher(hintString)"], ["transliterated", "When true, special latin characters are translated to their ascii equivalent (e.g., \u00e9 -> e)"] ] }); options.add(["hintchars", "hc"], "What characters to use for labeling hints", "string", "0123456789", // TODO: Change to charlist { setter: function (value) { if (modes.extended & modes.HINTS) hints._showHints(); return value; }, completer: function (context) [ ["0123456789", "Numbers only"], ["hjklasdf", "Home row"], ["hjklasdfgyuiopqwertnmzxcvb", "Smart order"], ["abcdefghijklmnopqrstuvwxyz", "Alphabetically ordered"], ], validator: function (arg) { let prev; let list = arg.split(""); list.sort(); let ret = list.some(function (n) prev == (prev=n)); return !ret && arg.length > 1; } }); options.add(["wordseparators", "wsp"], "How words are split for hintmatching", "string", '[.,!?:;/"^$%&?()[\\]{}<>#*+|=~ _-]'); options.add(["hintinputs", "hin"], "How text input fields are hinted", "stringlist", "label,value", { completer: function (context) [ ["value", "Match against the value contained by the input field"], ["label", "Match against the value of a label for the input field, if one can be found"], ["name", "Match against the name of an input field, only if neither a name or value could be found."] ] }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2010 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * @param {String} name * @param {String} description * @param {String|TemplateXML} node * String : the id attribute value of the existing node * TemplateXML: a TemplateXML instance. e.g) xml`<xul:label ...>` * @param {Function} updater * @param {Object} extraInfo */ const StatusField = Class("StatusField", { init: function (name, description, node, updater, extraInfo) { this.name = name; this.description = description; if (typeof updater === "function") this._updater = updater; if (typeof node === "string") { this.node = document.getElementById(node); if (!this.node) throw new Error('the element is not found: "' + node + '"'); } else if (node instanceof TemplateXML) { this.node = util.xmlToDom(node, document); this.node.setAttribute("id", "liberator-status-" + name); statusline._statuslineWidget.appendChild(this.node); } else throw new TypeError("the argument node must be String or TemplateXML: " + node); this.node.hidden = true; if (extraInfo) update(this, extraInfo); }, /** * field position starting 0. * if set -1, this field will be hidden. * @type {Number} */ get position () { if (this.node.hasAttribute("liberatorPosition")) return parseInt(this.node.getAttribute("libeatorPosition"), 10); this.node.setAttribute("liberatorPosition", -1); return -1; }, set position (val) { if (typeof val !== "number") return false; this.node.hidden = (val === -1); this.node.setAttribute("liberatorPosition", val); return true; }, update: function (value) { if (this._updater) this._updater(this.node, value); }, desctroy: function () { this.node.parentNode.removeChild(this.node); }, }); const StatusLine = Module("statusline", { init: function () { // our status bar fields this._statusfields = {}; this._statuslineWidget = document.getElementById("liberator-status"); }, /** * @see StatusField */ addField: function (name, description, node, updater, extraInfo) { if (name in this._statusfields) return this._statusfields[name]; try { var field = new StatusField(name, description, node, updater, extraInfo); Object.defineProperty(this, name, { value: field, configurable: true, enumerable: true }); } catch (e) { Cu.reportError(e); return null; } return this._statusfields[name] = field; }, removeField: function (name) { if (name in this._statusfields) { this._statusfields[name].destroy(); return delete this._statusfields[name] && delete this[name]; } return false; }, sortFields: function (fieldNames) { if (!fieldNames) fieldNames = options.get("status").values; for (var name of Object.keys(this._statusfields)) this._statusfields[name].position = fieldNames.indexOf(name); Cc["@mozilla.org/xul/xul-sort-service;1"] .getService(Ci.nsIXULSortService) .sort(this._statuslineWidget, "liberatorPosition", "integer ascending"); }, // update all fields of the statusline update: function update() { let statusfields = this._statusfields; let fieldNames = options.get("status").values; this.sortFields(fieldNames); for (let field of fieldNames) { if (field in statusfields) statusfields[field].update(); } }, /** * Set any field in the statusbar * * @param {String} fieldname * @param {any} value */ updateField: function updateField (fieldname, value) { var field = this._statusfields[fieldname]; if (field) field.update(value); }, }, { }, { statusline: function () { statusline.addField("input", "Any partially entered key mapping", "liberator-status-input", /** * Set the contents of the status line's input buffer to the given * string. Used primarily when a key press requires further input * before being processed, including mapping counts and arguments, * along with multi-key mappings. * * @param {Element} node * @param {string} buffer */ function updateInputBuffer (node, buffer) { if (!buffer || typeof buffer != "string") buffer = ""; node.value = buffer; }); statusline.addField("ssl", "The currently SSL status", "liberator-status-ssl", function updateSSLState (node, state) { var className = ""; if (!state) { let securityUI = config.tabbrowser.securityUI; if (securityUI) state = securityUI.state || 0; } const WPL = Components.interfaces.nsIWebProgressListener; if (state & WPL.STATE_IDENTITY_EV_TOPLEVEL) className = "verifiedIdentity"; else if (state & WPL.STATE_IS_SECURE) className = "verifiedDomain"; else if (state & WPL.STATE_IS_BROKEN) { if ((state & WPL.STATE_LOADED_MIXED_ACTIVE_CONTENT) && options.getPref("security.mixed_content.block_active_content", false)) className = "mixedActiveContent"; } node.className = className; }, { openPopup: function (anchor) { var handler = window.gIdentityHandler; if (typeof handler === "undefiend") // Thunderbird has none return; handler._identityPopup.hidden = false; handler.setPopupMessages(handler._identityBox.className); handler._identityPopup.openPopup(anchor); }, }); statusline.addField("location", "The currently loaded URL", "liberator-status-location", /** * Update the URL displayed in the status line * * @param {Element} node * @param {string} url The URL to display. * @default buffer.URL */ function updateUrl (node, url) { if (typeof(buffer) == "undefined") // quick hack to make the muttator compose work, needs more thought return; if (url == null) // TODO: this probably needs a more general solution. url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL); // make it even more Vim-like if (url == "about:blank") { if (!buffer.title) url = "[No Name]"; } else { url = url.replace(RegExp("^liberator://help/(\\S+)#(.*)"), function (m, n1, n2) n1 + " " + decodeURIComponent(n2) + " [Help]") .replace(RegExp("^liberator://help/(\\S+)"), "$1 [Help]"); } node.value = url; }); statusline.addField("history", "The backward / forward history indicators", "liberator-status-history", function updateHistory (node) { let history = ""; if (window.getWebNavigation) { let sh = window.getWebNavigation().sessionHistory; if (sh && sh.index > 0) history += "<"; if (sh && sh.index < sh.count - 1) history += ">"; } node.value = history; }); statusline.addField("bookmark", "The bookmark indicator (heart)", "liberator-status-bookmark", function updateBookmark (node, url) { if (typeof(buffer) == "undefined") // quick hack to make the muttator compose work, needs more thought return; // if no url is given as the argument, use the current page if (url == null) url = buffer.URL; let bookmark = ""; if ((modules.bookmarks) && (bookmarks.isBookmarked(url))) bookmark = "\u2764"; node.value = bookmark; }); statusline.addField("tabcount", "The number of currently selected tab and total number of tabs", "liberator-status-tabcount", /** * Display the correct tabcount (e.g., [1/5]) on the status bar. * * @param {Element} node * @param {bool} delayed When true, update count after a * brief timeout. Useful in the many cases when an * event that triggers an update is broadcast before * the tab state is fully updated. */ function updateTabCount (node, delayed) { if (liberator.has("tabs")) { if (delayed) { window.setTimeout(function() updateTabCount(node, false), 0); return; } node.value = "[" + (tabs.index() + 1) + "/" + tabs.count + "]"; } }); statusline.addField("position", "The vertical scroll position", "liberator-status-position", /** * Display the main content's vertical scroll position in the status * bar. * * @param {Element} node * @param {number} percent The position, as a percentage. @optional */ function updateBufferPosition (node, percent) { if (!percent || typeof percent != "number") { let win = document.commandDispatcher.focusedWindow; if (!win) return; percent = win.scrollMaxY == 0 ? -1 : win.scrollY / win.scrollMaxY; } let bufferPositionStr = ""; percent = Math.round(percent * 100); if (percent < 0) bufferPositionStr = "All"; else if (percent == 0) bufferPositionStr = "Top"; else if (percent < 10) bufferPositionStr = " " + percent + "%"; else if (percent >= 100) bufferPositionStr = "Bot"; else bufferPositionStr = percent + "%"; node.value = bufferPositionStr; }); }, options: function () { options.add(["status"], "Define which information to show in the status bar", "stringlist", "input,location,bookmark,history,tabcount,position", { setter: function setter(value) { statusline.sortFields(this.values); return value; }, completer: function completer(context) { var fields = statusline._statusfields; return [[name, fields[name].description] for (name of Object.keys(fields))]; }, }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ // Do NOT create instances of this class yourself, use the helper method // commands.add() instead /** * A class representing Ex commands. Instances are created by * the {@link Command} class. * * @param {string[]} specs The names by which this command can be invoked. * These are specified in the form "com[mand]" where "com" is a unique * command name prefix. * @param {string} description A short one line description of the command. * @param {function} action The action invoked by this command when executed. * @param {Object} extraInfo An optional extra configuration hash. The * following properties are supported. * argCount - see {@link Command#argCount} * bang - see {@link Command#bang} * completer - see {@link Command#completer} * count - see {@link Command#count} * heredoc - see {@link Command#heredoc} * literal - see {@link Command#literal} * options - see {@link Command#options} * serial - see {@link Command#serial} * privateData - see {@link Command#privateData} * @optional * @private */ const Command = Class("Command", { requires: ["config"], init: function (specs, description, action, extraInfo) { specs = Array.concat(specs); // XXX let parsedSpecs = Command.parseSpecs(specs); if (!parsedSpecs.every(function (specs) specs.every(Command.validateName))) throw Error("Invalid command name"); this.specs = specs; this.shortNames = parsedSpecs.reduce(function(r,c){c[1]&&r.push(c[1]);return r;}, []); this.longNames = parsedSpecs.map(function (n) n[0]); this.name = this.longNames[0]; this.names = parsedSpecs.reduce(function(r,c) r.concat(c), []); this.description = description; this.action = action; if (extraInfo) update(this, extraInfo); }, /** * Execute this command. * * @param {string} args The args to be parsed and passed to * {@link #action}. * @param {boolean} bang Whether this command was executed with a trailing * bang. * @deprecated * @param {number} count Whether this command was executed with a leading * count. * @deprecated * @param {Object} modifiers Any modifiers to be passed to {@link #action}. */ execute: function (args, bang, count, modifiers) { // XXX bang = !!bang; count = (count === undefined) ? null : count; modifiers = modifiers || {}; let cmd = this; function exec(args) { // FIXME: Move to parseCommand? args = cmd.parseArgs(args, null, { count: count, bang: bang }); if (!args) return; if (args.subCmd) cmd = args.subCmd; liberator.trapErrors(cmd.action, cmd, args, modifiers); } if (this.hereDoc) { let matches = args.match(/(.*)<<\s*(\S+)$/); if (matches && matches[2]) { commandline.inputMultiline(RegExp("^" + matches[2] + "$", "m"), function (args) { exec(matches[1] + "\n" + args); }); return; } } exec(args); }, /** * Returns whether this command may be invoked via <b>name</b>. * * @param {string} name The candidate name. * @returns {boolean} */ hasName: function (name) { for (let spec of this.specs) { let fullName = spec.replace(/\[(\w+)]$/, "$1"); let index = spec.indexOf("["); let min = index == -1 ? fullName.length : index; if (fullName.startsWith(name) && name.length >= min) return true; } return false; }, /** * A helper function to parse an argument string. * * @param {string} args The argument string to parse. * @param {CompletionContext} complete A completion context. * Non-null when the arguments are being parsed for completion * purposes. * @param {Object} extra Extra keys to be spliced into the * returned Args object. * @returns {Args} * @see Commands#parseArgs */ parseArgs: function (args, complete, extra) commands.parseArgs(args, this.options, this.subCommands, this.argCount, false, this.literal, complete, extra), /** * @property {string[]} All of this command's name specs. e.g., "com[mand]" */ specs: null, /** @property {string[]} All of this command's short names, e.g., "com" */ shortNames: null, /** * @property {string[]} All of this command's long names, e.g., "command" */ longNames: null, /** @property {string} The command's canonical name. */ name: null, /** @property {string[]} All of this command's long and short names. */ names: null, /** @property {string} This command's description, as shown in :usage */ description: "", /** * @property {function (Args)} The function called to execute this command. */ action: null, /** * @property {string} This command's argument count spec. * @see Commands#parseArguments */ argCount: 0, /** * @property {function (CompletionContext, Args)} This command's completer. * @see CompletionContext */ completer: null, /** @property {boolean} Whether this command accepts a here document. */ hereDoc: false, /** * @property {Array} The options this command takes. * @see Commands@parseArguments */ options: [], /** * @property {Array} The sub-commands this command takes. */ subCommands: [], /** * @property {boolean} Whether this command may be called with a bang, * e.g., :com! */ bang: false, /** * @property {boolean} Whether this command may be called with a count, * e.g., :12bdel */ count: false, /** * @property {boolean} At what index this command's literal arguments * begin. For instance, with a value of 2, all arguments starting with * the third are parsed as a single string, with all quoting characters * passed literally. This is especially useful for commands which take * key mappings or Ex command lines as arguments. */ literal: null, /** * @property {function} Should return an array of <b>Object</b>s suitable * to be passed to {@link Commands#commandToString}, one for each past * invocation which should be restored on subsequent @liberator * startups. */ serial: null, /** * @property {boolean} When true, invocations of this command * may contain private data which should be purged from * saved histories when clearing private data. */ privateData: false, /** * @property {boolean} Specifies whether this is a user command. User * commands may be created by plugins, or directly by users, and, * unlike basic commands, may be overwritten. Users and plugin authors * should create only user commands. */ user: false, /** * @property {string} For commands defined via :command, contains the Ex * command line to be executed upon invocation. */ replacementText: null }, { // TODO: do we really need more than longNames as a convenience anyway? /** * Converts command name abbreviation specs of the form * 'shortname[optional-tail]' to short and long versions: * ["abc[def]", "ghijkl"] -> [["abcdef", "abc"], ["ghijlk"]] * * @param {Array} specs An array of command name specs to parse. * @returns {Array} */ parseSpecs: function parseSpecs(specs) { return specs.map(function (spec) { let [, head, tail] = spec.match(/([^[]+)(?:\[(.*)])?/); return tail ? [head + tail, head] : [head]; }); }, /** * Validate command name * * @param {string} command name * @returns {boolean} */ validateName: function (name) { return /^(!|[a-zA-Z][a-zA-Z\d]*)$/.test(name); } }); /** * @instance commands */ const ArgType = Struct("description", "parse"); const Commands = Module("commands", { init: function () { this._exCommands = []; }, // FIXME: remove later, when our option handler is better /** * @property {number} The option argument is unspecified. Any argument * is accepted and caller is responsible for parsing the return * value. * @final */ OPTION_ANY: 0, /** * @property {number} The option doesn't accept an argument. * @final */ OPTION_NOARG: 1, /** * @property {number} The option accepts a boolean argument. * @final */ OPTION_BOOL: 2, /** * @property {number} The option accepts a string argument. * @final */ OPTION_STRING: 3, /** * @property {number} The option accepts an integer argument. * @final */ OPTION_INT: 4, /** * @property {number} The option accepts a float argument. * @final */ OPTION_FLOAT: 5, /** * @property {number} The option accepts a string list argument. * E.g. "foo,bar" * @final */ OPTION_LIST: 6, /** * @property Indicates that no count was specified for this * command invocation. * @final */ COUNT_NONE: null, /** * @property {number} Indicates that the full buffer range (1,$) was * specified for this command invocation. * @final */ // FIXME: this isn't a count at all COUNT_ALL: -2, // :%... /** @property {Iterator(Command)} @private */ __iterator__: function () { let sorted = this._exCommands.sort(function (a, b) a.name > b.name); return util.Array.itervalues(sorted); }, /** @property {string} The last executed Ex command line. */ repeat: null, _addCommand: function (command, replace) { if (this._exCommands.some(function (c) c.hasName(command.name))) { if (command.user && replace) commands.removeUserCommand(command.name); else { liberator.echomsg("Command '" + command.name + "' already exists, NOT replacing existing command. Use ! to override."); return false; } } this._exCommands.push(command); return command; }, /** * Adds a new default command. * * @param {string[]} names The names by which this command can be * invoked. The first name specified is the command's canonical * name. * @param {string} description A description of the command. * @param {function} action The action invoked by this command. * @param {Object} extra An optional extra configuration hash. * @optional * @returns {Command} */ add: function (names, description, action, extra) { return this._addCommand(Command(names, description, action, extra), false); }, /** * Adds a new user-defined command. * * @param {string[]} names The names by which this command can be * invoked. The first name specified is the command's canonical * name. * @param {string} description A description of the command. * @param {function} action The action invoked by this command. * @param {Object} extra An optional extra configuration hash. * @param {boolean} replace Overwrite an existing command with the same * canonical name. * @returns {Command} */ addUserCommand: function (names, description, action, extra, replace) { extra = extra || {}; extra.user = true; description = description || "User defined command"; return this._addCommand(Command(names, description, action, extra), replace); }, /** * Returns the specified command invocation object serialized to * an executable Ex command string. * * @param {Object} args The command invocation object. * @returns {string} */ commandToString: function (args) { let res = [args.command + (args.bang ? "!" : "")]; function quote(str) Commands.quoteArg[/[\s"'\\]|^$/.test(str) ? '"' : ""](str); for (let [opt, val] in Iterator(args.options || {})) { let chr = /^-.$/.test(opt) ? " " : "="; if (val != null) opt += chr + quote(val); res.push(opt); } for (let [, arg] in Iterator(args.arguments || [])) res.push(quote(arg)); let str = args.literalArg; if (str) res.push(/\n/.test(str) ? "<<EOF\n" + str.replace(/\n$/, "") + "\nEOF" : str); return res.join(" "); }, /** * Returns the command with matching <b>name</b>. * * @param {string} name The name of the command to return. This can be * any of the command's names. * @returns {Command} */ get: function (name) { return this._exCommands.filter(function (cmd) cmd.hasName(name))[0] || null; }, /** * Returns the user-defined command with matching <b>name</b>. * * @param {string} name The name of the command to return. This can be * any of the command's names. * @returns {Command} */ getUserCommand: function (name) { return this._exCommands.filter(function (cmd) cmd.user && cmd.hasName(name))[0] || null; }, /** * Returns all user-defined commands. * * @returns {Command[]} */ getUserCommands: function () { return this._exCommands.filter(function (cmd) cmd.user); }, // TODO: should it handle comments? // : it might be nice to be able to specify that certain quoting // should be disabled E.g. backslash without having to resort to // using literal etc. // : error messages should be configurable or else we can ditch // Vim compatibility but it actually gives useful messages // sometimes rather than just "Invalid arg" // : I'm not sure documenting the returned object here, and // elsewhere, as type Args rather than simply Object makes sense, // especially since it is further augmented for use in // Command#action etc. /** * Parses <b>str</b> for options and plain arguments. * * The returned <b>Args</b> object is an augmented array of arguments. * Any key/value pairs of <b>extra</b> will be available and the * following additional properties: * -opt - the value of the option -opt if specified * string - the original argument string <b>str</b> * literalArg - any trailing literal argument * * Quoting rules: * '-quoted strings - only ' and \ itself are escaped * "-quoted strings - also ", \n and \t are translated * non-quoted strings - everything is taken literally apart from "\ * " and "\\" * * @param {string} str The Ex command-line string to parse. E.g. * "-x=foo -opt=bar arg1 arg2" * @param {Array} options The options accepted. These are specified as * an array [names, type, validator, completions, multiple]. * names - an array of option names. The first name is the * canonical option name. * type - the option's value type. This is one of: * (@link Commands#OPTION_NOARG), * (@link Commands#OPTION_STRING), * (@link Commands#OPTION_BOOL), * (@link Commands#OPTION_INT), * (@link Commands#OPTION_FLOAT), * (@link Commands#OPTION_LIST), * (@link Commands#OPTION_ANY) * validator - a validator function * completer - a list of completions, or a completion function * multiple - whether this option can be specified multiple times * E.g. * options = [[["-force"], OPTION_NOARG], * [["-fullscreen", "-f"], OPTION_BOOL], * [["-language"], OPTION_STRING, validateFunc, ["perl", "ruby"]], * [["-speed"], OPTION_INT], * [["-acceleration"], OPTION_FLOAT], * [["-accessories"], OPTION_LIST, null, ["foo", "bar"], true], * [["-other"], OPTION_ANY]]; * @param {Array} subCommands The sub-commands accepted. These are Command instance * see @link Command * @param {string} argCount The number of arguments accepted. * "0": no arguments * "1": exactly one argument * "+": one or more arguments * "*": zero or more arguments (default if unspecified) * "?": zero or one arguments * @param {boolean} allowUnknownOptions Whether unspecified options * should cause an error. * @param {number} literal The index at which any literal arg begins. * See {@link Command#literal}. * @param {CompletionContext} complete The relevant completion context * when the args are being parsed for completion. * @param {Object} extra Extra keys to be spliced into the returned * Args object. * @returns {Args} */ parseArgs: function (str, options, subCommands, argCount, allowUnknownOptions, literal, complete, extra) { function getNextArg(str) { let [count, arg, quote] = Commands.parseArg(str); if (quote == "\\" && !complete) return [,,,"Trailing \\"]; if (quote && !complete) return [,,,"Missing quote: " + quote]; return [count, arg, quote]; } if (!options) options = []; if (!subCommands) subCommands = []; if (!argCount) argCount = "*"; if (!extra) extra = {}; var args = []; // parsed options args.__iterator__ = function () util.Array.iteritems(this); args.string = str; // for access to the unparsed string args.literalArg = ""; var argPosition = []; // argument's starting position // FIXME! for (let [k, v] in Iterator(extra)) { switch (k) { case "count": case "bang": case "subCmd": args[k] = v; break; case "opts": for (let [optKey, optValue] in Iterator(v)) args[optKey] = optValue; break; } } var invalid = false; // FIXME: best way to specify these requirements? var onlyArgumentsRemaining = allowUnknownOptions || (options.length == 0 && subCommands.length == 0) || false; // after a -- has been found var arg = null; var count = 0; // the length of the argument var i = 0; var completeOpts; // XXX function matchOpts(arg) { // Push possible option matches into completions if (complete && !onlyArgumentsRemaining) completeOpts = [[opt[0], opt[0][0]] for (opt of options) if (!(opt[0][0] in args))]; } function resetCompletions() { completeOpts = null; args.completeArg = null; args.completeOpt = null; args.completeFilter = null; args.completeStart = i; args.quote = Commands.complQuote[""]; } if (complete) { resetCompletions(); matchOpts(""); args.completeArg = 0; } function echoerr(error) { if (complete) complete.message = error; else liberator.echoerr(error); } outer: while (i < str.length || complete) { // skip whitespace while (/\s/.test(str[i]) && i < str.length) i++; if (i == str.length && !complete) break; if (complete) resetCompletions(); var sub = str.substr(i); if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub)) { onlyArgumentsRemaining = true; i += 2; continue; } var optname = ""; if (!onlyArgumentsRemaining) { for (let opt of options) { for (let optname of opt[0]) { if (sub.startsWith(optname)) { invalid = false; arg = null; quote = null; count = 0; let sep = sub[optname.length]; if (sep == "=" || /\s/.test(sep) && opt[1] != this.OPTION_NOARG) { [count, arg, quote, error] = getNextArg(sub.substr(optname.length + 1)); liberator.assert(!error, error); // if we add the argument to an option after a space, it MUST not be empty if (sep != "=" && !quote && arg.length == 0) arg = null; count++; // to compensate the "=" character } else if (!/\s/.test(sep) && sep != undefined) // this isn't really an option as it has trailing characters, parse it as an argument invalid = true; let context = null; if (!complete && quote) { liberator.echoerr("Invalid argument for option: " + optname); return null; } if (!invalid) { if (complete && count > 0) { args.completeStart += optname.length + 1; args.completeOpt = opt; args.completeFilter = arg; args.quote = Commands.complQuote[quote] || Commands.complQuote[""]; } let type = Commands.argTypes[opt[1]]; if (type && (!complete || arg != null)) { let orig = arg; arg = type.parse(arg); if (arg == null || (typeof arg == "number" && isNaN(arg))) { if (!complete || orig != "" || args.completeStart != str.length) echoerr("Invalid argument for " + type.description + " option: " + optname); if (complete) complete.highlight(args.completeStart, count - 1, "SPELLCHECK"); else return null; } } // we have a validator function if (typeof opt[2] == "function") { if (opt[2].call(this, arg) == false) { echoerr("Invalid argument for option: " + optname); if (complete) complete.highlight(args.completeStart, count - 1, "SPELLCHECK"); else return null; } } // option allowed multiple times if (!!opt[4]) args[opt[0][0]] = (args[opt[0][0]] || []).concat(arg); else args[opt[0][0]] = opt[1] == this.OPTION_NOARG || arg; i += optname.length + count; if (i == str.length) break outer; continue outer; } // if it is invalid, just fall through and try the next argument } } } } matchOpts(sub); if (complete) { if (argCount == "0" || args.length > 0 && (/[1?]/.test(argCount))) complete.highlight(i, sub.length, "SPELLCHECK"); } if (args.length == literal) { if (complete) args.completeArg = args.length; args.literalArg = sub; args.push(sub); args.quote = null; argPosition.push(i); break; } // if not an option, treat this token as an argument let [count, arg, quote, error] = getNextArg(sub); liberator.assert(!error, error); if (complete) { args.quote = Commands.complQuote[quote] || Commands.complQuote[""]; args.completeFilter = arg || ""; } else if (count == -1) { liberator.echoerr("Error parsing arguments: " + arg); return null; } // if /^\s*-/ is NOT TRUE, "-" be quoted. else if (!onlyArgumentsRemaining && /^-/.test(arg) && /^\s*-/.test(sub)) { liberator.echoerr("Invalid option: " + arg); return null; } else if (!onlyArgumentsRemaining) { let [cmdCount, cmdName, cmdBang, cmdArg] = commands.parseCommand(sub); if (cmdName) { for (let subCmd of subCommands) { if (subCmd.hasName(cmdName)) { let subExtra = { count: cmdCount, bang: cmdBang, subCmd: subCmd, opts: extra.opts || {} }; for (let opt of options) { if (opt[0][0] in args) subExtra.opts[opt[0][0]] = args[opt[0][0]]; } // delegate parsing to the sub-command return subCmd.parseArgs(sub.substr(count), null, subExtra); } } } } if (arg != null) { args.push(arg); argPosition.push(i); } if (complete) args.completeArg = args.length - 1; i += count; if (count <= 0 || i == str.length) break; } if (complete) { if (subCommands.length && !args.completeOpt) { complete.fork("subCmds", argPosition[0], completion, "ex", subCommands); // don't any more if sub-command arguments are completing if (complete.contexts[complete.name + "/subCmds/args"]) return; } if (args.completeOpt) { let opt = args.completeOpt; let context = complete.fork(opt[0][0], args.completeStart); context.filter = args.completeFilter; if (typeof opt[3] == "function") var compl = opt[3](context, args); else { if (opt[1] === commands.OPTION_LIST) { let [, prefix] = context.filter.match(/^(.*,)[^,]*$/) || []; if (prefix) context.advance(prefix.length); } compl = opt[3] || []; } context.title = [opt[0][0]]; context.quote = args.quote; context.completions = compl; } complete.advance(args.completeStart); complete.title = ["Options"]; if (completeOpts) complete.completions = completeOpts; } // check for correct number of arguments if (args.length == 0 && /^[1+]$/.test(argCount) || literal != null && /[1+]/.test(argCount) && !/\S/.test(args.literalArg || "")) { if (!complete) { liberator.echoerr("Argument required"); return null; } } else if (args.length == 1 && (argCount == "0") || args.length > 1 && /^[01?]$/.test(argCount)) { echoerr("Trailing characters"); return null; } return args; }, /** * Parses a complete Ex command. * * The parsed string is returned as an Array like * [count, command, bang, args]: * count - any count specified * command - the Ex command name * bang - whether the special "bang" version was called * args - the commands full argument string * E.g. ":2foo! bar" -> [2, "foo", true, "bar"] * * @param {string} str The Ex command line string. * @returns {Array} */ // FIXME: why does this return an Array rather than Object? parseCommand: function (str) { // remove comments str.replace(/\s*".*$/, ""); // 0 - count, 1 - cmd, 2 - special, 3 - args let matches = str.match(/^[:\s]*(\d+|%)?([a-zA-Z][a-zA-Z\d]*|!)(!)?(?:\s*(.*?))?$/); //var matches = str.match(/^:*(\d+|%)?([a-zA-Z]+|!)(!)?(?:\s*(.*?)\s*)?$/); if (!matches) return [null, null, null, null]; let [, count, cmd, special, args] = matches; // parse count if (count) count = count == "%" ? this.COUNT_ALL : parseInt(count, 10); else count = this.COUNT_NONE; return [count, cmd, !!special, args || ""]; }, /** @property */ get complQuote() Commands.complQuote, /** @property */ get quoteArg() Commands.quoteArg, // XXX: better somewhere else? /** * Remove the user-defined command with matching <b>name</b>. * * @param {string} name The name of the command to remove. This can be * any of the command's names. */ removeUserCommand: function (name) { this._exCommands = this._exCommands.filter(function (cmd) !(cmd.user && cmd.hasName(name))); }, // FIXME: still belong here? Also used for autocommand parameters. /** * Returns a string with all tokens in <b>string</b> matching "<key>" * replaced with "value". Where "key" is a property of the specified * <b>tokens</b> object and "value" is the corresponding value. The * <lt> token can be used to include a literal "<" in the returned * string. Any tokens prefixed with "q-" will be quoted except for * <q-lt> which is treated like <lt>. * * @param {string} str The string with tokens to replace. * @param {Object} tokens A map object whose keys are replaced with its * values. * @returns {string} */ replaceTokens: function replaceTokens(str, tokens) { return str.replace(/<((?:q-)?)([a-zA-Z]+)?>/g, function (match, quote, token) { if (token == "lt") // Don't quote, as in Vim (but, why so in Vim? You'd think people wouldn't say <q-lt> if they didn't want it) return "<"; let res = tokens[token]; if (res == undefined) // Ignore anything undefined res = "<" + token + ">"; if (quote && typeof res != "number") return Commands.quoteArg['"'](res); return res; }); } }, { QUOTE_STYLE: "rc-ish", // returns [count, parsed_argument] parseArg: function (str) { let arg = ""; let quote = null; let len = str.length; while (str.length && !/^\s/.test(str)) { let res; switch (Commands.QUOTE_STYLE) { case "vim-sucks": if (res = str.match(/^()((?:[^\\\s]|\\.)+)((?:\\$)?)/)) arg += res[2].replace(/\\(.)/g, "$1"); break; case "vimperator": if ((res = str.match(/^()((?:[^\\\s"']|\\.)+)((?:\\$)?)/))) arg += res[2].replace(/\\(.)/g, "$1"); else if ((res = str.match(/^(")((?:[^\\"]|\\.)*)("?)/))) arg += eval(res[0] + (res[3] ? "" : '"')); else if ((res = str.match(/^(')((?:[^\\']|\\.)*)('?)/))) arg += res[2].replace(/\\(.)/g, function (n0, n1) /[\\']/.test(n1) ? n1 : n0); break; case "rc-ish": if ((res = str.match(/^()((?:[^\\\s"']|\\.)+)((?:\\$)?)/))) arg += res[2].replace(/\\(.)/g, "$1"); else if ((res = str.match(/^(")((?:[^\\"]|\\.)*)("?)/))) arg += eval(res[0] + (res[3] ? "" : '"')); else if ((res = str.match(/^(')((?:[^']|'')*)('?)/))) arg += res[2].replace("''", "'", "g"); break; case "pythonesque": if ((res = str.match(/^()((?:[^\\\s"']|\\.)+)((?:\\$)?)/))) arg += res[2].replace(/\\(.)/g, "$1"); else if ((res = str.match(/^(""")((?:.?.?[^"])*)((?:""")?)/))) arg += res[2]; else if ((res = str.match(/^(")((?:[^\\"]|\\.)*)("?)/))) arg += eval(res[0] + (res[3] ? "" : '"')); else if ((res = str.match(/^(')((?:[^\\']|\\.)*)('?)/))) arg += res[2].replace(/\\(.)/g, function (n0, n1) /[\\']/.test(n1) ? n1 : n0); break; } if (!res) break; if (!res[3]) quote = res[1]; if (!res[1]) quote = res[3]; str = str.substr(res[0].length); } return [len - str.length, arg, quote]; } }, { mappings: function () { mappings.add(config.browserModes, ["@:"], "Repeat the last Ex command", function (count) { if (commands.repeat) { for (let i in util.interruptibleRange(0, Math.max(count, 1), 100)) liberator.execute(commands.repeat); } else liberator.echoerr("No previous command line"); }, { count: true }); }, completion: function () { JavaScript.setCompleter(this.get, [function () ([c.name, c.description] for (c in commands))]); completion.command = function command(context, subCmds) { context.keys = { text: "longNames", description: "description" }; if (subCmds) { context.title = ["Sub command"]; context.completions = subCmds; } else { context.title = ["Command"]; context.completions = [k for (k in commands)]; } }; // provides completions for ex commands, including their arguments completion.ex = function ex(context, subCmds) { // if there is no space between the command name and the cursor // then get completions of the command name let [count, cmd, bang, args] = commands.parseCommand(context.filter); let [, prefix, junk] = context.filter.match(/^(:*\d*)\w*(.?)/) || []; context.advance(prefix.length); if (!junk) { completion.command(context, subCmds); return; } // highlight non-existent commands let command = Commands.prototype.get.call(subCmds ? {_exCommands: subCmds} : commands, cmd); if (!command) { if (!subCmds) context.highlight(0, cmd ? cmd.length : context.filter.length, "SPELLCHECK"); return; } // dynamically get completions as specified with the command's completer function [prefix] = context.filter.match(/^(?:\w*[\s!]|!)\s*/); let cmdContext = context.fork(cmd, prefix.length); let argContext = context.fork("args", prefix.length); args = command.parseArgs(cmdContext.filter, argContext, { count: count, bang: bang }); if (args) { // FIXME: Move to parseCommand args.count = count; args.bang = bang; if (!args.completeOpt && command.completer) { cmdContext.advance(args.completeStart); cmdContext.quote = args.quote; cmdContext.filter = args.completeFilter; try { let compObject = command.completer.call(command, cmdContext, args); if (compObject instanceof Array) // for now at least, let completion functions return arrays instead of objects compObject = { start: compObject[0], items: compObject[1] }; if (compObject != null) { cmdContext.advance(compObject.start); cmdContext.filterFunc = null; cmdContext.completions = compObject.items; } } catch (e) { liberator.echoerr(e); } } } }; completion.userCommand = function userCommand(context) { context.title = ["User Command", "Definition"]; context.completions = [ [command.name, command.replacementText || "function () { ... }"] for (command of commands.getUserCommands()) ]; }; }, commands: function () { function userCommand(args, modifiers) { let tokens = { args: this.argCount && args.string, bang: this.bang && args.bang ? "!" : "", count: this.count && args.count }; liberator.execute(commands.replaceTokens(this.replacementText, tokens)); } // TODO: offer completion.ex? // : make this config specific var completeOptionMap = { abbreviation: "abbreviation", altstyle: "alternateStyleSheet", bookmark: "bookmark", buffer: "buffer", color: "colorScheme", command: "command", dialog: "dialog", dir: "directory", environment: "environment", event: "autocmdEvent", file: "file", help: "help", highlight: "highlightGroup", history: "history", javascript: "javascript", macro: "macro", mapping: "userMapping", menu: "menuItem", option: "option", preference: "preference", search: "search", shellcmd: "shellCommand", sidebar: "sidebar", url: "url", usercommand: "userCommand" }; // TODO: Vim allows commands to be defined without {rep} if there are {attr}s // specified - useful? commands.add(["com[mand]"], "List and define commands", function (args) { let cmd = args[0]; liberator.assert(Command.validateName(cmd), "Invalid command name: " + cmd); if (args.literalArg) { let nargsOpt = args["-nargs"] || "0"; let bangOpt = "-bang" in args; let countOpt = "-count" in args; let descriptionOpt = args["-description"] || "User-defined command"; let completeOpt = args["-complete"]; let completeFunc = null; // default to no completion for user commands if (completeOpt) { if (/^custom,/.test(completeOpt)) { completeOpt = completeOpt.substr(7); completeFunc = function () { try { var completer = liberator.eval(completeOpt); if (!(completer instanceof Function)) throw new TypeError("User-defined custom completer " + completeOpt.quote() + " is not a function"); } catch (e) { liberator.echoerr("Unknown function: " + completeOpt); return undefined; } return completer.apply(this, Array.slice(arguments)); }; } else completeFunc = function (context) completion[completeOptionMap[completeOpt]](context); } let added = commands.addUserCommand([cmd], descriptionOpt, userCommand, { argCount: nargsOpt, bang: bangOpt, count: countOpt, completer: completeFunc, replacementText: args.literalArg }, args.bang); if (!added) liberator.echoerr("Command '" + cmd + "' already exists: Add ! to replace it"); } else { function completerToString(completer) { if (completer) return [k for ([k, v] in Iterator(completeOptionMap)) if (completer == completion[v])][0] || "custom"; else return ""; } // TODO: using an array comprehension here generates flakey results across repeated calls // : perhaps we shouldn't allow options in a list call but just ignore them for now // : No, array comprehensions are fine, generator statements aren't. --Kris let cmds = commands._exCommands.filter(function (c) c.user && (!cmd || c.name.match("^" + cmd))); if (cmds.length > 0) { let str = template.tabular(["", "Name", "Args", "Range", "Complete", "Definition"], ([cmd.bang ? "!" : " ", cmd.name, cmd.argCount, cmd.count ? "0c" : "", completerToString(cmd.completer), cmd.replacementText || "function () { ... }"] for ([, cmd] in Iterator(cmds)))); commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } else liberator.echomsg("No user-defined commands found"); } }, { bang: true, completer: function (context, args) { if (args.completeArg == 0) completion.userCommand(context); else completion.ex(context); }, options: [ [["-nargs"], commands.OPTION_STRING, function (arg) /^[01*?+]$/.test(arg), [["0", "No arguments are allowed (default)"], ["1", "One argument is allowed"], ["*", "Zero or more arguments are allowed"], ["?", "Zero or one argument is allowed"], ["+", "One or more arguments is allowed"]]], [["-bang"], commands.OPTION_NOARG], [["-count"], commands.OPTION_NOARG], [["-description"], commands.OPTION_STRING], [["-complete"], commands.OPTION_STRING, function (arg) arg in completeOptionMap || /custom,\w+/.test(arg), function (context) [[k, ""] for ([k, v] in Iterator(completeOptionMap))]] ], literal: 1, serial: function () [ { command: this.name, bang: true, options: util.Array.toObject( [[v, typeof cmd[k] == "boolean" ? null : cmd[k]] // FIXME: this map is expressed multiple times for ([k, v] in Iterator({ argCount: "-nargs", bang: "-bang", count: "-count", description: "-description" })) // FIXME: add support for default values to parseArgs if (k in cmd && cmd[k] != "0" && cmd[k] != "User-defined command")]), arguments: [cmd.name], literalArg: cmd.replacementText } for ([k, cmd] in Iterator(commands._exCommands)) if (cmd.user && cmd.replacementText) ] }); commands.add(["comc[lear]"], "Delete all user-defined commands", function () { commands.getUserCommands().forEach(function (cmd) { commands.removeUserCommand(cmd.name); }); }, { argCount: "0" }); commands.add(["delc[ommand]"], "Delete the specified user-defined command", function (args) { let name = args[0]; if (commands.get(name)) commands.removeUserCommand(name); else liberator.echoerr("No such user-defined command: " + name); }, { argCount: "1", completer: function (context) completion.userCommand(context) }); } }); (function () { Commands.quoteMap = { "\n": "n", "\t": "t" }; function quote(q, list) { let re = RegExp("[" + list + "]", "g"); return function (str) q + String.replace(str, re, function ($0) $0 in Commands.quoteMap ? Commands.quoteMap[$0] : ("\\" + $0)) + q; }; function vimSingleQuote(s) s.replace(/'/g, "''"); Commands.complQuote = { // FIXME '"': ['"', quote("", '\n\t"\\\\'), '"'], "'": ["'", vimSingleQuote, "'"], "": ["", quote("", "\\\\'\" "), ""] }; Commands.quoteArg = { '"': quote('"', '\n\t"\\\\'), "'": vimSingleQuote, "": quote("", "\\\\'\" ") }; Commands.parseBool = function (arg) { if (/^(true|1|on)$/i.test(arg)) return true; if (/^(false|0|off)$/i.test(arg)) return false; return NaN; }; Commands.argTypes = [ null, ArgType("no arg", function (arg) !arg || null), ArgType("boolean", Commands.parseBool), ArgType("string", function (val) val), ArgType("int", parseInt), ArgType("float", parseFloat), ArgType("list", function (arg) arg && arg.split(/\s*,\s*/)) ]; })(); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Some code based on Venkman // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ plugins.contexts = {}; const Script = Class("Script", { init: function (file) { let self = plugins.contexts[file.path]; if (self) { if (self.onUnload) self.onUnload(); return self; } plugins.contexts[file.path] = this; this.NAME = file.leafName.replace(/\..*/, "").replace(/-([a-z])/g, function (m, n1) n1.toUpperCase()); this.PATH = file.path; this.toString = this.toString; this.__context__ = this; this.__proto__ = plugins; // This belongs elsewhere for (let dir of io.getRuntimeDirectories("plugin")) { if (dir.contains(file, false)) plugins[this.NAME] = this; } return this; } }); /** * @class File A class to wrap nsIFile objects and simplify operations * thereon. * * @param {nsIFile|string} path Expanded according to {@link IO#expandPath} * @param {boolean} checkPWD Whether to allow expansion relative to the * current directory. @default true */ const File = Class("File", { init: function (path, checkPWD) { if (arguments.length < 2) checkPWD = true; let file = services.create("file"); if (path instanceof Ci.nsIFile) file = path; else if (/file:\/\//.test(path)) file = services.create("file:").getFileFromURLSpec(path); else { let expandedPath = File.expandPath(path); if (!File.isAbsolutePath(expandedPath) && checkPWD) file = File.joinPaths(io.getCurrentDirectory().path, expandedPath); else file.initWithPath(expandedPath); } let self = XPCNativeWrapper(file); self.__proto__ = File.prototype; return self; }, /** * Iterates over the objects in this directory. */ iterDirectory: function () { if (!this.isDirectory()) throw Error("Not a directory"); let entries = this.directoryEntries; while (entries.hasMoreElements()) yield File(entries.getNext().QueryInterface(Ci.nsIFile)); }, /** * Returns the list of files in this directory. * * @param {boolean} sort Whether to sort the returned directory * entries. * @returns {nsIFile[]} */ readDirectory: function (sort) { if (!this.isDirectory()) throw Error("Not a directory"); let array = [e for (e in this.iterDirectory())]; if (sort) array.sort(function (a, b) b.isDirectory() - a.isDirectory() || String.localeCompare(a.path, b.path)); return array; }, /** * Reads this file's entire contents in "text" mode and returns the * content as a string. * * @param {string} encoding The encoding from which to decode the file. * @default options["fileencoding"] * @returns {string} */ read: function (encoding) { let ifstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream); let icstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream); if (!encoding) encoding = options["fileencoding"]; ifstream.init(this, -1, 0, 0); icstream.init(ifstream, encoding, 4096, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); // 4096 bytes buffering let buffer = []; let str = {}; while (icstream.readString(4096, str) != 0) buffer.push(str.value); icstream.close(); ifstream.close(); return buffer.join(""); }, /** * Writes the string <b>buf</b> to this file. * * @param {string} buf The file content. * @param {string|number} mode The file access mode, a bitwise OR of * the following flags: * {@link #MODE_RDONLY}: 0x01 * {@link #MODE_WRONLY}: 0x02 * {@link #MODE_RDWR}: 0x04 * {@link #MODE_CREATE}: 0x08 * {@link #MODE_APPEND}: 0x10 * {@link #MODE_TRUNCATE}: 0x20 * {@link #MODE_SYNC}: 0x40 * Alternatively, the following abbreviations may be used: * ">" is equivalent to {@link #MODE_WRONLY} | {@link #MODE_CREATE} | {@link #MODE_TRUNCATE} * ">>" is equivalent to {@link #MODE_WRONLY} | {@link #MODE_CREATE} | {@link #MODE_APPEND} * @default ">" * @param {number} perms The file mode bits of the created file. This * is only used when creating a new file and does not change * permissions if the file exists. * @default 0644 * @param {string} encoding The encoding to used to write the file. * @default options["fileencoding"] */ write: function (buf, mode, perms, encoding) { let ofstream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream); function getStream(defaultChar) { let stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream); stream.init(ofstream, encoding, 0, defaultChar); return stream; } if (!encoding) encoding = options["fileencoding"]; if (mode == ">>") mode = File.MODE_WRONLY | File.MODE_CREATE | File.MODE_APPEND; else if (!mode || mode == ">") mode = File.MODE_WRONLY | File.MODE_CREATE | File.MODE_TRUNCATE; if (!perms) perms = 0644; ofstream.init(this, mode, perms, 0); let ocstream = getStream(0); try { ocstream.writeString(buf); } catch (e) { // liberator.log(e); if (e.result == Cr.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA) { ocstream = getStream("?".charCodeAt(0)); ocstream.writeString(buf); return false; } else throw e; } finally { try { ocstream.close(); } catch (e) {} ofstream.close(); } return true; } }, { /** * @property {number} Open for reading only. * @final */ MODE_RDONLY: 0x01, /** * @property {number} Open for writing only. * @final */ MODE_WRONLY: 0x02, /** * @property {number} Open for reading and writing. * @final */ MODE_RDWR: 0x04, /** * @property {number} If the file does not exist, the file is created. * If the file exists, this flag has no effect. * @final */ MODE_CREATE: 0x08, /** * @property {number} The file pointer is set to the end of the file * prior to each write. * @final */ MODE_APPEND: 0x10, /** * @property {number} If the file exists, its length is truncated to 0. * @final */ MODE_TRUNCATE: 0x20, /** * @property {number} If set, each write will wait for both the file * data and file status to be physically updated. * @final */ MODE_SYNC: 0x40, /** * @property {number} With MODE_CREATE, if the file does not exist, the * file is created. If the file already exists, no action and NULL * is returned. * @final */ MODE_EXCL: 0x80, expandPathList: function (list) list.split(",").map(this.expandPath).join(","), expandPath: function (path, relative) { // expand any $ENV vars - this is naive but so is Vim and we like to be compatible // TODO: Vim does not expand variables set to an empty string (and documents it). // Kris reckons we shouldn't replicate this 'bug'. --djk // TODO: should we be doing this for all paths? function expand(path) path.replace( !liberator.has("Windows") ? /\$(\w+)\b|\${(\w+)}/g : /\$(\w+)\b|\${(\w+)}|%(\w+)%/g, function (m, n1, n2, n3) services.get("environment").get(n1 || n2 || n3) || m ); path = expand(path); // expand ~ // Yuck. if (!relative && RegExp("~(?:$|[/" + util.escapeRegex(IO.PATH_SEP) + "])").test(path)) { // Try $HOME first, on all systems let home = services.get("environment").get("HOME"); // Windows has its own idiosyncratic $HOME variables. if (!home && liberator.has("Windows")) home = services.get("environment").get("USERPROFILE") || services.get("environment").get("HOMEDRIVE") + services.get("environment").get("HOMEPATH"); path = home + path.substr(1); } // TODO: Vim expands paths twice, once before checking for ~, once // after, but doesn't document it. Is this just a bug? --Kris path = expand(path); return path.replace("/", IO.PATH_SEP, "g"); }, getPathsFromPathList: function (list) { if (!list) return []; // empty list item means the current directory return list.replace(/,$/, "").split(",") .map(function (dir) dir == "" ? io.getCurrentDirectory().path : dir); }, replacePathSep: function (path) path.replace("/", IO.PATH_SEP, "g"), joinPaths: function (head, tail) { let path = this(head); try { path.appendRelativePath(this.expandPath(tail, true)); // FIXME: should only expand env vars and normalise path separators // TODO: This code breaks the external editor at least in ubuntu // because /usr/bin/gvim becomes /usr/bin/vim.gnome normalized and for // some strange reason it will start without a gui then (which is not // optimal if you don't start firefox from a terminal ;) // Why do we need this code? // if (path.exists() && path.normalize) // path.normalize(); } catch (e) { return { exists: function () false, __noSuchMethod__: function () { throw e; } }; } return path; }, isAbsolutePath: function (path) { try { services.create("file").initWithPath(path); return true; } catch (e) { return false; } } }); // TODO: why are we passing around strings rather than file objects? /** * Provides a basic interface to common system I/O operations. * @instance io */ const IO = Module("io", { requires: ["config", "services"], init: function () { this._processDir = services.get("dirsvc").get("CurWorkD", Ci.nsIFile); this._cwd = this._processDir; this._oldcwd = null; this._lastRunCommand = ""; // updated whenever the users runs a command with :! this._scriptNames = []; this.downloadListener = { onDownloadStateChange: function (state, download) { if (download.state == services.get("downloads").DOWNLOAD_FINISHED) { let url = download.source.spec; let title = download.displayName; let file = download.targetFile.path; let size = download.size; liberator.echomsg("Download of " + title + " to " + file + " finished"); autocommands.trigger("DownloadPost", { url: url, title: title, file: file, size: size }); } }, onStateChange: function () {}, onProgressChange: function () {}, onSecurityChange: function () {} }; services.get("downloads").addListener(this.downloadListener); }, destroy: function () { services.get("downloads").removeListener(this.downloadListener); for (let [, plugin] in Iterator(plugins.contexts)) if (plugin.onUnload) plugin.onUnload(); }, /** * @property {function} File class. * @final */ File: File, /** * @property {Object} The current file sourcing context. As a file is * being sourced the 'file' and 'line' properties of this context * object are updated appropriately. */ sourcing: null, /** * Expands "~" and environment variables in <b>path</b>. * * "~" is expanded to to the value of $HOME. On Windows if this is not * set then the following are tried in order: * $USERPROFILE * ${HOMDRIVE}$HOMEPATH * * The variable notation is $VAR (terminated by a non-word character) * or ${VAR}. %VAR% is also supported on Windows. * * @param {string} path The unexpanded path string. * @param {boolean} relative Whether the path is relative or absolute. * @returns {string} */ expandPath: File.expandPath, // TODO: there seems to be no way, short of a new component, to change // the process's CWD - see https://bugzilla.mozilla.org/show_bug.cgi?id=280953 /** * Returns the current working directory. * * It's not possible to change the real CWD of the process so this * state is maintained internally. External commands run via * {@link #system} are executed in this directory. * * @returns {nsIFile} */ getCurrentDirectory: function () { let dir = File(this._cwd.path); // NOTE: the directory could have been deleted underneath us so // fallback to the process's CWD if (dir.exists() && dir.isDirectory()) return dir; else return this._processDir; }, /** * Sets the current working directory. * * @param {string} newDir The new CWD. This may be a relative or * absolute path and is expanded by {@link #expandPath}. */ setCurrentDirectory: function (newDir) { newDir = newDir || "~"; if (newDir == "-") { [this._cwd, this._oldcwd] = [this._oldcwd, this.getCurrentDirectory()]; } else { let dir = File(newDir); if (!dir.exists() || !dir.isDirectory()) { liberator.echoerr("Directory does not exist: " + dir.path); return null; } dir.normalize(); [this._cwd, this._oldcwd] = [dir, this.getCurrentDirectory()]; } return this.getCurrentDirectory(); }, /** * Returns all directories named <b>name<b/> in 'runtimepath'. * * @param {string} name * @returns {nsIFile[]) */ getRuntimeDirectories: function (name) { let dirs = File.getPathsFromPathList(options["runtimepath"]); dirs = dirs.map(function (dir) File.joinPaths(dir, name)) .filter(function (dir) dir.exists() && dir.isDirectory() && dir.isReadable()); return dirs; }, /** * Returns the first user RC file found in <b>dir</b>. * * @param {string} dir The directory to search. * @param {boolean} always When true, return a path whether * the file exists or not. * @default $HOME. * @returns {nsIFile} The RC file or null if none is found. */ getRCFile: function (dir, always) { dir = dir || "~"; let rcFile1 = File.joinPaths(dir, "." + config.name.toLowerCase() + "rc"); let rcFile2 = File.joinPaths(dir, "_" + config.name.toLowerCase() + "rc"); if (liberator.has("Windows")) [rcFile1, rcFile2] = [rcFile2, rcFile1]; if (rcFile1.exists() && rcFile1.isFile()) return rcFile1; else if (rcFile2.exists() && rcFile2.isFile()) return rcFile2; else if (always) return rcFile1; return null; }, // TODO: make secure /** * Creates a temporary file. * * @returns {File} */ createTempFile: function () { let file = services.get("dirsvc").get("TmpD", Ci.nsIFile); file.append(config.tempFile); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600); return File(file); }, /** * Runs an external program. * * @param {string} program The program to run. * @param {string[]} args An array of arguments to pass to <b>program</b>. * @param {boolean} blocking Whether to wait until the process terminates. */ blockingProcesses: [], run: function (program, args, blocking) { args = args || []; blocking = !!blocking; let file; if (File.isAbsolutePath(program)) file = File(program, true); else { let dirs = services.get("environment").get("PATH").split(liberator.has("Windows") ? ";" : ":"); // Windows tries the CWD first TODO: desirable? if (liberator.has("Windows")) dirs = [io.getCurrentDirectory().path].concat(dirs); lookup: for (let dir of dirs) { file = File.joinPaths(dir, program); try { if (file.exists()) break; // TODO: couldn't we just palm this off to the start command? // automatically try to add the executable path extensions on windows if (liberator.has("Windows")) { let extensions = services.get("environment").get("PATHEXT").split(";"); for (let extension of extensions) { file = File.joinPaths(dir, program + extension); if (file.exists()) break lookup; } } } catch (e) {} } } if (!file || !file.exists()) { liberator.callInMainThread(function() { if (services.get("threadManager").isMainThread) // does not really seem to work but at least doesn't crash Firefox liberator.echoerr("Command not found: " + program); }, this); return -1; } let process = services.create("process"); process.init(file); process.run(false, args.map(String), args.length); try { if (blocking) while (process.isRunning) liberator.threadYield(false, true); } catch (e) { process.kill(); throw e; } return process.exitValue; }, // FIXME: multiple paths? /** * Sources files found in 'runtimepath'. For each relative path in * <b>paths</b> each directory in 'runtimepath' is searched and if a * matching file is found it is sourced. Only the first file found (per * specified path) is sourced unless <b>all</b> is specified, then * all found files are sourced. * * @param {string[]} paths An array of relative paths to source. * @param {boolean} all Whether all found files should be sourced. */ sourceFromRuntimePath: function (paths, all) { let dirs = File.getPathsFromPathList(options["runtimepath"]); let found = false; liberator.log("Searching for \"" + paths.join(" ") + "\" in \"" + options["runtimepath"] + "\""); outer: for (let dir of dirs) { for (let path of paths) { let file = File.joinPaths(dir, path); if (file.exists() && file.isFile() && file.isReadable()) { io.source(file.path, false); found = true; if (!all) break outer; } } } if (!found) liberator.log("not found in 'runtimepath': \"" + paths.join(" ") + "\""); return found; }, /** * Reads Ex commands, JavaScript or CSS from <b>filename</b>. * * @param {string} filename The name of the file to source. * @param {boolean} silent Whether errors should be reported. */ source: function (filename, silent) { let wasSourcing = this.sourcing; try { var file = File(filename); this.sourcing = { file: file.path, line: 0 }; if (!file.exists() || !file.isReadable() || file.isDirectory()) { if (!silent) { if (file.exists() && file.isDirectory()) liberator.echomsg("Cannot source a directory: " + filename); else liberator.echomsg("Could not source: " + filename); liberator.echoerr("Cannot open file: " + filename); } return; } // liberator.echomsg("Sourcing \"" + filename + "\" ..."); let str = file.read(); let uri = services.get("io").newFileURI(file); // handle pure JavaScript files specially if (/\.js$/.test(filename)) { try { // Workaround for SubscriptLoader caching. let suffix = '?' + encodeURIComponent(services.get("UUID").generateUUID().toString()); liberator.loadScript(uri.spec + suffix, Script(file)); if (liberator.initialized) liberator.initHelp(); } catch (e) { let err = new Error(); for (let [k, v] in Iterator(e)) err[k] = v; err.echoerr = xml`${file.path}:${e.lineNumber}: ${e}`; throw err; } } else if (/\.css$/.test(filename)) storage.styles.registerSheet(uri.spec, false, true); else { let heredoc = ""; let heredocEnd = null; // the string which ends the heredoc let lines = str.split(/\r\n|[\r\n]/); function execute(args) { command.execute(args, special, count, { setFrom: file }); } for (let [i, line] in Iterator(lines)) { if (heredocEnd) { // we already are in a heredoc if (heredocEnd.test(line)) { execute(heredoc); heredoc = ""; heredocEnd = null; } else heredoc += line + "\n"; } else { this.sourcing.line = i + 1; // skip line comments and blank lines line = line.replace(/\r$/, ""); if (/^\s*(".*)?$/.test(line)) continue; var [count, cmd, special, args] = commands.parseCommand(line); var command = commands.get(cmd); if (!command) { let lineNumber = i + 1; liberator.echoerr("Error detected while processing: " + file.path); commandline.echo("line " + lineNumber + ":", commandline.HL_LINENR, commandline.APPEND_TO_MESSAGES); liberator.echoerr("Not an editor command: " + line); } else { if (command.name == "finish") break; else if (command.hereDoc) { // check for a heredoc let matches = args.match(/(.*)<<\s*(\S+)$/); if (matches) { args = matches[1]; heredocEnd = RegExp("^" + matches[2] + "$", "m"); if (matches[1]) heredoc = matches[1] + "\n"; continue; } } execute(args); } } } // if no heredoc-end delimiter is found before EOF then // process the heredoc anyway - Vim compatible ;-) if (heredocEnd) execute(heredoc); } if (this._scriptNames.indexOf(file.path) == -1) this._scriptNames.push(file.path); liberator.log("Sourced: " + filename); } catch (e) { liberator.echoerr(e, null, "Sourcing file failed: "); } finally { this.sourcing = wasSourcing; } }, // TODO: when https://bugzilla.mozilla.org/show_bug.cgi?id=68702 is // fixed use that instead of a tmpfile /** * Runs <b>command</b> in a subshell and returns the output in a * string. The shell used is that specified by the 'shell' option. * * @param {string} command The command to run. * @param {string} input Any input to be provided to the command on stdin. * @returns {string} */ system: function (command, input) { liberator.echomsg("Executing: " + command); function escape(str) '"' + str.replace(/[\\"$]/g, "\\$&") + '"'; return this.withTempFiles(function (stdin, stdout, cmd) { if (input) stdin.write(input); // TODO: implement 'shellredir' if (liberator.has("Windows")) { if (options["shell"] == "cmd.exe") { command = "cd /D " + this._cwd.path + " && " + command + " > " + stdout.path + " 2>&1" + " < " + stdin.path; } else { // in this case, assume the shell is unix-like command = "cd " + escape(this._cwd.path) + " && " + command + " > " + escape(stdout.path) + " 2>&1" + " < " + escape(stdin.path); } var res = this.run(options["shell"], options["shellcmdflag"].split(/\s+/).concat(command), true); } else { cmd.write("cd " + escape(this._cwd.path) + "\n" + ["exec", ">" + escape(stdout.path), "2>&1", "<" + escape(stdin.path), escape(options["shell"]), options["shellcmdflag"], escape(command)].join(" ")); res = this.run("/bin/sh", ["-e", cmd.path], true); } let output = stdout.read(); if (res > 0) output += "\nshell returned " + res; // if there is only one \n at the end, chop it off else if (output && output.indexOf("\n") == output.length - 1) output = output.substr(0, output.length - 1); return output; }) || ""; }, /** * Creates a temporary file context for executing external commands. * <b>func</b> is called with a temp file, created with * {@link #createTempFile}, for each explicit argument. Ensures that * all files are removed when <b>func</b> returns. * * @param {function} func The function to execute. * @param {Object} self The 'this' object used when executing func. * @returns {boolean} false if temp files couldn't be created, * otherwise, the return value of <b>func</b>. */ withTempFiles: function (func, self) { let args = util.map(util.range(0, func.length), this.createTempFile); if (!args.every(util.identity)) return false; try { return func.apply(self || this, args); } finally { args.forEach(function (f) f.remove(false)); } } }, { /** * @property {string} The value of the $VIMPERATOR_RUNTIME environment * variable. */ get runtimePath() { const rtpvar = config.name.toUpperCase() + "_RUNTIME"; let rtp = services.get("environment").get(rtpvar); if (!rtp) { rtp = "~/" + (liberator.has("Windows") ? "" : ".") + config.name.toLowerCase(); services.get("environment").set(rtpvar, rtp); } return rtp; }, /** * @property {string} The current platform's path seperator. */ get PATH_SEP() { delete this.PATH_SEP; let f = services.get("dirsvc").get("CurProcD", Ci.nsIFile); f.append("foo"); return this.PATH_SEP = f.path.substr(f.parent.path.length, 1); } }, { commands: function () { commands.add(["cd", "chd[ir]"], "Change the current directory", function (args) { let arg = args.literalArg; if (!arg) { arg = "~"; } else if (arg == "-") { liberator.assert(io._oldcwd, "No previous directory"); arg = io._oldcwd.path; } arg = File.expandPath(arg); // go directly to an absolute path or look for a relative path // match in 'cdpath' if (File.isAbsolutePath(arg)) { if (io.setCurrentDirectory(arg)) liberator.echomsg(io.getCurrentDirectory().path); } else { let dirs = File.getPathsFromPathList(options["cdpath"]); let found = false; for (let dir of dirs) { dir = File.joinPaths(dir, arg); if (dir.exists() && dir.isDirectory() && dir.isReadable()) { io.setCurrentDirectory(dir.path); liberator.echomsg(io.getCurrentDirectory().path); found = true; break; } } if (!found) liberator.echoerr("Can't find directory " + arg.quote() + " in cdpath\n" + "Command failed"); } }, { argCount: "?", completer: function (context) completion.directory(context, true), literal: 0 }); // NOTE: this command is only used in :source commands.add(["fini[sh]"], "Stop sourcing a script file", function () { liberator.echoerr(":finish used outside of a sourced file"); }, { argCount: "0" }); commands.add(["pw[d]"], "Print the current directory name", function () { liberator.echomsg(io.getCurrentDirectory().path); }, { argCount: "0" }); // "mkv[imperatorrc]" or "mkm[uttatorrc]" commands.add([config.name.toLowerCase().replace(/(.)(.*)/, "mk$1[$2rc]")], "Write current key mappings and changed options to the config file", function (args) { liberator.assert(args.length <= 1, "Only one file name allowed"); let filename = args[0] || io.getRCFile(null, true).path; let file = File(filename); liberator.assert(!file.exists() || args.bang, "File exists: " + filename + ". Add ! to override."); // TODO: Use a set/specifiable list here: let lines = [cmd.serial().map(commands.commandToString) for (cmd in commands) if (cmd.serial)]; lines = util.Array.flatten(lines); // source a user .vimperatorrc file lines.unshift('"' + liberator.version + "\n"); // For the record, I think that adding this line is absurd. --Kris // I can't disagree. --djk lines.push(commands.commandToString({ command: "source", bang: true, arguments: [filename + ".local"] })); lines.push("\n\" vim: set ft=" + config.name.toLowerCase() + ":"); try { file.write(lines.join("\n")); } catch (e) { liberator.echoerr("Could not write to " + file.path + ": " + e.message); } }, { argCount: "*", // FIXME: should be "?" but kludged for proper error message bang: true, completer: function (context) completion.file(context, true) }); commands.add(["runt[ime]"], "Source the specified file from each directory in 'runtimepath'", function (args) { io.sourceFromRuntimePath(args, args.bang); }, { argCount: "+", bang: true } ); commands.add(["scrip[tnames]"], "List all sourced script names", function () { let list = template.tabular([{ header: "<SNR>", style: "text-align: right; padding-right: 1em;" }, "Filename"], ([i + 1, file] for ([i, file] in Iterator(io._scriptNames)))); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); }, { argCount: "0" }); commands.add(["so[urce]"], "Read Ex commands from a file", function (args) { io.source(args.literalArg, args.bang); }, { literal: 0, bang: true, completer: function (context) completion.file(context, true) }); commands.add(["!", "run"], "Run a command", function (args) { let arg = args.literalArg; // :!! needs to be treated specially as the command parser sets the // bang flag but removes the ! from arg if (args.bang) arg = "!" + arg; // replaceable bang and no previous command? liberator.assert(!/((^|[^\\])(\\\\)*)!/.test(arg) || io._lastRunCommand, "No previous command"); // NOTE: Vim doesn't replace ! preceded by 2 or more backslashes and documents it - desirable? // pass through a raw bang when escaped or substitute the last command arg = arg.replace(/(\\)*!/g, function (m) /^\\(\\\\)*!$/.test(m) ? m.replace("\\!", "!") : m.replace("!", io._lastRunCommand) ); io._lastRunCommand = arg; let output = io.system(arg); commandline.command = "!" + arg; commandline.echo(template.genericOutput("Command Output: " + arg, xml`<span highlight="CmdOutput">${String(output)}</span>`)); autocommands.trigger("ShellCmdPost", {}); }, { argCount: "?", bang: true, completer: function (context) completion.shellCommand(context), literal: 0 }); }, completion: function () { JavaScript.setCompleter([this.File, File.expandPath], [function (context, obj, args) { context.quote[2] = ""; completion.file(context, true); }]); completion.charset = function (context) { context.anchored = false; context.generate = function () { let names = util.Array( "more1 more2 more3 more4 more5 static".split(" ").map(function (key) options.getPref("intl.charsetmenu.browser." + key).split(', ')) ).flatten().uniq(); let bundle = document.getElementById("liberator-charset-bundle"); return names.map(function (name) [name, bundle.getString(name.toLowerCase() + ".title")]); }; }; completion.directory = function directory(context, full) { this.file(context, full); context.filters.push(function ({ item: f }) f.isDirectory()); }; completion.environment = function environment(context) { let command = liberator.has("Windows") ? "set" : "env"; let lines = io.system(command).split("\n"); lines.pop(); context.title = ["Environment Variable", "Value"]; context.generate = function () lines.map(function (line) (line.match(/([^=]+)=(.+)/) || []).slice(1)); }; // TODO: support file:// and \ or / path separators on both platforms // if "tail" is true, only return names without any directory components completion.file = function file(context, full) { // dir == "" is expanded inside readDirectory to the current dir let [dir] = context.filter.match(/^(?:.*[\/\\])?/); if (!full) context.advance(dir.length); context.title = [full ? "Path" : "Filename", "Type"]; context.keys = { text: !full ? "leafName" : function (f) dir + f.leafName, description: function (f) f.isDirectory() ? "Directory" : "File", isdir: function (f) f.exists() && f.isDirectory(), icon: function (f) f.isDirectory() ? "resource://gre/res/html/folder.png" : "moz-icon://" + f.leafName }; context.compare = function (a, b) b.isdir - a.isdir || String.localeCompare(a.text, b.text); context.match = function (str) { let filter = this.filter; if (!filter) return true; if (this.ignoreCase) { filter = filter.toLowerCase(); str = str.toLowerCase(); } return str.substr(0, filter.length) === filter; }; // context.background = true; context.key = dir; context.generate = function generate_file() { try { return File(dir).readDirectory(); } catch (e) {} return []; }; }; completion.shellCommand = function shellCommand(context) { context.title = ["Shell Command", "Path"]; context.generate = function () { let dirNames = services.get("environment").get("PATH").split(RegExp(liberator.has("Windows") ? ";" : ":")); let commands = []; for (let dirName of dirNames) { let dir = io.File(dirName); if (dir.exists() && dir.isDirectory()) { commands.push([[file.leafName, dir.path] for (file in dir.iterDirectory()) if (file.isFile() && file.isExecutable())]); } } return util.Array.flatten(commands); }; }; completion.addUrlCompleter("f", "Local files", completion.file); }, options: function () { var shell, shellcmdflag; if (liberator.has("Windows")) { shell = "cmd.exe"; // TODO: setting 'shell' to "something containing sh" updates // 'shellcmdflag' appropriately at startup on Windows in Vim shellcmdflag = "/c"; } else { shell = services.get("environment").get("SHELL") || "sh"; shellcmdflag = "-c"; } options.add(["fileencoding", "fenc"], "Sets the character encoding of read and written files", "string", "UTF-8", { completer: function (context) completion.charset(context) }); options.add(["cdpath", "cd"], "List of directories searched when executing :cd", "stringlist", "," + (services.get("environment").get("CDPATH").replace(/[:;]/g, ",") || ","), { setter: function (value) File.expandPathList(value) }); options.add(["runtimepath", "rtp"], "List of directories searched for runtime files", "stringlist", IO.runtimePath, { setter: function (value) File.expandPathList(value) }); options.add(["shell", "sh"], "Shell to use for executing :! and :run commands", "string", shell, { setter: function (value) File.expandPath(value) }); options.add(["shellcmdflag", "shcf"], "Flag passed to shell when executing :! and :run commands", "string", shellcmdflag); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ const AutoCommand = Struct("event", "pattern", "command"); /** * @instance autocommands */ const AutoCommands = Module("autocommands", { requires: ["config"], init: function () { this._store = []; }, __iterator__: function () util.Array.itervalues(this._store), /** * Adds a new autocommand. <b>cmd</b> will be executed when one of the * specified <b>events</b> occurs and the URL of the applicable buffer * matches <b>regex</b>. * * @param {Array} events The array of event names for which this * autocommand should be executed. * @param {string} regex The URL pattern to match against the buffer URL. * @param {string} cmd The Ex command to run. */ add: function (events, regex, cmd) { if (typeof events == "string") events = events.split(","); events.forEach(function (event) { this._store.push(AutoCommand(event, RegExp(regex), cmd)); }, this); }, /** * Returns all autocommands with a matching <b>event</b> and * <b>regex</b>. * * @param {string} event The event name filter. * @param {string} regex The URL pattern filter. * @returns {AutoCommand[]} */ get: function (event, regex) { return this._store.filter(function (autoCmd) AutoCommands.matchAutoCmd(autoCmd, event, regex)); }, /** * Deletes all autocommands with a matching <b>event</b> and * <b>regex</b>. * * @param {string} event The event name filter. * @param {string} regex The URL pattern filter. */ remove: function (event, regex) { this._store = this._store.filter(function (autoCmd) !AutoCommands.matchAutoCmd(autoCmd, event, regex)); }, /** * Lists all autocommands with a matching <b>event</b> and * <b>regex</b>. * * @param {string} event The event name filter. * @param {string} regex The URL pattern filter. */ list: function (event, regex) { let cmds = {}; // XXX this._store.forEach(function (autoCmd) { if (AutoCommands.matchAutoCmd(autoCmd, event, regex)) { cmds[autoCmd.event] = cmds[autoCmd.event] || []; cmds[autoCmd.event].push(autoCmd); } }); let list = template.genericOutput("Auto Commands", xml`<table> ${ template.map2(xml, cmds, function ([event, items]) xml`<tr highlight="Title"> <td colspan="2">${event}</td> </tr>${ template.map2(xml, items, function (item) xml`<tr> <td>&#160;${item.pattern.source}</td> <td>${item.command}</td> </tr>`)}`) } </table>`); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); }, /** * Triggers the execution of all autocommands registered for * <b>event</b>. A map of <b>args</b> is passed to each autocommand * when it is being executed. * * @param {string} event The event to fire. * @param {Object} args The args to pass to each autocommand. */ trigger: function (event, args) { if (options.get("eventignore").has("all", event)) return; let autoCmds = this._store.filter(function (autoCmd) autoCmd.event == event); let lastPattern = null; let url = args.url || ""; for (let autoCmd of autoCmds) { if (autoCmd.pattern.test(url)) { if (!lastPattern || lastPattern.source != autoCmd.pattern.source) liberator.echomsg("Executing " + event + " Auto commands for \"" + autoCmd.pattern.source + "\""); lastPattern = autoCmd.pattern; // liberator.echomsg("autocommand " + autoCmd.command, 9); if (typeof autoCmd.command == "function") { try { autoCmd.command.call(autoCmd, args); } catch (e) { liberator.reportError(e); liberator.echoerr(e); } } else liberator.execute(commands.replaceTokens(autoCmd.command, args), null, true); } } } }, { matchAutoCmd: function (autoCmd, event, regex) { return (!event || autoCmd.event == event) && (!regex || autoCmd.pattern.source == regex); } }, { commands: function () { commands.add(["au[tocmd]"], "Execute commands automatically on events", function (args) { let [event, regex, cmd] = args; let events = []; try { RegExp(regex); } catch (e) { liberator.assert(false, "Invalid argument: " + regex); } if (event) { // NOTE: event can only be a comma separated list for |:au {event} {pat} {cmd}| let validEvents = config.autocommands.map(function (event) event[0]); validEvents.push("*"); events = event.split(","); liberator.assert(events.every(function (event) validEvents.indexOf(event) >= 0), "No such group or event: " + event); } if (cmd) { // add new command, possibly removing all others with the same event/pattern if (args.bang) autocommands.remove(event, regex); if (args["-javascript"]) cmd = eval("(function (args) { with(args) {" + cmd + "} })"); autocommands.add(events, regex, cmd); } else { if (event == "*") event = null; if (args.bang) { // TODO: "*" only appears to work in Vim when there is a {group} specified if (args[0] != "*" || regex) autocommands.remove(event, regex); // remove all } else autocommands.list(event, regex); // list all } }, { bang: true, completer: function (context, args) { if (args.length == 1) return completion.autocmdEvent(context); if (args.length == 3) return args["-javascript"] ? completion.javascript(context) : completion.ex(context); }, literal: 2, options: [[["-javascript", "-js"], commands.OPTION_NOARG]] }); [ { name: "do[autocmd]", description: "Apply the autocommands matching the specified URL pattern to the current buffer" }, { name: "doautoa[ll]", description: "Apply the autocommands matching the specified URL pattern to all buffers" } ].forEach(function (command) { commands.add([command.name], command.description, // TODO: Perhaps this should take -args to pass to the command? function (args) { // Vim compatible if (args.length == 0) { liberator.echomsg("No matching autocommands"); return; } let [event, url] = args; let defaultURL = url || buffer.URL; let validEvents = config.autocommands.map(function (e) e[0]); // TODO: add command validators liberator.assert(event != "*", "Cannot execute autocommands for ALL events"); liberator.assert(validEvents.indexOf(event) >= 0, "No such group or event: " + args); liberator.assert(autocommands.get(event).some(function (c) c.pattern.test(defaultURL)), "No matching autocommands"); if (this.name == "doautoall" && liberator.has("tabs")) { let current = tabs.index(); for (let i = 0; i < tabs.count; i++) { tabs.select(i, false, true); // if no url arg is specified use the current buffer's URL autocommands.trigger(event, { url: defaultURL }); } tabs.select(current); } else autocommands.trigger(event, { url: defaultURL }); }, { argCount: "*", // FIXME: kludged for proper error message should be "1". completer: function (context) completion.autocmdEvent(context) }); }); }, completion: function () { JavaScript.setCompleter(this.get, [function () config.autocommands]); completion.autocmdEvent = function autocmdEvent(context) { context.completions = config.autocommands; }; completion.macro = function macro(context) { context.title = ["Macro", "Keys"]; context.completions = [item for (item in events.getMacros())]; }; }, options: function () { options.add(["eventignore", "ei"], "List of autocommand event names which should be ignored", "stringlist", "", { completer: function () config.autocommands.concat([["all", "All events"]]) }); options.add(["focuscontent", "fc"], "Try to stay in normal mode after loading a web page", "boolean", false); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2009 by Kris Maglione <maglione.k@gmail.com> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; const Cu = Components.utils; function array(obj) { if (isgenerator(obj)) obj = [k for (k in obj)]; else if (obj.length) obj = Array.slice(obj); return util.Array(obj); } function allkeys(obj) { for(; obj; obj = obj.__proto__) for (let prop of Object.getOwnPropertyNames(obj)) yield prop; } function keys(obj) { for (let prop of Object.getOwnPropertyNames(obj)) yield prop; } function values(obj) { for (var k of Object.keys(obj)) yield obj[k]; } function foreach(iter, fn, self) { for (let val in iter) fn.call(self, val); } function dict(ary) { var obj = {}; for (var i = 0; i < ary.length; i++) { var val = ary[i]; obj[val[0]] = val[1]; } return obj; } function iter(obj) { if (obj instanceof Ci.nsISimpleEnumerator) return (function () { while (obj.hasMoreElements()) yield obj.getNext(); })(); if (isinstance(obj, [Ci.nsIStringEnumerator, Ci.nsIUTF8StringEnumerator])) return (function () { while (obj.hasMore()) yield obj.getNext(); })(); if (isinstance(obj, Ci.nsIDOMNodeIterator)) return (function () { try { while (true) yield obj.nextNode(); } catch (e) {} })(); if (isinstance(obj, [HTMLCollection, NodeList])) return (node for (node of obj)); if (obj instanceof NamedNodeMap) return (function () { for (let i = 0, len = obj.length; i < len; ++i) yield [obj[i].name, obj[i]]; })(); return Iterator(obj); } function issubclass(targ, src) { return src === targ || targ && typeof targ === "function" && targ.prototype instanceof src; } function isinstance(targ, src) { const types = { boolean: Boolean, string: String, function: Function, number: Number } src = Array.concat(src); for (var i = 0; i < src.length; i++) { if (targ instanceof src[i]) return true; var type = types[typeof targ]; if (type && issubclass(src[i], type)) return true; } return false; } function isobject(obj) { return typeof obj === "object" && obj != null; } /** * Returns true if and only if its sole argument is an * instance of the builtin Array type. The array may come from * any window, frame, namespace, or execution context, which * is not the case when using (obj instanceof Array). */ function isarray(val) { return Object.prototype.toString.call(val) == "[object Array]"; } /** * Returns true if and only if its sole argument is an * instance of the builtin Generator type. This includes * functions containing the 'yield' statement and generator * statements such as (x for (x in obj)). */ function isgenerator(val) { return Object.prototype.toString.call(val) == "[object Generator]"; } /** * Returns true if and only if its sole argument is a String, * as defined by the builtin type. May be constructed via * String(foo) or new String(foo) from any window, frame, * namespace, or execution context, which is not the case when * using (obj instanceof String) or (typeof obj == "string"). */ function isstring(val) { return Object.prototype.toString.call(val) == "[object String]"; } /** * Returns true if and only if its sole argument may be called * as a function. This includes classes and function objects. */ function callable(val) { return typeof val === "function"; } function call(fn, context, ...args) { fn.apply(context, args); return fn; } /** * Curries a function to the given number of arguments. Each * call of the resulting function returns a new function. When * a call does not contain enough arguments to satisfy the * required number, the resulting function is another curried * function with previous arguments accumulated. * * function foo(a, b, c) [a, b, c].join(" "); * curry(foo)(1, 2, 3) -> "1 2 3"; * curry(foo)(4)(5, 6) -> "4 5 6"; * curry(foo)(7)(8)(9) -> "7 8 9"; * * @param {function} fn The function to curry. * @param {integer} length The number of arguments expected. * @default fn.length * @optional * @param {object} self The 'this' value for the returned function. When * omitted, the value of 'this' from the first call to the function is * preserved. * @optional */ function curry(fn, length, self, acc) { if (length == null) length = fn.length; if (length == 0) return fn; // Close over function with 'this' function close(self, fn) function () fn.apply(self, Array.slice(arguments)); if (acc == null) acc = []; return function () { let args = acc.concat(Array.slice(arguments)); // The curried result should preserve 'this' if (arguments.length == 0) return close(self || this, arguments.callee); if (args.length >= length) return fn.apply(self || this, args); return curry(fn, length, self || this, args); }; } /** * Updates an object with the properties of another object. Getters * and setters are copied as expected. Moreover, any function * properties receive new 'supercall' and 'superapply' properties, * which will call the identically named function in target's * prototype. * * let a = { foo: function (arg) "bar " + arg } * let b = { __proto__: a } * update(b, { foo: function () arguments.callee.supercall(this, "baz") }); * * a.foo("foo") -> "bar foo" * b.foo() -> "bar baz" * * @param {Object} target The object to update. * @param {Object} src The source object from which to update target. * May be provided multiple times. * @returns {Object} Returns its updated first argument. */ function update(target, ...sources) { for (let src of sources) { if (!src) continue; foreach(keys(src), function (k) { let desc = Object.getOwnPropertyDescriptor(src, k); Object.defineProperty(target, k, desc); if (("value" in desc) && callable(desc.value)) { let v = desc.value, proto = Object.getPrototypeOf(target); if (proto && (k in proto) && callable(proto[k])) { v.superapply = function superapply(self, args) { return proto[k].apply(self, args); }; v.supercall = function supercall(self, ...args) { return v.superapply(self, args); }; } else v.superapply = v.supercall = function dummy() {}; } }); } return target; } /** * Extends a subclass with a superclass. The subclass's * prototype is replaced with a new object, which inherits * from the superclass's prototype, {@see update}d with the * members of 'overrides'. * * @param {function} subclass * @param {function} superclass * @param {Object} overrides @optional */ function extend(subclass, superclass, overrides) { subclass.prototype = {}; update(subclass.prototype, overrides); // This is unduly expensive. Unfortunately necessary since // we apparently can't rely on the presence of the // debugger to enumerate properties when we have // __iterators__ attached to prototypes. subclass.prototype.__proto__ = superclass.prototype; subclass.superclass = superclass.prototype; subclass.prototype.constructor = subclass; subclass.prototype.__class__ = subclass; if (superclass.prototype.constructor === Object.prototype.constructor) superclass.prototype.constructor = superclass; } /** * @constructor Class * * Constructs a new Class. Arguments marked as optional must be * either entirely elided, or they must have the exact type * specified. * * @param {string} name The class's as it will appear when toString * is called, as well as in stack traces. * @optional * @param {function} base The base class for this module. May be any * callable object. * @optional * @default Class * @param {Object} prototype The prototype for instances of this * object. The object itself is copied and not used as a prototype * directly. * @param {Object} classProperties The class properties for the new * module constructor. More than one may be provided. * @optional * * @returns {function} The constructor for the resulting class. */ function Class() { function constructor() { let self = { __proto__: Constructor.prototype, constructor: Constructor, get closure() { delete this.closure; function closure(fn) function () fn.apply(self, arguments); for (let k in this) if (!this.__lookupGetter__(k) && callable(this[k])) closure[k] = closure(self[k]); return this.closure = closure; } }; var res = self.init.apply(self, arguments); return res !== undefined ? res : self; } var args = Array.slice(arguments); if (isstring(args[0])) var name = args.shift(); var superclass = Class; if (callable(args[0])) superclass = args.shift(); var Constructor = eval("(function " + (name || superclass.name).replace(/\W/g, "_") + String.substr(constructor, 20) + ")"); Constructor.__proto__ = superclass; if (!("init" in superclass.prototype) && !("init" in args[0])) { var superc = superclass; superclass = function Shim() {}; extend(superclass, superc, { init: superc }); } extend(Constructor, superclass, args[0]); update(Constructor, args[1]); args = args.slice(2); Array.forEach(args, function (obj) { if (callable(obj)) obj = obj.prototype; update(Constructor.prototype, obj); }); return Constructor; } Class.toString = function () "[class " + this.constructor.name + "]", Class.prototype = { /** * Initializes new instances of this class. Called automatically * when new instances are created. */ init: function () {}, toString: function () "[instance " + this.constructor.name + "]", /** * Exactly like {@see nsIDOMWindow#setTimeout}, except that it * preserves the value of 'this' on invocation of 'callback'. * * @param {function} callback The function to call after 'timeout' * @param {number} timeout The timeout, in seconds, to wait * before calling 'callback'. * @returns {integer} The ID of this timeout, to be passed to * {@see nsIDOMWindow#clearTimeout}. */ setTimeout: function (callback, timeout) { const self = this; function target() callback.call(self); return window.setTimeout(target, timeout); } }; /** * @class Struct * * Creates a new Struct constructor, used for creating objects with * a fixed set of named members. Each argument should be the name of * a member in the resulting objects. These names will correspond to * the arguments passed to the resultant constructor. Instances of * the new struct may be treated very much like arrays, and provide * many of the same methods. * * const Point = Struct("x", "y", "z"); * let p1 = Point(x, y, z); * * @returns {function} The constructor for the new Struct. */ function Struct(...args) { const Struct = Class("Struct", StructBase, { length: args.length, members: args }); args.forEach(function (name, i) { Object.defineProperty(Struct.prototype, name, { get: function () this[i], set: function (val) { this[i] = val }, enumerable: true, }); }); return Struct; } const StructBase = Class("StructBase", { init: function (...args) { for (var i = 0, len = args.length; i < len; ++i) if (args[i] != null) this[i] = args[i]; }, clone: function clone() this.constructor.apply(null, this.slice()), // Iterator over our named members __iterator__: function () { let self = this; return ([k, self[i]] for ([i, k] in Iterator(self.members))) } }, { /** * Sets a lazily constructed default value for a member of * the struct. The value is constructed once, the first time * it is accessed and memoized thereafter. * * @param {string} key The name of the member for which to * provide the default value. * @param {function} val The function which is to generate * the default value. */ defaultValue: function (key, val) { let proto = this.prototype; let i = proto.members.indexOf(key); if (i === -1) return; Object.defineProperty(this.prototype, i, { get: function () { if (this === proto) return; var value = val.call(this); Object.defineProperty(this, i, { value: value, writable: true }); return value; }, set: function (value) { if (this === proto) return; Object.defineProperty(this, i, { value: value, writable: true, }) }, }); } }); // Add no-sideeffect array methods. Can't set new Array() as the prototype or // get length() won't work. for (let k in values(["concat", "every", "filter", "forEach", "indexOf", "join", "lastIndexOf", "map", "reduce", "reduceRight", "reverse", "slice", "some", "sort"])) StructBase.prototype[k] = Array.prototype[k]; // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ const Template = Module("template", { add: function add(a, b) a + b, join: function join(c) function (a, b) a + c + b, map: function map(iter, func, sep, interruptable) { return this.map2(xml, iter, func, sep, interruptable); }, map2: function map(tag, iter, func, sep, interruptable) { if (iter.length) // FIXME: Kludge? iter = util.Array.itervalues(iter); let ret = tag``; let n = 0; var op = tag["+="] || tag["+"] ||function (lhs, rhs) tag`${lhs}${rhs}`; for each (let i in Iterator(iter)) { let val = func(i); if (val == undefined || (tag.isEmpty && tag.isEmpty(val))) continue; if (sep && n++) ret = op(ret, sep); if (interruptable && n % interruptable == 0) liberator.threadYield(true, true); ret = op(ret, val); } return ret; }, maybeXML: function maybeXML(val) { if (typeof val == "xml" || val instanceof TemplateSupportsXML) return val; try { return xml.raw`${val}`; } catch (e) {} return xml`${val}`; }, completionRow: function completionRow(item, highlightGroup) { if (typeof icon == "function") icon = icon(); if (highlightGroup) { var text = item[0] || ""; var desc = item[1] || ""; } else { var text = this.process[0].call(this, item, item.text); var desc = this.process[1].call(this, item, item.description); } return xml`<div highlight=${highlightGroup || "CompItem"} style="white-space: nowrap"> <!-- The non-breaking spaces prevent empty elements - from pushing the baseline down and enlarging - the row. --> <li highlight="CompResult">${text}&#160;</li> <li highlight="CompDesc">${desc}&#160;</li> </div>`; }, bookmarkDescription: function (item, text, filter) xml` <a href=${item.item.url} highlight="URL">${template.highlightFilter(text || "", filter)}</a>&#160; ${ !(item.extra && item.extra.length) ? "" : xml`<span class="extra-info"> (${ template.map2(xml, item.extra, function (e) xml`${e[0]}: <span highlight=${e[2]}>${e[1]}</span>`, xml.cdata`&#xa0;`/* Non-breaking space */) }) </span>` } `, icon: function (item, text) { return xml`<span highlight="CompIcon">${item.icon ? xml`<img src=${item.icon}/>` : ""}</span><span class="td-strut"/>${text}`; }, filter: function (str) xml`<span highlight="Filter">${str}</span>`, // if "processStrings" is true, any passed strings will be surrounded by " and // any line breaks are displayed as \n highlight: function highlight(arg, processStrings, clip) { // some objects like window.JSON or getBrowsers()._browsers need the try/catch try { let str = clip ? util.clip(String(arg), clip) : String(arg); switch (arg == null ? "undefined" : typeof arg) { case "number": return xml`<span highlight="Number">${str}</span>`; case "string": if (processStrings) str = str.quote(); return xml`<span highlight="String">${str}</span>`; case "boolean": return xml`<span highlight="Boolean">${str}</span>`; case "function": // Vim generally doesn't like /foo*/, because */ looks like a comment terminator. // Using /foo*(:?)/ instead. if (processStrings) return xml`<span highlight="Function">${str.replace(/\{(.|\n)*(?:)/g, "{ ... }")}</span>`; return xml`${arg}`; case "undefined": return xml`<span highlight="Null">${arg}</span>`; case "object": if (arg instanceof TemplateSupportsXML) return arg; // for java packages value.toString() would crash so badly // that we cannot even try/catch it if (/^\[JavaPackage.*\]$/.test(arg)) return xml`[JavaPackage]`; if (processStrings && false) str = template.highlightFilter(str, "\n", function () xml`<span highlight="NonText">^J</span>`); return xml`<span highlight="Object">${str}</span>`; case "xml": return arg; default: return `<unknown type>`; } } catch (e) { return `<unknown>`; } }, highlightFilter: function highlightFilter(str, filter, highlight) { if (filter.length == 0) return str; let filterArr = filter.split(" "); let matchArr = []; for (let item of filterArr) { if (!item) continue; let lcstr = String.toLowerCase(str); let lcfilter = item.toLowerCase(); let start = 0; while ((start = lcstr.indexOf(lcfilter, start)) > -1) { matchArr.push({pos:start, len:lcfilter.length}); start += lcfilter.length; } } return this.highlightSubstrings(str, matchArr, highlight || template.filter); }, highlightRegexp: function highlightRegexp(str, re, highlight) { let matchArr = []; let res; while ((res = re.exec(str)) && res[0].length) matchArr.push({pos:res.index, len:res[0].length}); return this.highlightSubstrings(str, matchArr, highlight || template.filter); }, removeOverlapMatch: function removeOverlapMatch(matchArr) { matchArr.sort(function(a,b) a.pos - b.pos || b.len - a.len); // Ascending start positions let resArr = []; let offset = -1; let last, prev; for (let item of matchArr) { last = item.pos + item.len; if (item.pos > offset) { prev = resArr[resArr.length] = item; offset = last; } else if (last > offset) { prev.len += (last - offset); offset = last; } } return resArr; }, highlightSubstrings: function highlightSubstrings(str, iter, highlight) { if (typeof str == "xml" || str instanceof TemplateSupportsXML) return str; if (str == "") return xml`${str}`; str = String(str).replace(" ", "\u00a0"); let s = xml``; var add = xml["+="]; let start = 0; let n = 0; for (let item of this.removeOverlapMatch(iter)) { if (n++ > 50) // Prevent infinite loops. return add(s, xml`${str.substr(start)}`); add(s, xml`${str.substring(start, item.pos)}`); add(s, highlight(str.substr(item.pos, item.len))); start = item.pos + item.len; } return add(s, xml`${str.substr(start)}`); }, highlightURL: function highlightURL(str, force, highlight) { highlight = "URL" + (highlight ? " " + highlight : ""); if (force || /^[a-zA-Z]+:\/\//.test(str)) return xml`<a highlight=${highlight} href=${str}>${str}</a>`; else return str; }, // A generic output function which can have an (optional) // title and the output can be an XML which is just passed on genericOutput: function generic(title, value) { if (title) return xml`<table style="width: 100%"> <tr style="text-align: left;" highlight="CompTitle"> <th>${title}</th> </tr> </table> <div style="padding-left: 0.5ex; padding-right: 0.5ex">${value}</div> `; else return xml`${value}`; }, // every item must have a .xml property which defines how to draw itself // @param headers is an array of strings, the text for the header columns genericTable: function genericTable(items, format) { completion.listCompleter(function (context) { context.filterFunc = null; if (format) context.format = format; context.completions = items; }); }, options: function options(title, opts) { return this.genericOutput("", xml`<table style="width: 100%"> <tr highlight="CompTitle" align="left"> <th>${title}</th> </tr> ${ this.map2(xml, opts, function (opt) xml` <tr> <td> <span style=${opt.isDefault ? "" : "font-weight: bold"}>${opt.pre}${opt.name}</span><span>${opt.value}</span> ${opt.isDefault || opt.default == null ? "" : xml`<span class="extra-info"> (default: ${opt.default})</span>`} </td> </tr>`) } </table>`); }, // only used by showPageInfo: look for some refactoring table: function table(title, data, indent) { return this.table2(xml, title, data, indent); }, table2: function table2(tag, title, data, indent) { var body = this.map2(tag, data, function (datum) tag` <tr> <td style=${"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>${datum[0]}</td> <td>${template.maybeXML(datum[1])}</td> </tr>`); let table = tag`<table> <tr highlight="Title" align="left"> <th colspan="2">${title}</th> </tr> ${body} </table>`; return body ? table : tag``; }, // This is a generic function which can display tabular data in a nice way. // @param {string|array(string|object)} columns: Can either be: // a) A string which is the only column header, streching the whole width // b) An array of strings: Each string is the header of a column // c) An array of objects: An object has optional properties "header", "style" // and "highlight" which define the columns appearance // @param {object} rows: The rows as an array or arrays (or other iterable objects) tabular: function tabular(columns, rows) { function createHeadings() { if (typeof(columns) == "string") return xml`<th colspan=${(rows && rows[0].length) || 1}>${columns}</th>`; let colspan = 1; return template.map(columns, function (h) { if (colspan > 1) { colspan--; return xml``; } if (typeof(h) == "string") return xml`<th>${h}</th>`; let header = h.header || ""; colspan = h.colspan || 1; return xml`<th colspan=${colspan}>${header}</th>`; }); } function createRow(row) { return template.map(Iterator(row), function ([i, d]) { let style = ((columns && columns[i] && columns[i].style) || "") + (i == (row.length - 1) ? "; width: 100%" : ""); // the last column should take the available space -> width: 100% let highlight = (columns && columns[i] && columns[i].highlight) || ""; return xml`<td style=${style} highlight=${highlight}>${template.maybeXML(d)}</td>`; }); } return xml`<table style="width: 100%"> <tr highlight="CompTitle" align="left"> ${ createHeadings() } </tr> ${ this.map2(xml, rows, function (row) xml`<tr highlight="CompItem"> ${ createRow(row) } </tr>`) } </table>`; } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * @instance events */ const Events = Module("events", { requires: ["autocommands", "config"], init: function () { const self = this; this._fullscreen = window.fullScreen; this._lastFocus = null; this._currentMacro = ""; this._lastMacro = ""; this.sessionListeners = []; this._macros = storage.newMap("macros", { store: true, privateData: true }); // NOTE: the order of ["Esc", "Escape"] or ["Escape", "Esc"] // matters, so use that string as the first item, that you // want to refer to within liberator's source code for // comparisons like if (key == "<Esc>") { ... } this._keyTable = { add: ["Plus", "Add"], back_space: ["BS"], delete: ["Del"], escape: ["Esc", "Escape"], insert: ["Insert", "Ins"], left_shift: ["LT", "<"], return: ["Return", "CR", "Enter"], right_shift: [">"], space: ["Space", " "], subtract: ["Minus", "Subtract"] }; this._code_key = {}; this._key_code = {}; for (let [k, v] in Iterator(KeyEvent)) if (/^DOM_VK_(?![A-Z0-9]$)/.test(k)) { k = k.substr(7).toLowerCase(); let names = [k.replace(/(^|_)(.)/g, function (m, n1, n2) n2.toUpperCase()) .replace(/^NUMPAD/, "k")]; if (k in this._keyTable) names = this._keyTable[k]; this._code_key[v] = names[0]; for (let name of names) this._key_code[name.toLowerCase()] = v; } // HACK: as Gecko does not include an event for <, we must add this in manually. if (!("<" in this._key_code)) { this._key_code["<"] = 60; this._key_code["lt"] = 60; this._code_key[60] = "lt"; } this._input = { buffer: "", // partial command storage pendingMotionMap: null, // e.g. "d{motion}" if we wait for a motion of the "d" command pendingArgMap: null, // pending map storage for commands like m{a-z} count: null // parsed count from the input buffer }; // load all macros // setTimeout needed since io. is loaded after events. setTimeout(function () { try { let dirs = io.getRuntimeDirectories("macros"); if (dirs.length > 0) { for (let dir of dirs) { liberator.log("Sourcing macros directory: " + dir.path); for (let file in dir.iterDirectory()) { if (file.exists() && !file.isDirectory() && file.isReadable() && /^[\w_-]+(\.vimp)?$/i.test(file.leafName)) { let name = file.leafName.replace(/\.vimp$/i, ""); this._macros.set(name, file.read().split("\n")[0]); liberator.echomsg("Macro " + name + " added: " + this._macros.get(name)); } } } } else liberator.log("No user macros directory found"); } catch (e) { // thrown if directory does not exist liberator.log("Error sourcing macros directory: " + e); } }, 100); function wrapListener(method) { return function (event) { try { self[method](event); } catch (e) { if (e.message == "Interrupted") liberator.echoerr("Interrupted"); else liberator.echoerr("Processing " + event.type + " event: " + (e.echoerr || e)); liberator.echoerr(e); } }; } this._wrappedOnKeyPress = wrapListener("onKeyPress"); this._wrappedOnKeyUpOrDown = wrapListener("onKeyUpOrDown"); this.addSessionListener(window, "keypress", this.closure._wrappedOnKeyPress, true); this.addSessionListener(window, "keydown", this.closure._wrappedOnKeyUpOrDown, true); this.addSessionListener(window, "keyup", this.closure._wrappedOnKeyUpOrDown, true); this._activeMenubar = false; this.addSessionListener(window, "popupshown", this.closure.onPopupShown, true); this.addSessionListener(window, "popuphidden", this.closure.onPopupHidden, true); this.addSessionListener(window, "DOMMenuBarActive", this.closure.onDOMMenuBarActive, true); this.addSessionListener(window, "DOMMenuBarInactive", this.closure.onDOMMenuBarInactive, true); this.addSessionListener(window, "resize", this.closure.onResize, true); }, destroy: function () { liberator.log("Removing all event listeners"); for (let args in values(this.sessionListeners)) args[0].removeEventListener.apply(args[0], args.slice(1)); }, /** * Adds an event listener for this session and removes it on * liberator shutdown. * * @param {Element} target The element on which to listen. * @param {string} event The event to listen for. * @param {function} callback The function to call when the event is received. * @param {boolean} capture When true, listen during the capture * phase, otherwise during the bubbling phase. */ addSessionListener: function (target, event, callback, capture) { let args = Array.slice(arguments, 0); target.addEventListener.apply(target, args.slice(1)); this.sessionListeners.push(args); }, /** * @property {boolean} Whether synthetic key events are currently being * processed. */ feedingKeys: false, /** * Initiates the recording of a key event macro. * * @param {string} macro The name for the macro. */ startRecording: function (macro) { // TODO: ignore this like Vim? liberator.assert(/[a-zA-Z0-9]/.test(macro), "Invalid register name: '" + macro + "'"); modes.isRecording = true; if (/[A-Z]/.test(macro)) { // uppercase (append) this._currentMacro = macro.toLowerCase(); if (!this._macros.get(this._currentMacro)) this._macros.set(this._currentMacro, ""); // initialize if it does not yet exist } else { this._currentMacro = macro; this._macros.set(this._currentMacro, ""); } }, /** * Replays a macro. * * @param {string} The name of the macro to replay. * @returns {boolean} */ playMacro: function (macro) { let res = false; if (!/[a-zA-Z0-9@]/.test(macro) && macro.length == 1) { liberator.echoerr("Invalid macro name: " + macro); return false; } if (macro == "@") { // use lastMacro if it's set if (!this._lastMacro) { liberator.echoerr("No previously used macro"); return false; } } else { if (macro.length == 1) this._lastMacro = macro.toLowerCase(); // XXX: sets last played macro, even if it does not yet exist else this._lastMacro = macro; // e.g. long names are case sensitive } if (this._macros.get(this._lastMacro)) { // make sure the page is stopped before starting to play the macro try { window.getWebNavigation().stop(nsIWebNavigation.STOP_ALL); } catch (e) {} buffer.loaded = 1; // even if not a full page load, assume it did load correctly before starting the macro modes.isReplaying = true; res = events.feedkeys(this._macros.get(this._lastMacro), { noremap: true }); modes.isReplaying = false; } else { liberator.echoerr("Macro not set: " + this._lastMacro); } return res; }, /** * Returns all macros matching <b>filter</b>. * * @param {string} filter A regular expression filter string. A null * filter selects all macros. */ getMacros: function (filter) { if (!filter) return this._macros; let re = RegExp(filter); return ([macro, keys] for ([macro, keys] in this._macros) if (re.test(macro))); }, /** * Deletes all macros matching <b>filter</b>. * * @param {string} filter A regular expression filter string. A null * filter deletes all macros. */ deleteMacros: function (filter) { let re = RegExp(filter); for (let [item, ] in this._macros) { if (re.test(item) || !filter) this._macros.remove(item); } }, /** * Pushes keys onto the event queue from liberator. It is similar to * Vim's feedkeys() method, but cannot cope with 2 partially-fed * strings, you have to feed one parsable string. * * @param {string} keys A string like "2<C-f>" to push onto the event * queue. If you want "<" to be taken literally, prepend it with a * "\\". * @param {boolean} noremap Allow recursive mappings. * @param {boolean} silent Whether the command should be echoed to the * command line. * @returns {boolean} */ feedkeys: function (keys, noremap, quiet) { let doc = window.document; let view = window.document.defaultView; let wasFeeding = this.feedingKeys; this.feedingKeys = true; this.duringFeed = this.duringFeed || []; let wasQuiet = commandline.quiet; if (quiet) commandline.quiet = quiet; try { feed: { liberator.threadYield(1, true); for (let evt_obj of events.fromString(keys)) { let elem = liberator.focus || config.browser.contentWindow; let evt = events.create(doc, "keypress", evt_obj); if (typeof noremap == "object") for (let [k, v] in Iterator(noremap)) evt[k] = v; else evt.noremap = !!noremap; evt.isMacro = true; // A special hack for liberator-specific key names. if (evt_obj.liberatorString || evt_obj.liberatorShift) { evt.liberatorString = evt_obj.liberatorString; // for key-less keypress events e.g. <Nop> evt.liberatorShift = evt_obj.liberatorShift; // for untypable shift keys e.g. <S-1> events.onKeyPress(evt); } else elem.dispatchEvent(evt); if (!this.feedingKeys) break feed; // Stop feeding keys if page loading failed. if (modes.isReplaying && !this.waitForPageLoad()) break feed; } return true; } } finally { this.feedingKeys = wasFeeding; if (quiet) commandline.quiet = wasQuiet; if (this.duringFeed.length) { let duringFeed = this.duringFeed; this.duringFeed = []; for (let evt of duringFeed) evt.target.dispatchEvent(evt); } } }, /** * Creates an actual event from a pseudo-event object. * * The pseudo-event object (such as may be retrieved from events.fromString) * should have any properties you want the event to have. * * @param {Document} doc The DOM document to associate this event with * @param {Type} type The type of event (keypress, click, etc.) * @param {Object} opts The pseudo-event. */ create: function (doc, type, opts) { var DEFAULTS = { Key: { type: type, bubbles: true, cancelable: true, view: doc.defaultView, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, keyCode: 0, charCode: 0 }, Mouse: { type: type, bubbles: true, cancelable: true, view: doc.defaultView, detail: 1, screenX: 0, screenY: 0, clientX: 0, clientY: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, button: 0, relatedTarget: null } }; const TYPES = { click: "Mouse", mousedown: "Mouse", mouseup: "Mouse", mouseover: "Mouse", mouseout: "Mouse", keypress: "Key", keyup: "Key", keydown: "Key" }; var t = TYPES[type]; var evt = doc.createEvent(t + "Events"); evt["init" + t + "Event"].apply(evt, [v for (v of values(update(DEFAULTS[t], opts)))]); return evt; }, /** * Converts a user-input string of keys into a canonical * representation. * * <C-A> maps to <C-a>, <C-S-a> maps to <C-S-A> * <C- > maps to <C-Space>, <S-a> maps to A * << maps to <lt><lt> * * <S-@> is preserved, as in vim, to allow untypable key-combinations * in macros. * * canonicalKeys(canonicalKeys(x)) == canonicalKeys(x) for all values * of x. * * @param {string} keys Messy form. * @returns {string} Canonical form. */ canonicalKeys: function (keys) { return events.fromString(keys).map(events.closure.toString).join(""); }, /** * Converts an event string into an array of pseudo-event objects. * * These objects can be used as arguments to events.toString or * events.create, though they are unlikely to be much use for other * purposes. They have many of the properties you'd expect to find on a * real event, but none of the methods. * * Also may contain two "special" parameters, .liberatorString and * .liberatorShift these are set for characters that can never by * typed, but may appear in mappings, for example <Nop> is passed as * liberatorString, and liberatorShift is set when a user specifies * <S-@> where @ is a non-case-changable, non-space character. * * @param {string} keys The string to parse. * @returns {Array[Object]} */ fromString: function (input) { let out = []; let re = RegExp("<.*?>?>|[^<]|<(?!.*>)", "g"); let match; while ((match = re.exec(input))) { let evt_str = match[0]; let evt_obj = { ctrlKey: false, shiftKey: false, altKey: false, metaKey: false, keyCode: 0, charCode: 0, type: "keypress" }; if (evt_str.length > 1) { // <.*?> let [match, modifier, keyname] = evt_str.match(/^<((?:[CSMA]-)*)(.+?)>$/i) || [false, '', '']; modifier = modifier.toUpperCase(); keyname = keyname.toLowerCase(); if (keyname && !(keyname.length == 1 && modifier.length == 0 || // disallow <> and <a> !(keyname.length == 1 || this._key_code[keyname] || keyname == "nop" || /mouse$/.test(keyname)))) { // disallow <misteak> evt_obj.ctrlKey = /C-/.test(modifier); evt_obj.altKey = /A-/.test(modifier); evt_obj.shiftKey = /S-/.test(modifier); evt_obj.metaKey = /M-/.test(modifier); if (keyname.length == 1) { // normal characters if (evt_obj.shiftKey) { keyname = keyname.toUpperCase(); if (keyname == keyname.toLowerCase()) evt_obj.liberatorShift = true; } evt_obj.charCode = keyname.charCodeAt(0); } else if (keyname == "nop") { evt_obj.liberatorString = "<Nop>"; } else if (/mouse$/.test(keyname)) { // mouse events evt_obj.type = (/2-/.test(modifier) ? "dblclick" : "click"); evt_obj.button = ["leftmouse", "middlemouse", "rightmouse"].indexOf(keyname); delete evt_obj.keyCode; delete evt_obj.charCode; } else { // spaces, control characters, and < evt_obj.keyCode = this._key_code[keyname]; evt_obj.charCode = 0; } } else { // an invalid sequence starting with <, treat as a literal out = out.concat(events.fromString("<lt>" + evt_str.substr(1))); continue; } } else // a simple key (no <...>) evt_obj.charCode = evt_str.charCodeAt(0); // TODO: make a list of characters that need keyCode and charCode somewhere if (evt_obj.keyCode == 32 || evt_obj.charCode == 32) evt_obj.charCode = evt_obj.keyCode = 32; // <Space> if (evt_obj.keyCode == 60 || evt_obj.charCode == 60) evt_obj.charCode = evt_obj.keyCode = 60; // <lt> out.push(evt_obj); } return out; }, /** * Converts the specified event to a string in liberator key-code * notation. Returns null for an unknown event. * * E.g. pressing ctrl+n would result in the string "<C-n>". * * @param {Event} event * @returns {string} */ toString: function (event) { if (!event) return "[instance events]"; if (event.liberatorString) return event.liberatorString; let key = null; let modifier = ""; if (event.ctrlKey) modifier += "C-"; if (event.altKey) modifier += "A-"; if (event.metaKey) modifier += "M-"; if (/^key/.test(event.type)) { let charCode = event.type == "keyup" ? 0 : event.charCode; if (charCode == 0) { if (event.shiftKey) modifier += "S-"; if (event.keyCode in this._code_key) key = this._code_key[event.keyCode]; } // [Ctrl-Bug] special handling of mysterious <C-[>, <C-\\>, <C-]>, <C-^>, <C-_> bugs (OS/X) // (i.e., cntrl codes 27--31) // --- // For more information, see: // [*] Vimp FAQ: http://vimperator.org/trac/wiki/Vimperator/FAQ#WhydoesntC-workforEscMacOSX // [*] Referenced mailing list msg: http://www.mozdev.org/pipermail/vimperator/2008-May/001548.html // [*] Mozilla bug 416227: event.charCode in keypress handler has unexpected values on Mac for Ctrl with chars in "[ ] _ \" // https://bugzilla.mozilla.org/show_bug.cgi?query_format=specific&order=relevance+desc&bug_status=__open__&id=416227 // [*] Mozilla bug 432951: Ctrl+'foo' doesn't seem same charCode as Meta+'foo' on Cocoa // https://bugzilla.mozilla.org/show_bug.cgi?query_format=specific&order=relevance+desc&bug_status=__open__&id=432951 // --- // // The following fixes are only activated if liberator.has("MacUnix"). // Technically, they prevent mappings from <C-Esc> (and // <C-C-]> if your fancy keyboard permits such things<?>), but // these <C-control> mappings are probably pathological (<C-Esc> // certainly is on Windows), and so it is probably // harmless to remove the has("MacUnix") if desired. // else if (liberator.has("MacUnix") && event.ctrlKey && charCode >= 27 && charCode <= 31) { if (charCode == 27) { // [Ctrl-Bug 1/5] the <C-[> bug key = "Esc"; modifier = modifier.replace("C-", ""); } else // [Ctrl-Bug 2,3,4,5/5] the <C-\\>, <C-]>, <C-^>, <C-_> bugs key = String.fromCharCode(charCode + 64); } // a normal key like a, b, c, 0, etc. else if (charCode > 0) { key = String.fromCharCode(charCode); if (key in this._key_code) { // a named charcode key (<Space> and <lt>) space can be shifted, <lt> must be forced if ((key.match(/^\s$/) && event.shiftKey) || event.liberatorShift) modifier += "S-"; key = this._code_key[this._key_code[key]]; } else { // a shift modifier is only allowed if the key is alphabetical and used in a C-A-M- mapping in the uppercase, // or if the shift has been forced for a non-alphabetical character by the user while :map-ping if ((key != key.toLowerCase() && (event.ctrlKey || event.altKey || event.metaKey)) || event.liberatorShift) modifier += "S-"; else if (modifier.length == 0) return key; } } if (key == null) return null; } else if (event.type == "click" || event.type == "dblclick") { if (event.shiftKey) modifier += "S-"; if (event.type == "dblclick") modifier += "2-"; switch (event.button) { case 0: key = "LeftMouse"; break; case 1: key = "MiddleMouse"; break; case 2: key = "RightMouse"; break; } } if (key == null) return null; return "<" + modifier + key + ">"; }, /** * Whether <b>key</b> is a key code defined to accept/execute input on * the command line. * * @param {string} key The key code to test. * @returns {boolean} */ isAcceptKey: function (key) key == "<Return>" || key == "<C-j>" || key == "<C-m>", /** * Whether <b>key</b> is a key code defined to reject/cancel input on * the command line. * * @param {string} key The key code to test. * @returns {boolean} */ isCancelKey: function (key) key == "<Esc>" || key == "<C-[>" || key == "<C-c>", /** * Waits for the current buffer to successfully finish loading. Returns * true for a successful page load otherwise false. * * @returns {boolean} */ waitForPageLoad: function () { liberator.threadYield(true); // clear queue if (buffer.loaded == 1) return true; const maxWaitTime = 25; let start = Date.now(); let end = start + (maxWaitTime * 1000); // maximum time to wait - TODO: add option let now; while (now = Date.now(), now < end) { liberator.threadYield(); if (!events.feedingKeys) return false; if (buffer.loaded > 0) { liberator.sleep(250); break; } else liberator.echomsg("Waiting for page to load..."); } modes.show(); let ret = (buffer.loaded == 1); if (!ret) liberator.echoerr("Page did not load completely in " + maxWaitTime + " seconds. Macro stopped."); // sometimes the input widget had focus when replaying a macro // maybe this call should be moved somewhere else? // liberator.focusContent(true); return ret; }, // argument "event" is deliberately not used, as i don't seem to have // access to the real focus target // Huh? --djk onFocusChange: function (event) { // command line has it's own focus change handler if (liberator.mode == modes.COMMAND_LINE) return; function hasHTMLDocument(win) win && win.document && win.document instanceof HTMLDocument let win = window.document.commandDispatcher.focusedWindow; let elem = window.document.commandDispatcher.focusedElement; if (win && win.top == content) buffer.localStore.focusedFrame = win; try { if (elem && elem.readOnly) return; if ((elem instanceof HTMLInputElement && /^(text|password|datetime|datetime-local|date|month|time|week|number|range|email|url|search|tel|color)$/.test(elem.type)) || (elem instanceof HTMLSelectElement)) { liberator.mode = modes.INSERT; if (hasHTMLDocument(win)) buffer.lastInputField = elem; return; } if (elem instanceof HTMLEmbedElement || elem instanceof HTMLObjectElement) { liberator.mode = modes.EMBED; return; } if (elem instanceof HTMLTextAreaElement || (elem && elem.contentEditable == "true")) { if (options["insertmode"]) modes.set(modes.INSERT); else if (elem.selectionEnd - elem.selectionStart > 0) modes.set(modes.VISUAL, modes.TEXTAREA); else modes.main = modes.TEXTAREA; if (hasHTMLDocument(win)) buffer.lastInputField = elem; return; } if (Editor.windowIsEditable(win)) { if (options["insertmode"]) modes.set(modes.INSERT); else if (win.getSelection().toString() != "") modes.set(modes.VISUAL, modes.TEXTAREA); else modes.main = modes.TEXTAREA; buffer.lastInputField = win; return; } if (config.focusChange) { config.focusChange(win); return; } let urlbar = document.getElementById("urlbar"); if (elem == null && urlbar && urlbar.inputField == this._lastFocus) liberator.threadYield(true); if (liberator.mode & (modes.EMBED | modes.INSERT | modes.TEXTAREA | modes.VISUAL)) modes.reset(); } finally { this._lastFocus = elem; } }, onSelectionChange: function (event) { let couldCopy = false; let controller = document.commandDispatcher.getControllerForCommand("cmd_copy"); if (controller && controller.isCommandEnabled("cmd_copy")) couldCopy = true; if (liberator.mode != modes.VISUAL) { if (couldCopy) { if ((liberator.mode == modes.TEXTAREA || (modes.extended & modes.TEXTAREA)) && !options["insertmode"]) modes.set(modes.VISUAL, modes.TEXTAREA); else if (liberator.mode == modes.CARET) modes.set(modes.VISUAL, modes.CARET); } } // XXX: disabled, as i think automatically starting visual caret mode does more harm than help // else // { // if (!couldCopy && modes.extended & modes.CARET) // liberator.mode = modes.CARET; // } }, /** * The global escape key handler. This is called in ALL modes. */ onEscape: function () { if (modes.passNextKey) // We allow <Esc> in passAllKeys return; // always clear the commandline. Even if we are in // NORMAL mode, we might have a commandline visible, // e.g. after pressing 'n' to show the last search // again. commandline.clear(); switch (liberator.mode) { case modes.NORMAL: // clear any selection made let selection = Buffer.focusedWindow.getSelection(); try { // a simple if (selection) does not seem to work selection.collapseToStart(); } catch (e) {} // also clear any focus rectangle if (liberator.focus) liberator.focus.blur(); // select only one message in Muttator if (liberator.has("mail") && !config.isComposeWindow) { let i = gDBView.selection.currentIndex; if (i == -1 && gDBView.rowCount >= 0) i = 0; gDBView.selection.select(i); } //modes.reset(); // TODO: Needed? break; case modes.VISUAL: if (modes.extended & modes.TEXTAREA) liberator.mode = modes.TEXTAREA; else if (modes.extended & modes.CARET) liberator.mode = modes.CARET; break; case modes.CARET: // setting this option will trigger an observer which will // take care of all other details like setting the NORMAL // mode options.setPref("accessibility.browsewithcaret", false); break; case modes.TEXTAREA: // TODO: different behaviour for text areas and other input // fields seems unnecessarily complicated. If the user // likes Vi-mode then they probably like it for all input // fields, if not they can enter it explicitly for only // text areas. The mode name TEXTAREA is confusing and // would be better replaced with something indicating that // it's a Vi editing mode. Extended modes really need to be // displayed too. --djk function isInputField() { let elem = liberator.focus; return (elem instanceof HTMLInputElement && !/image/.test(elem.type)); } if (options["insertmode"] || isInputField()) liberator.mode = modes.INSERT; else modes.reset(); break; case modes.INSERT: if ((modes.extended & modes.TEXTAREA)) liberator.mode = modes.TEXTAREA; else modes.reset(); break; default: // HINTS, CUSTOM or COMMAND_LINE modes.reset(); break; } // clear any command output, if we have any modes.show(); }, // this keypress handler gets always called first, even if e.g. // the commandline has focus // TODO: ...help me...please... onKeyPress: function (event) { function isEscapeKey(key) key == "<Esc>" || key == "<C-[>"; function killEvent() { event.preventDefault(); event.stopPropagation(); } function updateCount(value) { events._input.count = parseInt(value, 10); if (isNaN(events._input.count)) events._input.count = null; } let key = events.toString(event); if (!key) return; let url = typeof(buffer) != "undefined" ? buffer.URL : ""; if (modes.isRecording) { if (key == "q" && liberator.mode != modes.INSERT && liberator.mode != modes.TEXTAREA) { // TODO: should not be hardcoded modes.isRecording = false; liberator.echomsg("Recorded macro '" + this._currentMacro + "'"); killEvent(); return; } else if (!mappings.hasMap(liberator.mode, this._input.buffer + key, url)) this._macros.set(this._currentMacro, this._macros.get(this._currentMacro) + key); } if (key == "<C-c>") liberator.interrupted = true; // feedingKeys needs to be separate from interrupted so // we can differentiate between a recorded <C-c> // interrupting whatever it's started and a real <C-c> // interrupting our playback. if (events.feedingKeys && !event.isMacro) { if (key == "<C-c>") { events.feedingKeys = false; if (modes.isReplaying) { modes.isReplaying = false; this.setTimeout(function () { liberator.echomsg("Canceled playback of macro '" + this._lastMacro + "'"); }, 100); } } else events.duringFeed.push(event); killEvent(); return; } try { let stop = false; let win = document.commandDispatcher.focusedWindow; // special mode handling if (modes.isMenuShown) { // menus have their own command handlers stop = true; } else if (modes.passNextKey) { // handle Escape-one-key mode ('i') modes.passNextKey = false; stop = true; } else if (modes.passAllKeys) { // handle Escape-all-keys mode (Shift-Esc) if (key == "<S-Esc>" || key == "<Insert>") // FIXME: Don't hardcode! modes.passAllKeys = false; // If we manage to get into command line mode while IGNOREKEYS, let the command line handle keys if (liberator.mode == modes.COMMAND_LINE) stop = false; // If we are in the middle of a mapping, we never send the next key to the host app else if (this._input.buffer) stop = false; // Respect "unignored" keys else if (modes._passKeysExceptions == null || modes._passKeysExceptions.indexOf(key) < 0) stop = true; } if (stop) { this._input.buffer = ""; return; } stop = true; // set to false if we should NOT consume this event but let the host app handle it // just forward event without checking any mappings when the MOW is open if (liberator.mode == modes.COMMAND_LINE && (modes.extended & modes.OUTPUT_MULTILINE)) { commandline.onMultilineOutputEvent(event); throw killEvent(); } // XXX: ugly hack for now pass certain keys to the host app as // they are without beeping also fixes key navigation in combo // boxes, submitting forms, etc. // FIXME: breaks iabbr for now --mst if (key in config.ignoreKeys && (config.ignoreKeys[key] & liberator.mode)) { this._input.buffer = ""; return; } // TODO: handle middle click in content area if (!isEscapeKey(key)) { // custom mode... if (liberator.mode == modes.CUSTOM) { plugins.onEvent(event); throw killEvent(); } // All of these special cases for hint mode are driving // me insane! -Kris if (modes.extended & modes.HINTS) { // under HINT mode, certain keys are redirected to hints.onEvent if (key == "<Return>" || key == "<Tab>" || key == "<S-Tab>" || key == mappings.getMapLeader() || (key == "<BS>" && hints.previnput == "number") || (hints._isHintNumber(key) && !hints.escNumbers)) { hints.onEvent(event); this._input.buffer = ""; throw killEvent(); } // others are left to generate the 'input' event or handled by the host app return; } } // FIXME (maybe): (is an ESC or C-] here): on HINTS mode, it enters // into 'if (map && !skipMap) below. With that (or however) it // triggers the onEscape part, where it resets mode. Here I just // return true, with the effect that it also gets to there (for // whatever reason). if that happens to be correct, well.. // XXX: why not just do that as well for HINTS mode actually? if (liberator.mode == modes.CUSTOM) return; let inputStr = this._input.buffer + key; let countStr = inputStr.match(/^[1-9][0-9]*|/)[0]; let candidateCommand = inputStr.substr(countStr.length); let map = mappings[event.noremap ? "getDefault" : "get"](liberator.mode, candidateCommand, url); let candidates = mappings.getCandidates(liberator.mode, candidateCommand, url); if (candidates.length == 0 && !map) { map = this._input.pendingMap; this._input.pendingMap = null; if (map && map.arg) this._input.pendingArgMap = map; } // counts must be at the start of a complete mapping (10j -> go 10 lines down) if (countStr && !candidateCommand) { // no count for insert mode mappings if (!modes.mainMode.count || modes.mainMode.input) stop = false; else this._input.buffer = inputStr; } else if (this._input.pendingArgMap) { this._input.buffer = ""; let map = this._input.pendingArgMap; this._input.pendingArgMap = null; if (!isEscapeKey(key)) { if (modes.isReplaying && !this.waitForPageLoad()) return; map.execute(null, this._input.count, key); } } // only follow a map if there isn't a longer possible mapping // (allows you to do :map z yy, when zz is a longer mapping than z) else if (map && !event.skipmap && candidates.length == 0) { this._input.pendingMap = null; updateCount(countStr); this._input.buffer = ""; if (map.arg) { this._input.buffer = inputStr; this._input.pendingArgMap = map; } else if (this._input.pendingMotionMap) { if (!isEscapeKey(key)) this._input.pendingMotionMap.execute(candidateCommand, this._input.count, null); this._input.pendingMotionMap = null; } // no count support for these commands yet else if (map.motion) { this._input.pendingMotionMap = map; } else { if (modes.isReplaying && !this.waitForPageLoad()) throw killEvent(); let ret = map.execute(null, this._input.count); if (map.route && ret) stop = false; } } else if (candidates.length > 0 && !event.skipmap) { updateCount(countStr); this._input.pendingMap = map; this._input.buffer += key; } else { // if the key is neither a mapping nor the start of one // the mode checking is necessary so that things like g<esc> do not beep if (this._input.buffer != "" && !event.skipmap && (liberator.mode & (modes.INSERT | modes.COMMAND_LINE | modes.TEXTAREA))) events.feedkeys(this._input.buffer, { noremap: true, skipmap: true }); this._input.buffer = ""; this._input.pendingArgMap = null; this._input.pendingMotionMap = null; this._input.pendingMap = null; if (!isEscapeKey(key)) { // allow key to be passed to the host app if we can't handle it stop = false; if (liberator.mode == modes.COMMAND_LINE) { if (!(modes.extended & modes.INPUT_MULTILINE)) commandline.onEvent(event); // reroute event in command line mode } // beep on unrecognized keys /*else if (!modes.mainMode.input) liberator.beep();*/ } } if (stop) killEvent(); } catch (e) { if (e !== undefined) liberator.echoerr(e); } finally { let motionMap = (this._input.pendingMotionMap && this._input.pendingMotionMap.names[0]) || ""; if (!(modes.extended & modes.HINTS)) statusline.updateField("input", motionMap + this._input.buffer); } }, // this is need for sites like msn.com which focus the input field on keydown onKeyUpOrDown: function (event) { if (modes.passNextKey || modes.passAllKeys || Events.isInputElemFocused()) return; event.stopPropagation(); }, onPopupShown: function (event) { if (event.originalTarget.localName == "tooltip" || event.originalTarget.id == "liberator-visualbell") return; modes.isMenuShown = true; }, onPopupHidden: function () { // gContextMenu is set to NULL, when a context menu is closed if ((window.gContextMenu == null || !window.gContextMenu.shouldDisplay) && !this._activeMenubar) modes.isMenuShown = false; }, onDOMMenuBarActive: function () { this._activeMenubar = true; modes.isMenuShown = true; }, onDOMMenuBarInactive: function () { this._activeMenubar = false; modes.isMenuShown = false; }, onResize: function (event) { if (window.fullScreen != this._fullscreen) { this._fullscreen = window.fullScreen; liberator.triggerObserver("fullscreen", this._fullscreen); autocommands.trigger("Fullscreen", { state: this._fullscreen }); } } }, { isInputElemFocused: function () { let elem = liberator.focus; return ((elem instanceof HTMLInputElement && !/image/.test(elem.type)) || elem instanceof HTMLTextAreaElement || elem instanceof HTMLObjectElement || elem instanceof HTMLEmbedElement); } }, { commands: function () { commands.add(["delmac[ros]"], "Delete macros", function (args) { liberator.assert(!args.bang || !args.string, "Invalid argument"); if (args.bang) events.deleteMacros(); else if (args.string) events.deleteMacros(args.string); else liberator.echoerr("Argument required"); }, { bang: true, completer: function (context) completion.macro(context) }); commands.add(["mac[ros]"], "List all macros", function (args) { completion.listCompleter("macro", args[0]); }, { argCount: "?", completer: function (context) completion.macro(context) }); commands.add(["pl[ay]"], "Replay a recorded macro", function (args) { events.playMacro(args[0]); }, { argCount: "1", completer: function (context) completion.macro(context) }); }, mappings: function () { mappings.add(modes.all, ["<Esc>", "<C-[>"], "Focus content", function () { events.onEscape(); }); // add the ":" mapping in all but insert mode mappings mappings.add(modes.matchModes({ extended: false, input: false }), [":"], "Enter command line mode", function (count) { commandline.open("", count ? String(count) : "", modes.EX); }, {count: true}); // focus events mappings.add([modes.NORMAL, modes.PLAYER, modes.VISUAL, modes.CARET], ["<Tab>"], "Advance keyboard focus", function () { document.commandDispatcher.advanceFocus(); }); mappings.add([modes.NORMAL, modes.PLAYER, modes.VISUAL, modes.CARET, modes.INSERT, modes.TEXTAREA], ["<S-Tab>"], "Rewind keyboard focus", function () { document.commandDispatcher.rewindFocus(); }); mappings.add(modes.all, ["<S-Esc>", "<Insert>"], "Temporarily ignore all " + config.name + " key bindings", function () { modes.passAllKeys = !modes.passAllKeys; }); mappings.add([modes.NORMAL], ["i"], "Ignore next key and send it directly to the webpage", function () { modes.passNextKey = true; }); mappings.add(modes.all, ["<Nop>"], "Do nothing", function () { return; }); // macros mappings.add([modes.NORMAL, modes.PLAYER, modes.MESSAGE], ["q"], "Record a key sequence into a macro", function (arg) { events.startRecording(arg); }, { arg: true }); mappings.add([modes.NORMAL, modes.PLAYER, modes.MESSAGE], ["@"], "Play a macro", function (count, arg) { if (count < 1) count = 1; while (count-- && events.playMacro(arg)) ; }, { arg: true, count: true }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ // command names taken from: // http://developer.mozilla.org/en/docs/Editor_Embedding_Guide /** @instance editor */ const Editor = Module("editor", { requires: ["config", "abbreviations"], init: function () { // store our last search with f, F, t or T this._lastFindChar = null; this._lastFindCharFunc = null; this._visualMode = ""; }, line: function () { let line = 1; let text = Editor.getEditor().value; for (let i = 0; i < Editor.getEditor().selectionStart; i++) if (text[i] == "\n") line++; return line; }, col: function () { let col = 1; let text = Editor.getEditor().value; for (let i = 0; i < Editor.getEditor().selectionStart; i++) { col++; if (text[i] == "\n") col = 1; } return col; }, unselectText: function () { let e = Editor.getEditor(); if (e instanceof Window) { e.getSelection().collapseToStart(); } else { // A error occurs if the element has been removed when "e.selectionStart" is executed. try { if (e && e.selectionEnd) e.selectionEnd = e.selectionStart; } catch (e) {} } }, selectedText: function () { let e = Editor.getEditor(); if (e instanceof Window) return e.getSelection().toString(); let text = e.value; return text.substring(e.selectionStart, e.selectionEnd); }, pasteClipboard: function () { if (liberator.has("Windows")) { this.executeCommand("cmd_paste"); return; } // FIXME: #93 (<s-insert> in the bottom of a long textarea bounces up) let elem = liberator.focus; if (elem.setSelectionRange && util.readFromClipboard()) { // readFromClipboard would return 'undefined' if not checked // dunno about .setSelectionRange // This is a hacky fix - but it works. let curTop = elem.scrollTop; let curLeft = elem.scrollLeft; let rangeStart = elem.selectionStart; // caret position let rangeEnd = elem.selectionEnd; let tempStr1 = elem.value.substring(0, rangeStart); let tempStr2 = util.readFromClipboard(); let tempStr3 = elem.value.substring(rangeEnd); elem.value = tempStr1 + tempStr2 + tempStr3; elem.selectionStart = rangeStart + tempStr2.length; elem.selectionEnd = elem.selectionStart; elem.scrollTop = curTop; elem.scrollLeft = curLeft; } }, // count is optional, defaults to 1 executeCommand: function (cmd, count) { let controller = Editor.getController(cmd); if (!controller || !controller.supportsCommand(cmd) || !controller.isCommandEnabled(cmd)) { liberator.beep(); return false; } if (typeof count != "number" || count < 1) count = 1; let didCommand = false; while (count--) { // some commands need this try/catch workaround, because a cmd_charPrevious triggered // at the beginning of the textarea, would hang the doCommand() // good thing is, we need this code anyway for proper beeping try { controller.doCommand(cmd); didCommand = true; } catch (e) { if (!didCommand) liberator.beep(); return false; } } return true; }, // cmd = y, d, c // motion = b, 0, gg, G, etc. executeCommandWithMotion: function (cmd, motion, count) { if (typeof count != "number" || count < 1) count = 1; if (cmd == motion) { motion = "j"; count--; } modes.set(modes.VISUAL, modes.TEXTAREA); switch (motion) { case "j": this.executeCommand("cmd_beginLine", 1); this.executeCommand("cmd_selectLineNext", count + 1); break; case "k": this.executeCommand("cmd_beginLine", 1); this.executeCommand("cmd_lineNext", 1); this.executeCommand("cmd_selectLinePrevious", count + 1); break; case "h": this.executeCommand("cmd_selectCharPrevious", count); break; case "l": this.executeCommand("cmd_selectCharNext", count); break; case "e": case "w": this.executeCommand("cmd_selectWordNext", count); break; case "b": this.executeCommand("cmd_selectWordPrevious", count); break; case "0": case "^": this.executeCommand("cmd_selectBeginLine", 1); break; case "$": this.executeCommand("cmd_selectEndLine", 1); break; case "gg": this.executeCommand("cmd_endLine", 1); this.executeCommand("cmd_selectTop", 1); this.executeCommand("cmd_selectBeginLine", 1); break; case "G": this.executeCommand("cmd_beginLine", 1); this.executeCommand("cmd_selectBottom", 1); this.executeCommand("cmd_selectEndLine", 1); break; default: liberator.beep(); return false; } switch (cmd) { case "d": this.executeCommand("cmd_delete", 1); // need to reset the mode as the visual selection changes it modes.main = modes.TEXTAREA; break; case "c": this.executeCommand("cmd_delete", 1); modes.set(modes.INSERT, modes.TEXTAREA); break; case "y": this.executeCommand("cmd_copy", 1); this.unselectText(); break; default: liberator.beep(); return false; } return true; }, // This function will move/select up to given "pos" // Simple setSelectionRange() would be better, but we want to maintain the correct // order of selectionStart/End (a Gecko bug always makes selectionStart <= selectionEnd) // Use only for small movements! moveToPosition: function (pos, forward, select) { if (!select) { Editor.getEditor().setSelectionRange(pos, pos); return; } if (forward) { if (pos <= Editor.getEditor().selectionEnd || pos > Editor.getEditor().value.length) return; do { // TODO: test code for endless loops this.executeCommand("cmd_selectCharNext", 1); } while (Editor.getEditor().selectionEnd != pos); } else { if (pos >= Editor.getEditor().selectionStart || pos < 0) return; do { // TODO: test code for endless loops this.executeCommand("cmd_selectCharPrevious", 1); } while (Editor.getEditor().selectionStart != pos); } }, // returns the position of char findCharForward: function (ch, count) { if (!Editor.getEditor()) return -1; this._lastFindChar = ch; this._lastFindCharFunc = this.findCharForward; let text = Editor.getEditor().value; if (!typeof count == "number" || count < 1) count = 1; for (let i = Editor.getEditor().selectionEnd + 1; i < text.length; i++) { if (text[i] == "\n") break; if (text[i] == ch) count--; if (count == 0) return i + 1; // always position the cursor after the char } liberator.beep(); return -1; }, // returns the position of char findCharBackward: function (ch, count) { if (!Editor.getEditor()) return -1; this._lastFindChar = ch; this._lastFindCharFunc = this.findCharBackward; let text = Editor.getEditor().value; if (!typeof count == "number" || count < 1) count = 1; for (let i = Editor.getEditor().selectionStart - 1; i >= 0; i--) { if (text[i] == "\n") break; if (text[i] == ch) count--; if (count == 0) return i; } liberator.beep(); return -1; }, editFileExternally: function (path) { // TODO: save return value in v:shell_error let args = commands.parseArgs(options["editor"], [], [], "*", true); liberator.assert(args.length >= 1, "No editor specified"); args.push(path); io.run(io.expandPath(args.shift()), args, true); }, // TODO: clean up with 2 functions for textboxes and currentEditor? editFieldExternally: function (forceEditing, field) { if (!options["editor"]) return; let textBox = null, nsEditor = null; if (Editor.windowIsEditable()) { let win = document.commandDispatcher.focusedWindow; nsEditor = win.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIEditingSession) .getEditorForWindow(win); nsEditor instanceof Ci.nsIPlaintextEditor; nsEditor instanceof Ci.nsIHTMLEditor; } else { if (field !== undefined) { textBox = field; // if I reply 'yes', textBox.value == 'yes', so get the real value } else { textBox = liberator.focus; } } if (!forceEditing && textBox && textBox.type == "password") { commandline.input("Editing a password field externally will reveal the password. Would you like to continue? (yes/[no]): ", function (resp) { if (resp && resp.match(/^y(es)?$/i)) editor.editFieldExternally(true, textBox); }); return; } let text = ""; // XXX let isHTML = false; if (textBox) { text = textBox.value; } else if (nsEditor) { isHTML = nsEditor.flags & Ci.nsIPlaintextEditor.eEditorPlaintextMask ? false : true; text = isHTML ? nsEditor.outputToString("text/html", Ci.nsIDocumentEncoder.OutputBodyOnly) : nsEditor.outputToString("text/plain", Ci.nsIDocumentEncoder.OutpuFormatted); } else { return; } let elem, oldBg, tmpBg; try { let res = io.withTempFiles(function (tmpfile) { if (textBox) { textBox.setAttribute("readonly", "true"); elem = textBox; } else if (nsEditor) { nsEditor.flags |= Ci.nsIPlaintextEditor.eEditorReadonlyMask; elem = nsEditor.rootElement; } oldBg = elem.style.backgroundColor; tmpBg = "yellow"; elem.style.backgroundColor = "#bbbbbb"; if (!tmpfile.write(text)) throw Error("Input contains characters not valid in the current " + "file encoding"); let lastUpdate = Date.now(); function update (force) { if (force != true && tmpfile.lastModifiedTime <= lastUpdate) return; lastUpdate = Date.now(); let val = tmpfile.read(); if (textBox) textBox.value = val; else if (nsEditor) { let wholeDocRange = nsEditor.document.createRange(); let rootNode = nsEditor.rootElement.QueryInterface(Ci.nsIDOMNode); wholeDocRange.selectNodeContents(rootNode); nsEditor.selection.addRange(wholeDocRange); nsEditor.selection.deleteFromDocument(); if (isHTML) { let doc = nsEditor.document; let range = doc.createRange(); range.setStartAfter(doc.body); doc.body.appendChild(range.createContextualFragment(val)); } else { nsEditor.insertText(val); } let lastChild = rootNode.lastChild; while (lastChild.localName === "br" && (lastChild.hasAttribute("_moz_editor_bogus_node") || lastChild.hasAttribute("type"))) { nsEditor.rootElement.removeChild(lastChild) lastChild = rootNode.lastChild; } } } let timer = services.create("timer"); timer.initWithCallback({ notify: update }, 100, timer.TYPE_REPEATING_SLACK); try { this.editFileExternally(tmpfile.path); } finally { timer.cancel(); } update(true); }, this); if (res == false) throw Error("Couldn't create temporary file"); } catch (e) { // Errors are unlikely, and our error messages won't // likely be any more helpful than that given in the // exception. liberator.echoerr(e); tmpBg = "red"; } finally { if (textBox) textBox.removeAttribute("readonly"); else if (nsEditor) nsEditor.flags &= ~Ci.nsIPlaintextEditor.eEditorReadonlyMask; } // blink the textbox after returning if (elem) { let colors = [tmpBg, oldBg, tmpBg, oldBg]; (function () { elem.style.backgroundColor = colors.shift(); if (colors.length > 0) setTimeout(arguments.callee, 100); })(); } return; }, /** * Expands an abbreviation in the currently active textbox. * * @param {string} filter The mode filter. * @see #addAbbreviation */ expandAbbreviation: function (mode) { let textbox = Editor.getEditor(); if (!textbox) return false; let text = textbox.value; let currStart = textbox.selectionStart; let currEnd = textbox.selectionEnd; let foundWord = text.substring(0, currStart).replace(/.*[\s\n]/gm, '').match(RegExp('(' + abbreviations._match + ')$')); if (!foundWord) return true; foundWord = foundWord[0]; let abbrev = abbreviations.get(mode, foundWord); if (abbrev) { let len = foundWord.length; let abbrText = abbrev.text; text = text.substring(0, currStart - len) + abbrText + text.substring(currStart); textbox.value = text; textbox.selectionStart = currStart - len + abbrText.length; textbox.selectionEnd = currEnd - len + abbrText.length; } return true; }, getVisualMode: function() { return this._visualMode; }, setVisualMode: function(value) { this._visualMode = value; modes.show(); } }, { getEditor: function () { let e = liberator.focus; if (!e) { e = document.commandDispatcher.focusedWindow; if (!Editor.windowIsEditable(e)) return null; } else if (config.isComposeWindow && document.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_DISCONNECTED && window.GetCurrentEditor) { return window.GetCurrentEditor().document.defaultView; } return e; }, getController: function (cmd) { let ed = Editor.getEditor(); if (!ed || !ed.controllers) return null; return ed.controllers.getControllerForCommand(cmd || "cmd_beginLine"); }, windowIsEditable: function (win) { if (!win) win = document.commandDispatcher.focusedWindow; if (!(win instanceof Window)) return false; let editingSession = win .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIEditingSession); return editingSession.windowIsEditable(win) && win.document.body && util.computedStyle(win.document.body).getPropertyValue("-moz-user-modify") == "read-write"; } }, { mappings: function () { var myModes = [modes.INSERT, modes.COMMAND_LINE]; // add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXTAREA mode function addMovementMap(keys, hasCount, caretModeMethod, caretModeArg, textareaCommand, visualTextareaCommand) { let extraInfo = {}; if (hasCount) extraInfo.count = true; mappings.add([modes.CARET], keys, "", function (count) { if (typeof count != "number" || count < 1) count = 1; let controller = buffer.selectionController; while (count--) controller[caretModeMethod](caretModeArg, false); }, extraInfo); mappings.add([modes.VISUAL], keys, "", function (count) { if (typeof count != "number" || count < 1 || !hasCount) count = 1; let controller = buffer.selectionController; while (count--) { if (modes.extended & modes.TEXTAREA) { if (typeof visualTextareaCommand == "function") visualTextareaCommand(); else editor.executeCommand(visualTextareaCommand); } else controller[caretModeMethod](caretModeArg, true); } }, extraInfo); mappings.add([modes.TEXTAREA], keys, "", function (count) { if (typeof count != "number" || count < 1) count = 1; editor.executeCommand(textareaCommand, count); }, extraInfo); } // add mappings for commands like i,a,s,c,etc. in TEXTAREA mode function addBeginInsertModeMap(keys, commands) { mappings.add([modes.TEXTAREA], keys, "", function (count) { commands.forEach(function (cmd) editor.executeCommand(cmd, 1)); modes.set(modes.INSERT, modes.TEXTAREA); }); } function addMotionMap(key) { mappings.add([modes.TEXTAREA], [key], "Motion command", function (motion, count) { editor.executeCommandWithMotion(key, motion, count); }, { count: true, motion: true }); } function selectPreviousLine() { editor.executeCommand("cmd_selectLinePrevious"); if (editor.getVisualMode() == "LINE" && !editor.selectedText()) editor.executeCommand("cmd_selectLinePrevious"); } function selectNextLine() { editor.executeCommand("cmd_selectLineNext"); if (editor.getVisualMode() == "LINE" && !editor.selectedText()) editor.executeCommand("cmd_selectLineNext"); } // KEYS COUNT CARET TEXTAREA VISUAL_TEXTAREA addMovementMap(["k", "<Up>"], true, "lineMove", false, "cmd_linePrevious", selectPreviousLine); addMovementMap(["j", "<Down>", "<Return>"], true, "lineMove", true, "cmd_lineNext", selectNextLine); addMovementMap(["h", "<Left>", "<BS>"], true, "characterMove", false, "cmd_charPrevious", "cmd_selectCharPrevious"); addMovementMap(["l", "<Right>", "<Space>"], true, "characterMove", true, "cmd_charNext", "cmd_selectCharNext"); addMovementMap(["b", "B", "<C-Left>"], true, "wordMove", false, "cmd_wordPrevious", "cmd_selectWordPrevious"); addMovementMap(["w", "W", "e", "<C-Right>"], true, "wordMove", true, "cmd_wordNext", "cmd_selectWordNext"); addMovementMap(["<C-f>", "<PageDown>"], true, "pageMove", true, "cmd_movePageDown", "cmd_selectNextPage"); addMovementMap(["<C-b>", "<PageUp>"], true, "pageMove", false, "cmd_movePageUp", "cmd_selectPreviousPage"); addMovementMap(["gg", "<C-Home>"], false, "completeMove", false, "cmd_moveTop", "cmd_selectTop"); addMovementMap(["G", "<C-End>"], false, "completeMove", true, "cmd_moveBottom", "cmd_selectBottom"); addMovementMap(["0", "^", "<Home>"], false, "intraLineMove", false, "cmd_beginLine", "cmd_selectBeginLine"); addMovementMap(["$", "<End>"], false, "intraLineMove", true, "cmd_endLine" , "cmd_selectEndLine" ); addBeginInsertModeMap(["i", "<Insert>"], []); addBeginInsertModeMap(["a"], ["cmd_charNext"]); addBeginInsertModeMap(["I", "gI"], ["cmd_beginLine"]); addBeginInsertModeMap(["A"], ["cmd_endLine"]); addBeginInsertModeMap(["s"], ["cmd_deleteCharForward"]); addBeginInsertModeMap(["S"], ["cmd_deleteToEndOfLine", "cmd_deleteToBeginningOfLine"]); addBeginInsertModeMap(["C"], ["cmd_deleteToEndOfLine"]); addMotionMap("d"); // delete addMotionMap("c"); // change addMotionMap("y"); // yank // insert mode mappings mappings.add([modes.INSERT], ["<C-w>"], "Delete previous word", function () { editor.executeCommand("cmd_deleteWordBackward", 1); }); mappings.add([modes.COMMAND_LINE], ["<C-w>"], "Delete previous word", function () { // XXX Error occurs on doCommand, when completion's preview is available. if (commandline._completions) commandline._completions.previewClear(); editor.executeCommand("cmd_deleteWordBackward", 1); }); mappings.add(myModes, ["<C-u>"], "Delete until beginning of current line", function () { // broken in FF3, deletes the whole line: // editor.executeCommand("cmd_deleteToBeginningOfLine", 1); editor.executeCommand("cmd_selectBeginLine", 1); editor.executeCommand("cmd_delete", 1); }); mappings.add(myModes, ["<C-k>"], "Delete until end of current line", function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); }); mappings.add(myModes, ["<C-a>"], "Move cursor to beginning of current line", function () { editor.executeCommand("cmd_beginLine", 1); }); mappings.add(myModes, ["<C-e>"], "Move cursor to end of current line", function () { editor.executeCommand("cmd_endLine", 1); }); mappings.add(myModes, ["<C-h>"], "Delete character to the left", function () { editor.executeCommand("cmd_deleteCharBackward", 1); }); mappings.add(myModes, ["<C-d>"], "Delete character to the right", function () { editor.executeCommand("cmd_deleteCharForward", 1); }); /*mappings.add(myModes, ["<C-Home>"], "Move cursor to beginning of text field", function () { editor.executeCommand("cmd_moveTop", 1); }); mappings.add(myModes, ["<C-End>"], "Move cursor to end of text field", function () { editor.executeCommand("cmd_moveBottom", 1); });*/ mappings.add(myModes, ["<S-Insert>"], "Insert clipboard/selection", function () { editor.pasteClipboard(); }); mappings.add(modes.getCharModes("i"), ["<C-i>"], "Edit text field with an external editor", function () { editor.editFieldExternally(); }); mappings.add([modes.INSERT], ["<C-t>"], "Edit text field in Vi mode", function () { liberator.mode = modes.TEXTAREA; }); mappings.add([modes.INSERT], ["<Space>", "<Return>"], "Expand insert mode abbreviation", function () { editor.expandAbbreviation(modes.INSERT); }, { route: true }); mappings.add([modes.INSERT], ["<Tab>"], "Expand insert mode abbreviation", function () { editor.expandAbbreviation(modes.INSERT); document.commandDispatcher.advanceFocus(); }); mappings.add([modes.INSERT], ["<C-]>", "<C-5>"], "Expand insert mode abbreviation", function () { editor.expandAbbreviation(modes.INSERT); }); // textarea mode mappings.add([modes.TEXTAREA], ["u"], "Undo", function (count) { editor.executeCommand("cmd_undo", count); liberator.mode = modes.TEXTAREA; }, { count: true }); mappings.add([modes.TEXTAREA], ["<C-r>"], "Redo", function (count) { editor.executeCommand("cmd_redo", count); liberator.mode = modes.TEXTAREA; }, { count: true }); mappings.add([modes.TEXTAREA], ["D"], "Delete the characters under the cursor until the end of the line", function () { editor.executeCommand("cmd_deleteToEndOfLine"); }); mappings.add([modes.TEXTAREA], ["o"], "Open line below current", function (count) { editor.executeCommand("cmd_endLine", 1); modes.set(modes.INSERT, modes.TEXTAREA); events.feedkeys("<Return>"); }); mappings.add([modes.TEXTAREA], ["O"], "Open line above current", function (count) { editor.executeCommand("cmd_beginLine", 1); modes.set(modes.INSERT, modes.TEXTAREA); events.feedkeys("<Return>"); editor.executeCommand("cmd_linePrevious", 1); }); mappings.add([modes.TEXTAREA], ["X"], "Delete character to the left", function (count) { editor.executeCommand("cmd_deleteCharBackward", count); }, { count: true }); mappings.add([modes.TEXTAREA], ["x"], "Delete character to the right", function (count) { editor.executeCommand("cmd_deleteCharForward", count); }, { count: true }); // visual mode mappings.add([modes.CARET, modes.TEXTAREA], ["v"], "Start visual mode", function (count) { modes.set(modes.VISUAL, liberator.mode); editor.setVisualMode(""); }); mappings.add([modes.VISUAL], ["v"], "End visual mode", function (count) { events.onEscape(); }); mappings.add([modes.TEXTAREA], ["V"], "Start visual line mode", function (count) { //modes.set(modes.VISUAL, modes.TEXTAREA | modes.LINE); modes.set(modes.VISUAL, liberator.mode); editor.setVisualMode("LINE"); editor.executeCommand("cmd_beginLine", 1); editor.executeCommand("cmd_selectLineNext", 1); }); mappings.add([modes.VISUAL], ["c", "s"], "Change selected text", function (count) { liberator.assert(modes.extended & modes.TEXTAREA); editor.executeCommand("cmd_cut"); modes.set(modes.INSERT, modes.TEXTAREA); }); mappings.add([modes.VISUAL], ["d"], "Delete selected text", function (count) { if (modes.extended & modes.TEXTAREA) { editor.executeCommand("cmd_cut"); modes.set(modes.TEXTAREA); } else liberator.beep(); }); mappings.add([modes.VISUAL], ["y"], "Yank selected text", function (count) { if (modes.extended & modes.TEXTAREA) { editor.executeCommand("cmd_copy"); modes.set(modes.TEXTAREA); } else { util.copyToClipboard(buffer.getCurrentWord(), true); } }); mappings.add([modes.VISUAL, modes.TEXTAREA], ["p"], "Paste clipboard contents", function (count) { liberator.assert(!(modes.extended & modes.CARET)); if (!count) count = 1; while (count--) editor.executeCommand("cmd_paste"); liberator.mode = modes.TEXTAREA; }); // finding characters mappings.add([modes.TEXTAREA, modes.VISUAL], ["f"], "Move to a character on the current line after the cursor", function (count, arg) { let pos = editor.findCharForward(arg, count); if (pos >= 0) editor.moveToPosition(pos, true, liberator.mode == modes.VISUAL); }, { arg: true, count: true }); mappings.add([modes.TEXTAREA, modes.VISUAL], ["F"], "Move to a charater on the current line before the cursor", function (count, arg) { let pos = editor.findCharBackward(arg, count); if (pos >= 0) editor.moveToPosition(pos, false, liberator.mode == modes.VISUAL); }, { arg: true, count: true }); mappings.add([modes.TEXTAREA, modes.VISUAL], ["t"], "Move before a character on the current line", function (count, arg) { let pos = editor.findCharForward(arg, count); if (pos >= 0) editor.moveToPosition(pos - 1, true, liberator.mode == modes.VISUAL); }, { arg: true, count: true }); mappings.add([modes.TEXTAREA, modes.VISUAL], ["T"], "Move before a character on the current line, backwards", function (count, arg) { let pos = editor.findCharBackward(arg, count); if (pos >= 0) editor.moveToPosition(pos + 1, false, liberator.mode == modes.VISUAL); }, { arg: true, count: true }); // textarea and visual mode mappings.add([modes.TEXTAREA, modes.VISUAL], ["~"], "Switch case of the character under the cursor and move the cursor to the right", function (count) { if (modes.main == modes.VISUAL) count = Editor.getEditor().selectionEnd - Editor.getEditor().selectionStart; if (typeof count != "number" || count < 1) count = 1; while (count-- > 0) { let text = Editor.getEditor().value; let pos = Editor.getEditor().selectionStart; liberator.assert(pos < text.length); let chr = text[pos]; Editor.getEditor().value = text.substring(0, pos) + (chr == chr.toLocaleLowerCase() ? chr.toLocaleUpperCase() : chr.toLocaleLowerCase()) + text.substring(pos + 1); editor.moveToPosition(pos + 1, true, false); } modes.set(modes.TEXTAREA); }, { count: true }); }, options: function () { options.add(["editor"], "Set the external text editor", "string", "gvim -f"); options.add(["insertmode", "im"], "Use Insert mode as the default for text areas", "boolean", true); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ // TODO: proper backwards search - implement our own component? // : implement our own highlighter? // : <ESC> should cancel search highlighting in 'incsearch' mode and jump // back to the presearch page location - can probably use the same // solution as marks // : 'linksearch' searches should highlight link matches only // : changing any search settings should also update the search state including highlighting // : incremental searches shouldn't permanently update search modifiers // // TODO: Clean up this rat's nest. --Kris /** * @instance finder */ const Finder = Module("finder", { requires: ["config"], init: function () { const self = this; this._found = false; // true if the last search was successful this._backwards = false; // currently searching backwards this._searchString = ""; // current search string (without modifiers) this._searchPattern = ""; // current search string (includes modifiers) this._lastSearchPattern = ""; // the last searched pattern (includes modifiers) this._lastSearchString = ""; // the last searched string (without modifiers) this._lastSearchBackwards = false; // like "backwards", but for the last search, so if you cancel a search with <esc> this is not set this._caseSensitive = false; // search string is case sensitive this._linksOnly = false; // search is limited to link text only }, // set searchString, searchPattern, caseSensitive, linksOnly _processUserPattern: function (pattern) { //// strip off pattern terminator and offset //if (backwards) // pattern = pattern.replace(/\?.*/, ""); //else // pattern = pattern.replace(/\/.*/, ""); this._searchPattern = pattern; // links only search - \l wins if both modifiers specified if (/\\l/.test(pattern)) this._linksOnly = true; else if (/\L/.test(pattern)) this._linksOnly = false; else if (options["linksearch"]) this._linksOnly = true; else this._linksOnly = false; // strip links-only modifiers pattern = pattern.replace(/(\\)?\\[lL]/g, function ($0, $1) { return $1 ? $0 : ""; }); // case sensitivity - \c wins if both modifiers specified if (/\c/.test(pattern)) this._caseSensitive = false; else if (/\C/.test(pattern)) this._caseSensitive = true; else if (options["ignorecase"] && options["smartcase"] && /[A-Z]/.test(pattern)) this._caseSensitive = true; else if (options["ignorecase"]) this._caseSensitive = false; else this._caseSensitive = true; // strip case-sensitive modifiers pattern = pattern.replace(/(\\)?\\[cC]/g, function ($0, $1) { return $1 ? $0 : ""; }); // remove any modifier escape \ pattern = pattern.replace(/\\(\\[cClL])/g, "$1"); this._searchString = pattern; }, /** * Called when the search dialog is requested. * * @param {number} mode The search mode, either modes.SEARCH_FORWARD or * modes.SEARCH_BACKWARD. * @default modes.SEARCH_FORWARD */ openPrompt: function (mode) { this._backwards = mode == modes.SEARCH_BACKWARD; //commandline.open(this._backwards ? "Find backwards" : "Find", "", mode); commandline.input(this._backwards ? "Find backwards" : "Find", this.closure.onSubmit, { onChange: function() { if (options["incsearch"]) finder.find(commandline.command) } }); //modes.extended = mode; // TODO: focus the top of the currently visible screen }, // TODO: backwards seems impossible i fear /** * Searches the current buffer for <b>str</b>. * * @param {string} str The string to find. */ find: function (str) { let fastFind = config.browser.fastFind; this._processUserPattern(str); fastFind.caseSensitive = this._caseSensitive; let result = fastFind.find(this._searchString, this._linksOnly); this._displayFindResult(result, this._backwards); }, /** * Searches the current buffer again for the most recently used search * string. * * @param {boolean} reverse Whether to search forwards or backwards. * @default false */ findAgain: function (reverse) { // This hack is needed to make n/N work with the correct string, if // we typed /foo<esc> after the original search. Since searchString is // readonly we have to call find() again to update it. if (config.browser.fastFind.searchString != this._lastSearchString) this.find(this._lastSearchString); let backwards = reverse ? !this._lastSearchBackwards : this._lastSearchBackwards; let result = config.browser.fastFind.findAgain(backwards, this._linksOnly); this._displayFindResult(result, backwards); }, _displayFindResult: function(result, backwards) { if (result == Ci.nsITypeAheadFind.FIND_NOTFOUND) { liberator.echoerr("Pattern not found: " + this._searchString, commandline.FORCE_SINGLELINE); } else if (result == Ci.nsITypeAheadFind.FIND_WRAPPED) { let msg = backwards ? "Search hit TOP, continuing at BOTTOM" : "Search hit BOTTOM, continuing at TOP"; commandline.echo(msg, commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES | commandline.FORCE_SINGLELINE); } else { liberator.echomsg("Found pattern: " + this._searchString); } }, /** * Called when the user types a key in the search dialog. Triggers a * search attempt if 'incsearch' is set. * * @param {string} str The search string. */ /*onKeyPress: function (str) { if (options["incsearch"]) this.find(str); },*/ /** * Called when the <Enter> key is pressed to trigger a search. * * @param {string} str The search string. * @param {boolean} forcedBackward Whether to search forwards or * backwards. This overrides the direction set in * (@link #openPrompt). * @default false */ onSubmit: function (str, forcedBackward) { if (typeof forcedBackward === "boolean") this._backwards = forcedBackward; if (str) var pattern = str; else { liberator.assert(this._lastSearchPattern, "No previous search pattern"); pattern = this._lastSearchPattern; } this.clear(); // liberator.log('inc: ' + options["incsearch"] + ' sea:' + this._searchPattern + ' pat:' + pattern); if (!options["incsearch"] /*|| !str || !this._found */|| this._searchPattern != pattern) { // prevent any current match from matching again if (!window.content.getSelection().isCollapsed) window.content.getSelection().getRangeAt(0).collapse(this._backwards); this.find(pattern); } // focus links after searching, so the user can just hit <Enter> another time to follow the link // This has to be done async, because the mode reset after onSubmit would // clear the focus let elem = config.browser.fastFind.foundLink; this.setTimeout(function() { if (elem) elem.focus(); // fm.moveFocus(elem.ownerDocument.defaultView, null, Ci.nsIFocusManager.MOVEFOCUS_CARET, Ci.nsIFocusManager.FLAG_NOSCROLL);*/ }, 0); this._lastSearchBackwards = this._backwards; this._lastSearchPattern = pattern; this._lastSearchString = this._searchString; // TODO: move to find() when reverse incremental searching is kludged in // need to find again for reverse searching if (this._backwards) this.setTimeout(function () { this.findAgain(false); }, 0); if (options["hlsearch"]) this.highlight(this._searchString); }, /** * Highlights all occurances of <b>str</b> in the buffer. * * @param {string} str The string to highlight. */ highlight: function (str) { // FIXME: Thunderbird incompatible if (config.name == "Muttator") return; if (window.gFindBar) { window.gFindBar._setCaseSensitivity(this._caseSensitive); window.gFindBar._highlightDoc(false); window.gFindBar._highlightDoc(true, str); } }, /** * Clears all search highlighting. */ clear: function () { // FIXME: Thunderbird incompatible if (config.name == "Muttator") return; if (window.gFindBar) window.gFindBar._highlightDoc(false); } }, { }, { commands: function () { // TODO: Remove in favor of :set nohlsearch? commands.add(["noh[lsearch]"], "Remove the search highlighting", function () { finder.clear(); }, { argCount: "0" }); }, mappings: function () { var myModes = config.browserModes; myModes = myModes.concat([modes.CARET]); mappings.add(myModes, ["/"], "Search forward for a pattern", function () { finder.openPrompt(modes.SEARCH_FORWARD); }); mappings.add(myModes, ["?"], "Search backwards for a pattern", function () { finder.openPrompt(modes.SEARCH_BACKWARD); }); mappings.add(myModes, ["n"], "Find next", function () { finder.findAgain(false); }); mappings.add(myModes, ["N"], "Find previous", function () { finder.findAgain(true); }); mappings.add(myModes.concat([modes.CARET, modes.TEXTAREA]), ["*"], "Find word under cursor", function () { this._found = false; finder.onSubmit(buffer.getCurrentWord(), false); }); mappings.add(myModes.concat([modes.CARET, modes.TEXTAREA]), ["#"], "Find word under cursor backwards", function () { this._found = false; finder.onSubmit(buffer.getCurrentWord(), true); }); }, options: function () { options.add(["hlsearch", "hls"], "Highlight previous search pattern matches", "boolean", true, { setter: function (value) { try { if (value) finder.highlight(); else finder.clear(); } catch (e) {} return value; } }); options.add(["ignorecase", "ic"], "Ignore case in search patterns", "boolean", true); options.add(["incsearch", "is"], "Show where the search pattern matches as it is typed", "boolean", true); options.add(["linksearch", "lks"], "Limit the search to hyperlink text", "boolean", false); options.add(["smartcase", "scs"], "Override the 'ignorecase' option if the pattern contains uppercase characters", "boolean", true); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ const Modes = Module("modes", { requires: ["config", "util"], init: function () { this._main = 1; // NORMAL this._extended = 0; // NONE this._lastShown = null; this._passNextKey = false; this._passAllKeys = false; this._passKeysExceptions = null; // Which keys are still allowed in ignore mode. ONLY set when an :ignorekeys LocationChange triggered it this._isRecording = false; this._isReplaying = false; // playing a macro this._modeStack = []; this._mainModes = [this.NONE]; this._lastMode = 0; this._modeMap = {}; // main modes, only one should ever be active this.addMode("NORMAL", { char: "n", display: -1 }); this.addMode("INSERT", { char: "i", input: true }); this.addMode("VISUAL", { char: "v", display: function () "VISUAL" + (editor.getVisualMode() ? " " + editor.getVisualMode() : "") }); this.addMode("COMMAND_LINE", { char: "c", input: true, display: -1 }); this.addMode("CARET"); // text cursor is visible this.addMode("TEXTAREA", { char: "i" }); this.addMode("EMBED", { input: true }); this.addMode("CUSTOM", { display: function () plugins.mode }); // this._extended modes, can include multiple modes, and even main modes this.addMode("EX", true); this.addMode("HINTS", true); this.addMode("INPUT_MULTILINE", true); this.addMode("OUTPUT_MULTILINE", true); this.addMode("SEARCH_FORWARD", true); this.addMode("SEARCH_BACKWARD", true); this.addMode("SEARCH_VIEW_FORWARD", true); this.addMode("SEARCH_VIEW_BACKWARD", true); this.addMode("LINE", true); // linewise visual mode this.addMode("PROMPT", true); config.modes.forEach(function (mode) { this.addMode.apply(this, mode); }, this); }, _getModeMessage: function () { if (this._passNextKey) { return "IGNORE"; } else if (this._passAllKeys) { if (!this._passKeysExceptions || this._passKeysExceptions.length == 0) return "IGNORE ALL KEYS (Press <S-Esc> or <Insert> to exit)"; else return "IGNORE MOST KEYS (All except " + this._passKeysExceptions + ")"; } // when recording or replaying a macro if (modes.isRecording) return "RECORDING"; else if (modes.isReplaying) return "REPLAYING"; if (this._main in this._modeMap && typeof this._modeMap[this._main].display === "function") return this._modeMap[this._main].display(); return ""; // default mode message }, // NOTE: Pay attention that you don't run into endless loops // Usually you should only indicate to leave a special mode like HINTS // by calling modes.reset() and adding the stuff which is needed // for its cleanup here _handleModeChange: function (oldMode, newMode, oldExtended) { switch (oldMode) { case modes.TEXTAREA: case modes.INSERT: editor.unselectText(); break; case modes.VISUAL: if (newMode == modes.CARET) { try { // clear any selection made; a simple if (selection) does not work let selection = Buffer.focusedWindow.getSelection(); selection.collapseToStart(); } catch (e) {} } else editor.unselectText(); break; case modes.CUSTOM: plugins.stop(); break; case modes.COMMAND_LINE: // clean up for HINT mode if (oldExtended & modes.HINTS) hints.hide(); commandline.close(); break; } if (newMode == modes.NORMAL) { // disable caret mode when we want to switch to normal mode if (options.getPref("accessibility.browsewithcaret")) options.setPref("accessibility.browsewithcaret", false); if (oldMode == modes.COMMAND_LINE) liberator.focusContent(false); // when coming from the commandline, we might want to keep the focus (after a Search, e.g.) else liberator.focusContent(true); // unfocus textareas etc. } else if (newMode === modes.COMPOSE) { services.get("focus").clearFocus(window); } }, NONE: 0, __iterator__: function () util.Array.itervalues(this.all), get all() this._mainModes.slice(), get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)), get mainMode() this._modeMap[this._main], addMode: function (name, extended, options) { let disp = name.replace("_", " ", "g"); this[name] = 1 << this._lastMode++; if (typeof extended == "object") { options = extended; extended = false; } this._modeMap[name] = this._modeMap[this[name]] = update({ extended: extended, count: true, input: false, mask: this[name], name: name, disp: disp }, options); this._modeMap[name].display = this._modeMap[name].display || function () disp; if (!extended) this._mainModes.push(this[name]); if ("mappings" in modules) mappings.addMode(this[name]); }, getMode: function (name) this._modeMap[name], getCharModes: function (chr) [m for (m in values(this._modeMap)) if (m.char == chr)], matchModes: function (obj) [m for (m in values(this._modeMap)) if (array(keys(obj)).every(function (k) obj[k] == (m[k] || false)))], // show the current mode string in the command line show: function () { if (options["showmode"]) commandline.setModeMessage(this._getModeMessage()); }, // add/remove always work on the this._extended mode only add: function (mode) { this._extended |= mode; this.show(); }, // helper function to set both modes in one go // if silent == true, you also need to take care of the mode handling changes yourself set: function (mainMode, extendedMode, silent, stack) { silent = (silent || this._main == mainMode && this._extended == extendedMode); // if a this._main mode is set, the this._extended is always cleared let oldMain = this._main, oldExtended = this._extended; if (typeof extendedMode === "number") this._extended = extendedMode; if (typeof mainMode === "number") { this._main = mainMode; if (!extendedMode) this._extended = modes.NONE; if (this._main != oldMain) { this._handleModeChange(oldMain, mainMode, oldExtended); liberator.triggerObserver("modeChange", [oldMain, oldExtended], [this._main, this._extended]); // liberator.log("Changing mode from " + oldMain + "/" + oldExtended + " to " + this._main + "/" + this._extended + "(" + this._getModeMessage() + ")"); if (!silent) this.show(); } } }, // TODO: Deprecate this in favor of addMode? --Kris // Ya --djk setCustomMode: function (modestr, oneventfunc, stopfunc) { // TODO this.plugin[id]... ('id' maybe submode or what..) plugins.mode = modestr; plugins.onEvent = oneventfunc; plugins.stop = stopfunc; }, passAllKeysExceptSome: function passAllKeysExceptSome(exceptions) { this._passAllKeys = true; this._passKeysExceptions = exceptions || []; this.show(); }, isKeyIgnored: function isKeyIgnored(key) { if (modes.passNextKey) return true; if (modes.passAllKeys) { // handle Escape-all-keys mode (Shift-Esc) // Respect "unignored" keys if (modes._passKeysExceptions == null || modes._passKeysExceptions.indexOf(key) < 0) return true; else return false; // TODO: "unignore" option // TODO: config.ignoreKeys support or remove config.ignoreKeys } return false; }, // keeps recording state reset: function (silent) { this._modeStack = []; if (config.isComposeWindow) this.set(modes.COMPOSE, modes.NONE, silent); else this.set(modes.NORMAL, modes.NONE, silent); }, remove: function (mode) { if (this._extended & mode) { this._extended &= ~mode; this.show(); } }, isMenuShown: false, // when a popup menu is active get passNextKey() this._passNextKey, set passNextKey(value) { this._passNextKey = value; this.show(); }, get passAllKeys() this._passAllKeys, set passAllKeys(value) { this._passAllKeys = value; this._passKeysExceptions = null; this.show(); }, get isRecording() this._isRecording, set isRecording(value) { this._isRecording = value; this.show(); }, get isReplaying() this._isReplaying, set isReplaying(value) { this._isReplaying = value; this.show(); }, get main() this._main, set main(value) { this.set(value); }, get extended() this._extended, set extended(value) { this.set(null, value); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2010 by anekos <anekos@snca.net> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ const Abbreviation = Class("Abbreviation", { init: function (modes, lhs, rhs) { this.modes = modes; this.lhs = lhs; this.rhs = rhs; }, equals: function (other) { return this.lhs == other.lhs && this.rhs == other.rhs; }, modesEqual: function (modes) { return (modes.length === this.modes.length) && (this.modes.every(function (m1) modes.some(function (m2) m1 === m2))); }, get text() (this.rhs instanceof Function ? this.rhs() : this.rhs).toString(), inMode: function (mode) { return this.modes.some(function (_mode) _mode == mode); }, inModes: function (modes) { let self = this; return modes.some(function (mode) self.inMode(mode)); }, removeMode: function (mode) { this.modes = this.modes.filter(function (m) m != mode); }, get modeChar() Abbreviation.modeChar(this.modes) }, { modeChar: function (_modes) { let result = ""; for ([, mode] in Iterator(_modes)) result += modes.getMode(mode).char; if (/^(ic|ci)$/.test(result)) result = "!"; return result; } }); const Abbreviations = Module("abbreviations", { requires: ["config", "modes"], init: function () { this.abbrevs = {}; // (summarized from Vim's ":help abbreviations") // // There are three types of abbreviations. // // full-id: Consists entirely of keyword characters. // ("foo", "g3", "-1") // // end-id: Ends in a keyword character, but all other // are not keyword characters. // ("#i", "..f", "$/7") // // non-id: Ends in a non-keyword character, but the // others can be of any type other than space // and tab. // ("def#", "4/7$") // // Example strings that cannot be abbreviations: // "a.b", "#def", "a b", "_$r" // // For now, a keyword character is anything except for \s, ", or ' // (i.e., whitespace and quotes). In Vim, a keyword character is // specified by the 'iskeyword' setting and is a much less inclusive // list. // // TODO: Make keyword definition closer to Vim's default keyword // definition (which differs across platforms). let nonkw = "\\s\"'"; let keyword = "[^" + nonkw + "]"; let nonkeyword = "[" + nonkw + "]"; let fullId = keyword + "+"; let endId = nonkeyword + "+" + keyword; let nonId = "\\S*" + nonkeyword; // Used in add and expand this._match = fullId + "|" + endId + "|" + nonId; }, /** * Adds a new abbreviation. * * @param {Abbreviation} * @returns {Abbreviation} */ add: function (abbr) { if (!(abbr instanceof Abbreviation)) abbr = Abbreviation.apply(null, arguments); for (let mode of abbr.modes) { if (!this.abbrevs[mode]) this.abbrevs[mode] = {}; this.abbrevs[mode][abbr.lhs] = abbr; } return abbr; }, /** * Returns matched abbreviation. * * @param {mode} * @param {string} */ get: function (mode, lhs) { let abbrevs = this.abbrevs[mode]; return abbrevs && abbrevs.hasOwnProperty(lhs) && abbrevs.propertyIsEnumerable(lhs) && abbrevs[lhs]; }, /** * The list of the abbreviations merged from each modes. */ get merged() { let result = []; let lhses = util.Array.uniq([lhs for ([, mabbrevs] in Iterator(this.abbrevs)) for (lhs of Object.keys(mabbrevs))].sort()); for (let lhs of lhses) { let exists = {}; for (let [, mabbrevs] in Iterator(this.abbrevs)) { let abbr = mabbrevs[lhs]; if (abbr && !exists[abbr.rhs]) { exists[abbr.rhs] = 1; result.push(abbr); } } } return result; }, /** * Lists all abbreviations matching <b>modes</b> and <b>lhs</b>. * * @param {Array} list of mode. * @param {string} lhs The LHS of the abbreviation. */ list: function (modes, lhs) { let list = this.merged.filter(function (abbr) (abbr.inModes(modes) && abbr.lhs.startsWith(lhs))); if (!list.length) liberator.echomsg("No abbreviations found"); else if (list.length == 1) { let head = list[0]; liberator.echo(head.modeChar + " " + head.lhs + " " + head.rhs, commandline.FORCE_SINGLELINE); // 2 spaces, 3 spaces } else { list = list.map(function (abbr) [abbr.modeChar, abbr.lhs, abbr.rhs]); list = template.tabular([{ header: "Mode", style: "padding-left: 1ex"}, { header: "Abbreviation", highlight: "Mapping"}, "Expanded text"], list); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } }, /** * Remove the specified abbreviations. * * @param {Array} list of mode. * @param {string} lhs of abbreviation. * @returns {boolean} did the deleted abbreviation exist? */ remove: function (modes, lhs) { let result = false; for (let mode of modes) { if ((mode in this.abbrevs) && (lhs in this.abbrevs[mode])) { result = true; this.abbrevs[mode][lhs].removeMode(mode); delete this.abbrevs[mode][lhs]; } } return result; }, /** * Removes all abbreviations specified <b>modes<b>. * * @param {Array} list of mode. */ removeAll: function (modes) { for (let mode of modes) { if (!(mode in this.abbrevs)) return; for (let [, abbr] in this.abbrevs[mode]) abbr.removeMode(mode); delete this.abbrevs[mode]; } } }, { }, { completion: function () { // TODO: shouldn't all of these have a standard signature (context, args, ...)? --djk completion.abbreviation = function abbreviation(context, args, modes) { if (args.completeArg == 0) { let abbrevs = abbreviations.merged.filter(function (abbr) abbr.inModes(modes)); context.completions = [[abbr.lhs, abbr.rhs] for (abbr of abbrevs)]; } }; }, commands: function () { function addAbbreviationCommands(modes, ch, modeDescription) { function splitArg (arg) { return arg.match(RegExp("^\\s*($|" + abbreviations._match + ")(?:\\s*$|\\s+(.*))")); } modeDescription = modeDescription ? " in " + modeDescription + " mode" : ""; commands.add([ch ? ch + "a[bbrev]" : "ab[breviate]"], "Abbreviate a key sequence" + modeDescription, function (args) { let matches = splitArg(args.literalArg); liberator.assert(matches, "Invalid argument: " + args.literalArg); let [, lhs, rhs] = matches; if (rhs) { if (args["-javascript"]) { let expr = rhs; rhs = function () liberator.eval(expr); rhs.toString = function () expr; } abbreviations.add(modes, lhs, rhs); } else { abbreviations.list(modes, lhs || ""); } }, { options: [[["-javascript", "-j"], commands.OPTION_NOARG, null]], completer: function (context, args) { let [, lhs, rhs] = splitArg(args.literalArg); if (rhs && args["-javascript"]) return completion.javascript(context); completion.abbreviation(context, args, modes) }, literal: 0, serial: function () [ { command: this.name, arguments: [abbr.lhs], literalArg: abbr.rhs, options: abbr.rhs instanceof Function ? {"-javascript": null} : {} } for ([, abbr] in Iterator(abbreviations.merged)) if (abbr.modesEqual(modes)) ] }); commands.add([ch ? ch + "una[bbrev]" : "una[bbreviate]"], "Remove an abbreviation" + modeDescription, function (args) { let lhs = args.literalArg; if (!lhs) return liberator.echoerr("Invalid argument"); if (!abbreviations.remove(modes, lhs)) return liberator.echoerr("No such abbreviation: " + lhs); }, { argCount: "1", completer: function (context, args) completion.abbreviation(context, args, modes), literal: 0 }); commands.add([ch + "abc[lear]"], "Remove all abbreviations" + modeDescription, function () { abbreviations.removeAll(modes); }, { argCount: "0" }); } addAbbreviationCommands([modes.INSERT, modes.COMMAND_LINE], "", ""); addAbbreviationCommands([modes.INSERT], "i", "insert"); addAbbreviationCommands([modes.COMMAND_LINE], "c", "command line"); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ Cu.import("resource://gre/modules/XPCOMUtils.jsm", modules); Cu.import("resource://gre/modules/AddonManager.jsm") const plugins = { __proto__: modules }; const userContext = { __proto__: modules }; const EVAL_ERROR = "__liberator_eval_error"; const EVAL_RESULT = "__liberator_eval_result"; const EVAL_STRING = "__liberator_eval_string"; // Move elsewhere? const Storage = Module("storage", { requires: ["services"], init: function () { Cu.import("resource://liberator/storage.jsm", this); modules.Timer = this.Timer; // Fix me, please. try { let infoPath = services.create("file"); infoPath.initWithPath(File.expandPath(IO.runtimePath.replace(/,.*/, ""))); infoPath.append("info"); infoPath.append(liberator.profileName); this.storage.infoPath = infoPath; } catch (e) {} return this.storage; } }); function Runnable(self, func, args) { return { QueryInterface: XPCOMUtils.generateQI([Ci.nsIRunnable]), run: function () { func.apply(self, args); } }; } const FailedAssertion = Class("FailedAssertion", Error, { init: function (message) { this.message = message; } }); const Liberator = Module("liberator", { requires: ["config", "services"], init: function () { window.liberator = this; this.observers = {}; this.modules = modules; // NOTE: services.get("profile").selectedProfile.name doesn't return // what you might expect. It returns the last _actively_ selected // profile (i.e. via the Profile Manager or -P option) rather than the // current profile. These will differ if the current process was run // without explicitly selecting a profile. /** @property {string} The name of the current user profile. */ this.profileName = services.get("dirsvc").get("ProfD", Ci.nsIFile).leafName.replace(/^.+?\./, ""); let platform = Liberator.getPlatformFeature() config.features.add(platform); if (/^Win(32|64)$/.test(platform)) config.features.add('Windows'); if (AddonManager) { let self = this; self._extensions = []; AddonManager.getAddonsByTypes(["extension"], function (e) self._extensions = e); this.onEnabled = this.onEnabling = this.onDisabled = this.onDisabling = this.onInstalled = this.onInstalling = this.onUninstalled = this.onUninstalling = function () AddonManager.getAddonsByTypes(["extension"], function (e) self._extensions = e); AddonManager.addAddonListener(this); } }, destroy: function () { autocommands.trigger(config.name + "LeavePre", {}); storage.saveAll(); liberator.triggerObserver("shutdown", null); liberator.log("All liberator modules destroyed"); autocommands.trigger(config.name + "Leave", {}); }, /** * @property {number} The current main mode. * @see modes#mainModes */ get mode() modes.main, set mode(value) modes.main = value, get menuItems() Liberator.getMenuItems(), /** @property {Element} The currently focused element. */ get focus() document.commandDispatcher.focusedElement, // TODO: Do away with this getter when support for 1.9.x is dropped get extensions() { return this._extensions.map(function (e) ({ id: e.id, name: e.name, description: e.description, enabled: e.isActive, icon: e.iconURL, options: e.optionsURL, version: e.version, original: e })); }, getExtension: function (name) this.extensions.filter(function (e) e.name == name)[0], // Global constants CURRENT_TAB: [], NEW_TAB: [], NEW_BACKGROUND_TAB: [], NEW_WINDOW: [], NEW_PRIVATE_WINDOW: [], forceNewTab: false, forceNewWindow: false, forceNewPrivateWindow: false, /** @property {string} The Liberator version string. */ version: "###VERSION### (created: ###DATE###)", // these VERSION and DATE tokens are replaced by the Makefile /** * @property {Object} The map of command-line options. These are * specified in the argument to the host application's -{config.name} * option. E.g. $ firefox -vimperator '+u=/tmp/rcfile ++noplugin' * Supported options: * +u=RCFILE Use RCFILE instead of .vimperatorrc. * ++noplugin Don't load plugins. */ commandLineOptions: { /** @property Whether plugin loading should be prevented. */ noPlugins: false, /** @property An RC file to use rather than the default. */ rcFile: null, /** @property An Ex command to run before any initialization is performed. */ preCommands: null, /** @property An Ex command to run after all initialization has been performed. */ postCommands: null }, registerObserver: function (type, callback) { if (!(type in this.observers)) this.observers[type] = []; this.observers[type].push(callback); }, unregisterObserver: function (type, callback) { if (type in this.observers) this.observers[type] = this.observers[type].filter(function (c) c != callback); }, // TODO: "zoom": if the zoom value of the current buffer changed triggerObserver: function (type) { let args = Array.slice(arguments, 1); for (let func of this.observers[type] || []) func.apply(null, args); }, /** * Triggers the application bell to notify the user of an error. The * bell may be either audible or visual depending on the value of the * 'visualbell' option. */ beep: function () { // FIXME: popups clear the command line if (options["visualbell"]) { // flash the visual bell let popup = document.getElementById("liberator-visualbell"); let win = config.visualbellWindow; let rect = win.getBoundingClientRect(); let width = rect.right - rect.left; let height = rect.bottom - rect.top; // NOTE: this doesn't seem to work in FF3 with full box dimensions popup.openPopup(win, "overlap", 1, 1, false, false); popup.sizeTo(width - 2, height - 2); setTimeout(function () { popup.hidePopup(); }, 20); } else { let soundService = Cc["@mozilla.org/sound;1"].getService(Ci.nsISound); soundService.beep(); } return false; // so you can do: if (...) return liberator.beep(); }, /** * Creates a new thread. */ newThread: function () services.get("threadManager").newThread(0), /** * Calls a function asynchronously on a new thread. * * @param {nsIThread} thread The thread to call the function on. If no * thread is specified a new one is created. * @optional * @param {Object} self The 'this' object used when executing the * function. * @param {function} func The function to execute. * */ callAsync: function (thread, self, func) { thread = thread || services.get("threadManager").newThread(0); thread.dispatch(Runnable(self, func, Array.slice(arguments, 3)), thread.DISPATCH_NORMAL); }, /** * Calls a function synchronously on a new thread. * * NOTE: Be sure to call GUI related methods like alert() or dump() * ONLY in the main thread. * * @param {nsIThread} thread The thread to call the function on. If no * thread is specified a new one is created. * @optional * @param {function} func The function to execute. */ callFunctionInThread: function (thread, func) { thread = thread || services.get("threadManager").newThread(0); // DISPATCH_SYNC is necessary, otherwise strange things will happen thread.dispatch(Runnable(null, func, Array.slice(arguments, 2)), thread.DISPATCH_SYNC); }, /** * Prints a message to the console. If <b>msg</b> is an object it is * pretty printed. * * NOTE: the "browser.dom.window.dump.enabled" preference needs to be * set. * * @param {string|Object} msg The message to print. */ dump: function () { let msg = Array.map(arguments, function (msg) { if (typeof msg == "object") msg = util.objectToString(msg); return msg; }).join(", "); msg = String.replace(msg, /\n?$/, "\n"); window.dump(msg.replace(/^./gm, ("config" in modules && config.name.toLowerCase()) + ": $&")); }, /** * Outputs a plain message to the command line. * * @param {string} str The message to output. * @param {number} flags These control the multiline message behaviour. * See {@link CommandLine#echo}. */ echo: function (str, flags) { commandline.echo(str, commandline.HL_NORMAL, flags); }, /** * Outputs an error message to the command line. * * @param {string|Error} str The message to output. * @param {number} flags These control the multiline message behavior. * See {@link CommandLine#echo}. * @param {string} prefix The prefix of error message. */ echoerr: function (str, flags, prefix) { try { flags |= commandline.APPEND_TO_MESSAGES | commandline.DISALLOW_MULTILINE | commandline.FORCE_SINGLELINE; if (typeof str == "object" && "echoerr" in str) str = str.echoerr; if (options["errorbells"]) liberator.beep(); commandline.echo((prefix || "") + str, commandline.HL_ERRORMSG, flags); // For errors, also print the stack trace to our :messages list if (str instanceof Error) { let stackTrace = xml``; let stackItems = new Error().stack.split('\n'); // ignore the first element intenationally! stackTrace = template.map2(xml, stackItems.slice(1), function (stackItema) { let atIndex = stackItem.lastIndexOf("@"); if (n === 0 || atIndex < 0) return ""; let stackLocation = stackItem.substring(atIndex + 1); let stackArguments = stackItem.substring(0, atIndex); if (stackArguments) stackArguments = " - " + stackArguments; return xml`<span style="font-weight: normal">&#xa0;&#xa0;xxx at </span>${stackLocation}<span style="font-weight: normal">${stackArguments}</span><br/>`; }); commandline.messages.add({str: stackTrace, highlight: commandline.HL_ERRORMSG}); } } catch (e) { // if for some reason, echoerr fails, log this information at least to // the console! liberator.dump(str); } }, /** * Outputs an information message to the command line. * * @param {string} str The message to output. * @param {number} flags These control the multiline message behavior. * See {@link CommandLine#echo}. */ echomsg: function (str, flags) { flags |= commandline.APPEND_TO_MESSAGES | commandline.DISALLOW_MULTILINE | commandline.FORCE_SINGLELINE; commandline.echo(str, commandline.HL_INFOMSG, flags); }, /** * Loads and executes the script referenced by <b>uri</b> in the scope * of the <b>context</b> object. * * @param {string} uri The URI of the script to load. Should be a local * chrome:, file:, or resource: URL. * @param {Object} context The context object into which the script * should be loaded. */ loadScript: function (uri, context) { if (options.expandtemplate) { var prefix = "liberator://template/"; if (uri.lastIndexOf(prefix, 0) === -1) uri = prefix + uri; } services.get("scriptloader").loadSubScript(uri, context, "UTF-8"); }, eval: function (str, context) { try { if (!context) context = userContext; if (options.expandtemplate) { var obj = new Object; Cu.import("resource://liberator/template.js", obj); str = obj.convert(str); } context[EVAL_ERROR] = null; context[EVAL_STRING] = str; context[EVAL_RESULT] = null; this.loadScript("chrome://liberator/content/eval.js", context); if (context[EVAL_ERROR]) { try { context[EVAL_ERROR].fileName = io.sourcing.file; context[EVAL_ERROR].lineNumber += io.sourcing.line; } catch (e) {} throw context[EVAL_ERROR]; } return context[EVAL_RESULT]; } finally { delete context[EVAL_ERROR]; delete context[EVAL_RESULT]; delete context[EVAL_STRING]; } }, // partial sixth level expression evaluation // TODO: what is that really needed for, and where could it be used? // Or should it be removed? (c) Viktor // Better name? See other liberator.eval() // I agree, the name is confusing, and so is the // description --Kris evalExpression: function (string) { string = string.toString().trim(); let matches = null; // String if ((matches = string.match(/^(['"])([^\1]*?[^\\]?)\1/))) { return matches[2].toString(); } // Number else if ((matches = string.match(/^(\d+)$/))) return parseInt(matches[1], 10); let reference = this.variableReference(string); if (!reference[0]) this.echoerr("Undefined variable: " + string); else return reference[0][reference[1]]; return null; }, /** * Execute an Ex command string. E.g. ":zoom 300". * * @param {string} str The command to execute. * @param {Object} modifiers Any modifiers to be passed to * {@link Command#action}. * @param {boolean} silent Whether the command should be echoed on the * command line. */ execute: function (str, modifiers, silent) { // skip comments and blank lines if (/^\s*("|$)/.test(str)) return; modifiers = modifiers || {}; let err = null; let [count, cmd, special, args] = commands.parseCommand(str.replace(/^'(.*)'$/, "$1")); let command = commands.get(cmd); if (command === null) { err = "Not a " + config.name.toLowerCase() + " command: " + str; liberator.focusContent(); } else if (command.action === null) err = "Internal error: command.action === null"; // TODO: need to perform this test? -- djk else if (count != null && !command.count) err = "No range allowed"; else if (special && !command.bang) err = "No ! allowed"; liberator.assert(!err, err); if (!silent) commandline.command = str.replace(/^\s*:\s*/, ""); command.execute(args, special, count, modifiers); }, /** * Focuses the content window. * * @param {boolean} clearFocusedElement Remove focus from any focused * element. */ focusContent: function (clearFocusedElement) { if (window != services.get("ww").activeWindow) return; let elem = config.mainWidget || window.content; // TODO: make more generic try { if (this.has("tabs")) { // select top most frame in a frameset let frame = buffer.localStore.focusedFrame; if (frame && frame.top == window.content) elem = frame; } } catch (e) {} if (clearFocusedElement && liberator.focus) liberator.focus.blur(); if (elem && elem != liberator.focus) elem.focus(); }, /** * Returns whether this Liberator extension supports <b>feature</b>. * * @param {string} feature The feature name. * @returns {boolean} */ has: function (feature) config.features.has(feature), /** * Returns whether the host application has the specified extension * installed. * * @param {string} name The extension name. * @returns {boolean} */ hasExtension: function (name) { return this._extensions.some(function (e) e.name == name); }, /** * Returns the URL of the specified help <b>topic</b> if it exists. * * @param {string} topic The help topic to lookup. * @param {boolean} unchunked Whether to search the unchunked help page. * @returns {string} */ findHelp: function (topic, unchunked) { if (topic in services.get("liberator:").FILE_MAP) return topic; unchunked = !!unchunked; let items = completion._runCompleter("help", topic, null, unchunked).items; let partialMatch = null; function format(item) item.description + "#" + encodeURIComponent(item.text); for (let item of items) { if (item.text == topic) return format(item); else if (!partialMatch && topic) partialMatch = item; } if (partialMatch) return format(partialMatch); return null; }, /** * @private * Initialize the help system. */ initHelp: function () { let namespaces = [config.name.toLowerCase(), "liberator"]; services.get("liberator:").init({}); let tagMap = services.get("liberator:").HELP_TAGS; let fileMap = services.get("liberator:").FILE_MAP; let overlayMap = services.get("liberator:").OVERLAY_MAP; // Left as an XPCOM instantiation so it can easilly be moved // into XPCOM code. function XSLTProcessor(sheet) { let xslt = Cc["@mozilla.org/document-transformer;1?type=xslt"].createInstance(Ci.nsIXSLTProcessor); xslt.importStylesheet(util.httpGet(sheet).responseXML); return xslt; } // Find help and overlay files with the given name. function findHelpFile(file) { let result = []; for (let namespace of namespaces) { let url = ["chrome://", namespace, "/locale/", file, ".xml"].join(""); let res = util.httpGet(url); if (res) { if (res.responseXML.documentElement.localName == "document") fileMap[file] = url; if (res.responseXML.documentElement.localName == "overlay") overlayMap[file] = url; result.push(res.responseXML); } } return result; } // Find the tags in the document. function addTags(file, doc) { doc = XSLT.transformToDocument(doc); for (let elem in util.evaluateXPath("//xhtml:a/@id", doc)) tagMap[elem.value] = file; } const XSLT = XSLTProcessor("chrome://liberator/content/help-single.xsl"); // Scrape the list of help files from all.xml // Always process main and overlay files, since XSLTProcessor and // XMLHttpRequest don't allow access to chrome documents. tagMap.all = "all"; let files = findHelpFile("all").map(function (doc) [f.value for (f in util.evaluateXPath( "//liberator:include/@href", doc))]); // Scrape the tags from the rest of the help files. util.Array.flatten(files).forEach(function (file) { findHelpFile(file).forEach(function (doc) { addTags(file, doc); }); }); // Process plugin help entries. let lang = options.getPref("general.useragent.locale", "en-US"); const ps = new DOMParser; const encoder = Cc["@mozilla.org/layout/documentEncoder;1?type=text/xml"].getService(Ci.nsIDocumentEncoder); encoder.init(document, "text/xml", 0); body = xml.map([con for ([,con] in Iterator(plugins.contexts))], function (context) { try { // debug var info = context.INFO; if (!info) return ""; var div = ps.parseFromString(xml`<div xmlns=${XHTML}>${info}</div>`, "text/xml").documentElement; var list = div.querySelectorAll("plugin"); var res = {}; for (var i = 0, j = list.length; i < j; i++) { var info = list[i]; var value = info.getAttribute("lang") || ""; res[i] = res[value] = info; } var info = res[lang] || res[lang.split("-", 2).shift()] || res[0]; if (!info) return ""; encoder.setNode(info); return xml`<h2 xmlns=${NS.uri} tag=${info.getAttribute("name") + '-plugin'}>${ info.getAttribute("summary")}</h2>${xml.raw`${encoder.encodeToString()}`}`; } catch (ex) { Cu.reportError(ex); alert(ex); } }); let help = '<?xml version="1.0"?>\n' + '<?xml-stylesheet type="text/xsl" href="chrome://liberator/content/help.xsl"?>\n' + '<!DOCTYPE document SYSTEM "chrome://liberator/content/liberator.dtd">' + xml`<document xmlns=${NS} name="plugins" title=${config.name + " Plugins"}> <h1 tag="using-plugins">Using Plugins</h1> ${body} </document>`.toString(); fileMap["plugins"] = function () ['text/xml;charset=UTF-8', help]; addTags("plugins", util.httpGet("liberator://help/plugins").responseXML); }, /** * Opens the help page containing the specified <b>topic</b> if it * exists. * * @param {string} topic The help topic to open. * @param {boolean} unchunked Whether to use the unchunked help page. * @returns {string} */ help: function (topic, unchunked) { if (!topic) { let helpFile = unchunked ? "all" : options["helpfile"]; if (helpFile in services.get("liberator:").FILE_MAP) liberator.open("liberator://help/" + helpFile, { from: "help" }); else liberator.echomsg("Sorry, help file " + helpFile.quote() + " not found"); return; } let page = this.findHelp(topic, unchunked); liberator.assert(page != null, "Sorry, no help for: " + topic); liberator.open("liberator://help/" + page, { from: "help" }); if (!options["activate"] || options.get("activate").has("all", "help")) content.postMessage("fragmentChange", "*"); }, /** * The map of global variables. * * These are set and accessed with the "g:" prefix. */ globalVariables: {}, loadPlugins: function () { function sourceDirectory(dir) { liberator.assert(dir.isReadable(), "Cannot read directory: " + dir.path); liberator.log("Sourcing plugin directory: " + dir.path + "..."); dir.readDirectory(true).forEach(function (file) { if (file.isFile() && /\.(js|vimp)$/i.test(file.path) && !(file.path in liberator.pluginFiles)) { try { io.source(file.path, false); liberator.pluginFiles[file.path] = true; } catch (e) { liberator.echoerr(e); } } else if (file.isDirectory()) sourceDirectory(file); }); } let dirs = io.getRuntimeDirectories("plugin"); if (dirs.length == 0) { liberator.log("No user plugin directory found"); return; } liberator.log('Searching for "plugin/**/*.{js,vimp}" in "' + [dir.path.replace(/.plugin$/, "") for (dir of dirs)].join(",") + '"'); dirs.forEach(function (dir) { liberator.log("Searching for \"" + (dir.path + "/**/*.{js,vimp}") + "\"", 3); sourceDirectory(dir); }); }, /** * Logs a message to the JavaScript error console. * * @param {string|Object} msg The message to print. */ log: function (msg) { if (typeof msg == "object") msg = Cc["@mozilla.org/feed-unescapehtml;1"] .getService(Ci.nsIScriptableUnescapeHTML) .unescape(util.objectToString(msg, false).value); services.get("console").logStringMessage(config.name.toLowerCase() + ": " + msg); }, /** * Opens one or more URLs. Returns true when load was initiated, or * false on error. * * @param {string|string[]} urls Either a URL string or an array of URLs. * The array can look like this: * ["url1", "url2", "url3", ...] * or: * [["url1", postdata1], ["url2", postdata2], ...] * @param {number|Object} where If ommited, CURRENT_TAB is assumed but NEW_TAB * is set when liberator.forceNewTab is true. * @param {boolean} force Don't prompt whether to open more than 20 * tabs. * @returns {boolean} */ open: function (urls, params, force) { // convert the string to an array of converted URLs // -> see util.stringToURLArray for more details // // This is strange. And counterintuitive. Is it really // necessary? --Kris if (typeof urls == "string") { // rather switch to the tab instead of opening a new url in case of "12: Tab Title" like "urls" if (liberator.has("tabs")) { let matches = urls.match(/^(\d+):/); if (matches) { tabs.select(parseInt(matches[1], 10) - 1, false, true); // make it zero-based return; } } urls = util.stringToURLArray(urls); } if (urls.length > 20 && !force) { commandline.input("This will open " + urls.length + " new tabs. Would you like to continue? (yes/[no]) ", function (resp) { if (resp && resp.match(/^y(es)?$/i)) liberator.open(urls, params, true); }); return; } let flags = 0; params = params || {}; if (params instanceof Array) params = { where: params }; for (let [opt, flag] in Iterator({ replace: "REPLACE_HISTORY", hide: "BYPASS_HISTORY" })) if (params[opt]) flags |= Ci.nsIWebNavigation["LOAD_FLAGS_" + flag]; let where = params.where || liberator.CURRENT_TAB; if (liberator.forceNewTab) where = liberator.NEW_TAB; else if (liberator.forceNewWindow) where = liberator.NEW_WINDOW; else if (liberator.forceNewPrivateWindow) where = liberator.NEW_PRIVATE_WINDOW; if ("from" in params && liberator.has("tabs")) { if (!('where' in params) && options["newtab"] && options.get("newtab").has("all", params.from)) where = liberator.NEW_TAB; if (options["activate"] && !options.get("activate").has("all", params.from)) { if (where == liberator.NEW_TAB) where = liberator.NEW_BACKGROUND_TAB; else if (where == liberator.NEW_BACKGROUND_TAB) where = liberator.NEW_TAB; } } if (urls.length == 0) return; let browser = config.browser; let urlTasks = []; function open(urls, where) { if (!browser) { urlTasks.push(urls); return; } try { let url = "", postdata; if (typeof urls === "string") url = urls; else [url, postdata] = Array.concat(urls); if (!url) url = window.BROWSER_NEW_TAB_URL || "about:blank"; // decide where to load the first url switch (where) { case liberator.CURRENT_TAB: browser.loadURIWithFlags(url, flags, null, null, postdata); break; case liberator.NEW_BACKGROUND_TAB: case liberator.NEW_TAB: if (!liberator.has("tabs")) { open(urls, liberator.NEW_WINDOW); return; } options.withContext(function () { options.setPref("browser.tabs.loadInBackground", true); browser.loadOneTab(url, null, null, postdata, where == liberator.NEW_BACKGROUND_TAB); }); break; case liberator.NEW_PRIVATE_WINDOW: case liberator.NEW_WINDOW: let sa = Cc["@mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray); let wuri = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString); wuri.data = url; sa.AppendElement(wuri); sa.AppendElement(null); // charset sa.AppendElement(null); // referrerURI sa.AppendElement(postdata); sa.AppendElement(null); // allowThirdPartyFixup let features = "chrome,dialog=no,all" + (where === liberator.NEW_PRIVATE_WINDOW ? ",private" : ""); let win = services.get("ww").openWindow(window, "chrome://browser/content/browser.xul", null, features, sa); browser = null; win.addEventListener("load", function onload(aEvent) { win.removeEventListener("load", onload, false); browser = win.getBrowser(); for (let url of urlTasks) open(url, liberator.NEW_BACKGROUND_TAB); urlTasks = []; }, false); break; } } catch (e) {} } for (let url of urls) { open(url, where); where = liberator.NEW_BACKGROUND_TAB; } }, pluginFiles: {}, // namespace for plugins/scripts. Actually (only) the active plugin must/can set a // v.plugins.mode = <str> string to show on v.modes.CUSTOM // v.plugins.stop = <func> hooked on a v.modes.reset() // v.plugins.onEvent = <func> function triggered, on keypresses (unless <esc>) (see events.js) plugins: plugins, /** * Quit the host application, no matter how many tabs/windows are open. * * @param {boolean} saveSession If true the current session will be * saved and restored when the host application is restarted. * @param {boolean} force Forcibly quit irrespective of whether all * windows could be closed individually. */ quit: function (saveSession, force) { // TODO: Use safeSetPref? if (saveSession) options.setPref("browser.startup.page", 3); // start with saved session else options.setPref("browser.startup.page", 1); // start with default homepage session if (force) services.get("startup").quit(Ci.nsIAppStartup.eForceQuit); else window.goQuitApplication(); }, /* * Tests a condition and throws a FailedAssertion error on * failure. * * @param {boolean} condition The condition to test. * @param {string} message The message to present to the * user on failure. */ assert: function (condition, message) { if (!condition) throw new FailedAssertion(message); }, /** * Traps errors in the called function, possibly reporting them. * * @param {function} func The function to call * @param {object} self The 'this' object for the function. */ trapErrors: function (func, self) { try { return func.apply(self || this, Array.slice(arguments, 2)); } catch (e) { if (e instanceof FailedAssertion) { if (e.message) liberator.echoerr(e.message); else liberator.beep(); } else liberator.echoerr(e); return undefined; } }, /** * Reports an error to both the console and the host application's * Error Console. * * @param {Object} error The error object. */ /*reportError: function (error) { if (Cu.reportError) Cu.reportError(error); try { let obj = { toString: function () String(error), stack: <>{String.replace(error.stack || Error().stack, /^/mg, "\t")}</> }; for (let [k, v] in Iterator(error)) { if (!(k in obj)) obj[k] = v; } if (liberator.storeErrors) { let errors = storage.newArray("errors", { store: false }); errors.toString = function () [String(v[0]) + "\n" + v[1] for ([k, v] in this)].join("\n\n"); errors.push([new Date, obj + obj.stack]); } liberator.dump(String(error)); liberator.dump(obj); liberator.dump(""); } catch (e) { window.dump(e); } },*/ /** * Restart the host application. */ restart: function () { // notify all windows that an application quit has been requested. var cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool); services.get("obs").notifyObservers(cancelQuit, "quit-application-requested", null); // something aborted the quit process. if (cancelQuit.data) return; // notify all windows that an application quit has been granted. services.get("obs").notifyObservers(null, "quit-application-granted", null); // enumerate all windows and call shutdown handlers let windows = services.get("wm").getEnumerator(null); while (windows.hasMoreElements()) { let win = windows.getNext(); if (("tryToClose" in win) && !win.tryToClose()) return; } services.get("startup").quit(Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eAttemptQuit); }, /** * Parses a Liberator command-line string i.e. the value of the * -liberator command-line option. * * @param {string} cmdline The string to parse for command-line * options. * @returns {Object} * @see Commands#parseArgs */ parseCommandLine: function (cmdline) { const options = [ [["+u"], commands.OPTIONS_STRING], [["++noplugin"], commands.OPTIONS_NOARG], [["++cmd"], commands.OPTIONS_STRING, null, null, true], [["+c"], commands.OPTIONS_STRING, null, null, true] ]; return commands.parseArgs(cmdline, options, [], "*"); }, sleep: function (delay) { let mainThread = services.get("threadManager").mainThread; let end = Date.now() + delay; while (Date.now() < end) mainThread.processNextEvent(true); return true; }, callInMainThread: function (callback, self) { let mainThread = services.get("threadManager").mainThread; if (!services.get("threadManager").isMainThread) mainThread.dispatch({ run: callback.call(self) }, mainThread.DISPATCH_NORMAL); else callback.call(self); }, threadYield: function (flush, interruptable) { let mainThread = services.get("threadManager").mainThread; liberator.interrupted = false; do { mainThread.processNextEvent(!flush); if (liberator.interrupted) throw new Error("Interrupted"); } while (flush === true && mainThread.hasPendingEvents()); }, variableReference: function (string) { if (!string) return [null, null, null]; let matches = string.match(/^([bwtglsv]):(\w+)/); if (matches) { // Variable // Other variables should be implemented if (matches[1] == "g") { if (matches[2] in this.globalVariables) return [this.globalVariables, matches[2], matches[1]]; else return [null, matches[2], matches[1]]; } } else { // Global variable if (string in this.globalVariables) return [this.globalVariables, string, "g"]; else return [null, string, "g"]; } throw Error("What the fuck?"); }, /** * @property {Window[]} Returns an array of all the host application's * open windows. */ get windows() { let windows = []; let enumerator = services.get("wm").getEnumerator("navigator:browser"); while (enumerator.hasMoreElements()) windows.push(enumerator.getNext()); return windows; } }, { // return the platform normalized to Vim values getPlatformFeature: function () { let platform = navigator.platform; return /^Mac/.test(platform) ? "MacUnix" : platform == "Win32" ? "Win32" : platform == "Win64" ? "Win64" : "Unix"; }, // TODO: move this getMenuItems: function () { function addChildren(node, parent) { for (let item of node.childNodes) { if (item.childNodes.length == 0 && item.localName == "menuitem" && !/rdf:http:/.test(item.getAttribute("label"))) { // FIXME item.fullMenuPath = parent + item.getAttribute("label"); items.push(item); } else { let path = parent; if (item.localName == "menu") path += item.getAttribute("label") + "."; addChildren(item, path); } } } let items = []; addChildren(document.getElementById(config.toolbars["menu"][0][0]), ""); return items; }, }, { // Only general options are added here, which are valid for all liberator extensions options: function () { options.add(["errorbells", "eb"], "Ring the bell when an error message is displayed", "boolean", false); options.add(["exrc", "ex"], "Allow reading of an RC file in the current directory", "boolean", false); options.add(["fullscreen", "fs"], "Show the current window fullscreen", "boolean", false, { setter: function (value) window.fullScreen = value, getter: function () window.fullScreen }); options.add(["helpfile", "hf"], "Name of the main help file", "string", "intro"); options.add(["loadplugins", "lpl"], "Load plugin scripts when starting up", "boolean", true); // TODO: Is this vimperator only? Otherwise fix for Muttator options.add(["scrollbars", "sb"], "Show scrollbars in the content window when needed", "boolean", true, { setter: function (value) { if (value) styles.removeSheet(true, "scrollbars"); else // Use [orient="horizontal"] if you only want to change the horizontal scrollbars styles.addSheet(true, "scrollbars", "*", "html|html > xul|scrollbar { visibility: collapse !important; }", true); return value; } }); options.add(["smallicons", "si"], "Show small or normal size icons in the main toolbar", "boolean", true, { setter: function (value) { try { let mainToolbar = config.mainToolbar; mainToolbar.setAttribute("iconsize", value ? "small" : "large"); } catch (e) { } return value; }, getter: function () { try { let mainToolbar = config.mainToolbar; return mainToolbar.getAttribute("iconsize") == "small"; } catch (e) { return false; } } }); options.add(["titlestring"], "Change the title of the window", "string", config.defaults.titlestring || config.hostApplication, { setter: function (value) { let win = document.documentElement; if (liberator.has("privatebrowsing")) { let oldValue = win.getAttribute("titlemodifier_normal"); let suffix = win.getAttribute("titlemodifier_privatebrowsing").substr(oldValue.length); win.setAttribute("titlemodifier_normal", value); win.setAttribute("titlemodifier_privatebrowsing", value + suffix); if (window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsILoadContext) .usePrivateBrowsing) { win.setAttribute("titlemodifier", value + suffix); } else win.setAttribute("titlemodifier", value); } else win.setAttribute("titlemodifier", value); switch (config.hostApplication) { case "Firefox": config.tabbrowser.updateTitlebar(); break; case "Thunderbird": config.tabbrowser.setDocumentTitle(config.tabbrowser.currentTabInfo); break; } return value; } }); options.add(["toolbars", "gui"], "Show or hide toolbars", "stringlist", config.defaults.toolbars || "", { setter: function (values) { let toolbars = config.toolbars || {}; // a set of actions with the the name of the element as the object's keys // and the collapsed state for the values // Used in order to avoid multiple collapse/uncollapse actions // for values like :set gui=none,tabs let actions = {}; for (let action of this.parseValues(values)) { if (action === "all" || action === "none") { for (let [name, toolbar] in Iterator(toolbars)) { for (let id of toolbar[0] || []) actions[id] = action === "none"; } } else { let toolbarName = action.replace(/^(no|inv)/, ""); let toolbar = toolbars[toolbarName]; if (toolbar) { for (let id of toolbar[0] || []) { let elem = document.getElementById(id); if (!elem) continue; let collapsed = false; if (action.startsWith("no")) collapsed = true; else if (action.startsWith("inv")) { if (typeof(actions[id]) === "boolean") collapsed = !actions[id]; else { let hidingAttribute = elem.getAttribute("type") === "menubar" ? "autohide" : "collapsed"; collapsed = !(elem.getAttribute(hidingAttribute) === "true"); } } else collapsed = false; actions[id] = collapsed; // add the action, or change an existing action } } } } // finally we can just execute the actions for (let [id, collapsed] in Iterator(actions)) { let elem = document.getElementById(id); if (!elem) continue; // Firefox4 added this helper function, which does more than // just collapsing elements (like showing or hiding the menu button when the menu is hidden/shown) if (window.setToolbarVisibility) window.setToolbarVisibility(elem, !collapsed); else if (elem.getAttribute("type") == "menubar") elem.setAttribute("autohide", collapsed); else elem.collapsed = collapsed; // HACK: prevent the tab-bar from redisplaying when 'toolbars' option has 'notabs' // @see http://code.google.com/p/vimperator-labs/issues/detail?id=520 if (id == "TabsToolbar" && config.tabbrowser.mTabContainer.updateVisibility) config.tabbrowser.mTabContainer.updateVisibility = function () { }; } return ""; // we need this value, otherwise "inv" options won't work. Maybe we should just make this a local option }, getter: function() { let toolbars = config.toolbars || {}; let values = []; for (let [name, toolbar] in Iterator(toolbars)) { let elem = document.getElementById(toolbar[0]); if (elem) { let hidingAttribute = elem.getAttribute("type") == "menubar" ? "autohide" : "collapsed"; values.push(elem.getAttribute(hidingAttribute) == "true" ? "no" + name : name); } } return this.joinValues(values); }, completer: function (context) { let toolbars = config.toolbars || {}; let completions = [["all", "Show all toolbars"], ["none", "Hide all toolbars"]]; for (let [name, toolbar] in Iterator(toolbars)) { let elem = document.getElementById(toolbar[0][0]); if (elem) { let hidingAttribute = elem.getAttribute("type") == "menubar" ? "autohide" : "collapsed"; completions.push([elem.getAttribute(hidingAttribute) == "true" ? name : "no" + name, (elem.getAttribute(hidingAttribute) == "true" ? "Show " : "Hide ") + toolbar[1]]); } } context.completions = completions; context.compare = CompletionContext.Sort.unsorted; return completions; }, validator: function (value) { let toolbars = config.toolbars || {}; // "ne" is a simple hack, since in the next line val.replace() makes "ne" out from "none" let values = ["all", "ne"].concat([toolbar for each([toolbar, ] in Iterator(toolbars))]); return value.every(function(val) values.indexOf(val.replace(/^(no|inv)/, "")) >= 0); } }); options.add(["verbose", "vbs"], "Define which info messages are displayed", "number", 1, { validator: function (value) value >= 0 && value <= 15 }); options.add(["visualbell", "vb"], "Use visual bell instead of beeping on errors", "boolean", false, { setter: function (value) { options.safeSetPref("accessibility.typeaheadfind.enablesound", !value, "See 'visualbell' option"); return value; } }); }, mappings: function () { mappings.add(modes.all, ["<F1>"], "Open the help page", function () { liberator.help(); }); if (liberator.has("session")) { mappings.add([modes.NORMAL], ["ZQ"], "Quit and don't save the session", function () { liberator.quit(false); }); } mappings.add([modes.NORMAL], ["ZZ"], "Quit and save the session", function () { liberator.quit(true); }); }, commands: function () { commands.add(["addo[ns]"], "Manage available Extensions and Themes", function () { liberator.open("about:addons", { from: "addons" }); }, { argCount: "0" }); commands.add(["beep"], "Play a system beep", // Play? Wrong word. Implies some kind of musicality. --Kris function () { liberator.beep(); }, { argCount: "0" }); commands.add(["dia[log]"], "Open a " + config.name + " dialog", function (args) { let arg = args[0]; try { // TODO: why are these sorts of properties arrays? --djk let dialogs = config.dialogs; for (let dialog of dialogs) { if (util.compareIgnoreCase(arg, dialog[0]) == 0) { dialog[2](); return; } } liberator.echoerr("Invalid argument: " + arg); } catch (e) { liberator.echoerr("Error opening " + arg.quote() + ": " + e); } }, { argCount: "1", bang: true, completer: function (context) { context.ignoreCase = true; return completion.dialog(context); } }); commands.add(["em[enu]"], "Execute the specified menu item from the command line", function (args) { let arg = args.literalArg; let items = Liberator.getMenuItems(); liberator.assert(items.some(function (i) i.fullMenuPath == arg), "Menu not found: " + arg); for (let [, item] in Iterator(items)) { if (item.fullMenuPath == arg) item.doCommand(); } }, { argCount: "1", completer: function (context) completion.menuItem(context), literal: 0 }); commands.add(["exe[cute]"], "Execute the argument as an Ex command", // FIXME: this should evaluate each arg separately then join // with " " before executing. // E.g. :execute "source" io.getRCFile().path // Need to fix commands.parseArgs which currently strips the quotes // from quoted args function (args) { try { let cmd = liberator.eval(args.string); liberator.execute(cmd, null, true); } catch (e) { liberator.echoerr(e); } }); commands.add(["exta[dd]"], "Install an extension", function (args) { let file = io.File(args[0]); if (file.exists() && file.isReadable() && file.isFile()) AddonManager.getInstallForFile(file, function (a) a.install()); else { if (file.exists() && file.isDirectory()) liberator.echoerr("Cannot install a directory: " + file.path); liberator.echoerr("Cannot open file: " + file.path); } }, { argCount: "1", completer: function (context) { context.filters.push(function ({ item: f }) f.isDirectory() || /\.xpi$/.test(f.leafName)); completion.file(context); } }); // TODO: handle extension dependencies [ { name: "extde[lete]", description: "Uninstall an extension", action: "uninstallItem" }, { name: "exte[nable]", description: "Enable an extension", action: "enableItem", filter: function ({ item: e }) (!e.enabled || (e.original && e.original.userDisabled)) }, { name: "extd[isable]", description: "Disable an extension", action: "disableItem", filter: function ({ item: e }) (e.enabled || (e.original && !e.original.userDisabled)) } ].forEach(function (command) { commands.add([command.name], command.description, function (args) { let name = args[0]; function action(e) { if (command.action == "uninstallItem") e.original.uninstall(); else e.original.userDisabled = command.action == "disableItem"; }; if (args.bang) liberator.extensions.forEach(function (e) { action(e); }); else { liberator.assert(name, "Argument required"); let extension = liberator.getExtension(name); if (extension) action(extension); else liberator.echoerr("Invalid argument"); } }, { argCount: "?", // FIXME: should be "1" bang: true, completer: function (context) { completion.extension(context); if (command.filter) context.filters.push(command.filter); }, literal: 0 }); }); commands.add(["exto[ptions]", "extp[references]"], "Open an extension's preference dialog", function (args) { let extension = liberator.getExtension(args[0]); liberator.assert(extension && extension.options, "Invalid argument"); if (args.bang) window.openDialog(extension.options, "_blank", "chrome,toolbar"); else liberator.open(extension.options, { from: "extoptions" }); }, { argCount: "1", bang: true, completer: function (context) { completion.extension(context); context.filters.push(function ({ item: e }) e.options); }, literal: 0 }); // TODO: maybe indicate pending status too? commands.add(["extens[ions]"], "List available extensions", function (args) { let filter = args[0] || ""; let extensions = liberator.extensions.filter(function (e) e.name.indexOf(filter) >= 0); if (extensions.length > 0) { let list = template.tabular( ["Name", "Version", "Status", "Description"], ([template.icon(e, e.name), e.version, e.enabled ? xml`<span highlight="Enabled">enabled</span>` : xml`<span highlight="Disabled">disabled</span>`, e.description] for ([, e] in Iterator(extensions))) ); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } else { if (filter) liberator.echoerr("No matching extensions for: " + filter); else liberator.echoerr("No extensions installed"); } }, { argCount: "?" }); [ { name: "h[elp]", description: "Open the help page" }, { name: "helpa[ll]", description: "Open the single unchunked help page" } ].forEach(function (command) { let unchunked = command.name == "helpa[ll]"; commands.add([command.name], command.description, function (args) { liberator.assert(!args.bang, "Don't panic!"); liberator.help(args.literalArg, unchunked); }, { argCount: "?", bang: true, completer: function (context) completion.help(context, unchunked), literal: 0 }); }); commands.add(["javas[cript]", "js"], "Run a JavaScript command through eval()", function (args) { if (args.bang) { // open JavaScript console liberator.open("chrome://global/content/console.xul", { from: "javascript" }); } else { try { liberator.eval(args.string); } catch (e) { liberator.echoerr(e); } } }, { bang: true, completer: function (context) completion.javascript(context), hereDoc: true, literal: 0 }); commands.add(["loadplugins", "lpl"], "Load all plugins immediately", function () { liberator.loadPlugins(); }, { argCount: "0" }); commands.add(["norm[al]"], "Execute Normal mode commands", function (args) { events.feedkeys(args.string, args.bang); }, { argCount: "+", bang: true }); commands.add(["q[uit]"], liberator.has("tabs") ? "Quit current tab" : "Quit application", function (args) { if (liberator.has("tabs")) tabs.remove(config.browser.mCurrentTab, 1, false, 1); else liberator.quit(false, args.bang); }, { argCount: "0", bang: true }); commands.add(["res[tart]"], "Force " + config.name + " to restart", function () { liberator.restart(); }, { argCount: "0" }); commands.add(["time"], "Profile a piece of code or run a command multiple times", function (args) { let count = args.count; let special = args.bang; args = args.string; if (args[0] == ":") var method = function () liberator.execute(args, null, true); else method = liberator.eval("(function () {" + args + "})"); try { if (count > 1) { let each, eachUnits, totalUnits; let total = 0; for (let i in util.interruptibleRange(0, count, 500)) { let now = Date.now(); method(); total += Date.now() - now; } if (special) return; if (total / count >= 100) { each = total / 1000.0 / count; eachUnits = "sec"; } else { each = total / count; eachUnits = "msec"; } if (total >= 100) { total = total / 1000.0; totalUnits = "sec"; } else totalUnits = "msec"; let str = template.genericOutput("Code execution summary", xml`<table> <tr><td>Executed:</td><td align="right"><span class="times-executed">${count}</span></td><td>times</td></tr> <tr><td>Average time:</td><td align="right"><span class="time-average">${each.toFixed(2)}</span></td><td>${eachUnits}</td></tr> <tr><td>Total time:</td><td align="right"><span class="time-total">${total.toFixed(2)}</span></td><td>${totalUnits}</td></tr> </table>`); commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); } else { let beforeTime = Date.now(); method(); if (special) return; let afterTime = Date.now(); if (afterTime - beforeTime >= 100) liberator.echo("Total time: " + ((afterTime - beforeTime) / 1000.0).toFixed(2) + " sec"); else liberator.echo("Total time: " + (afterTime - beforeTime) + " msec"); } } catch (e) { liberator.echoerr(e); } }, { argCount: "+", bang: true, completer: function (context) { if (/^:/.test(context.filter)) return completion.ex(context); else return completion.javascript(context); }, count: true, literal: 0 }); commands.add(["verb[ose]"], "Execute a command with 'verbose' set", function (args) { let vbs = options.get("verbose"); let value = vbs.value; let setFrom = vbs.setFrom; try { vbs.set(args.count || 1); vbs.setFrom = null; liberator.execute(args[0], null, true); } finally { vbs.set(value); vbs.setFrom = setFrom; } }, { argCount: "+", completer: function (context) completion.ex(context), count: true, literal: 0 }); commands.add(["ve[rsion]"], "Show version information", function (args) { if (args.bang) liberator.open("about:"); else liberator.echo(template.tabular([{ header: "Version Information", style: "font-weight: bold; padding-left: 2ex", colspan: 2 }], [[config.name + ":", liberator.version], [config.hostApplication + ":", navigator.userAgent]])); }, { argCount: "0", bang: true }); commands.add(["us[age]"], "List all commands, mappings and options with a short description", function (args) { let usage = { mappings: function() template.table2(xml, "Mappings", [[item.name || item.names[0], item.description] for (item in mappings)].sort()), commands: function() template.table2(xml, "Commands", [[item.name || item.names[0], item.description] for (item in commands)]), options: function() template.table2(xml, "Options", [[item.name || item.names[0], item.description] for (item in options)]) } if (args[0] && !usage[args[0]]) return void liberator.echoerr("No usage information for: " + args[0]); if (args[0]) var usage = template.genericOutput(config.name + " Usage", usage[args[0]]()); else var usage = template.genericOutput(config.name + " Usage", xml`${ usage["mappings"]() }<br/>${ usage["commands"]() }<br/>${ usage["options"]()}`); liberator.echo(usage, commandline.FORCE_MULTILINE); }, { argCount: "?", bang: false, completer: function (context) { context.title = ["Usage Item"]; context.compare = CompletionContext.Sort.unsorted; context.completions = [["mappings", "All key bindings"], ["commands", "All ex-commands"], ["options", "All options"]]; } }); }, completion: function () { completion.dialog = function dialog(context) { context.title = ["Dialog"]; context.completions = config.dialogs; }; completion.extension = function extension(context) { context.title = ["Extension"]; context.anchored = false; context.keys = { text: "name", description: "description", icon: "icon" }, context.completions = liberator.extensions; }; completion.help = function help(context, unchunked) { context.title = ["Help"]; context.anchored = false; context.completions = services.get("liberator:").HELP_TAGS; if (unchunked) context.keys = { text: 0, description: function () "all" }; }; completion.menuItem = function menuItem(context) { context.title = ["Menu Path", "Label"]; context.anchored = false; context.keys = { text: "fullMenuPath", description: function (item) item.getAttribute("label") }; context.completions = liberator.menuItems; }; completion.toolbar = function toolbar(context) { let toolbox = document.getElementById("navigator-toolbox"); context.title = ["Toolbar"]; context.keys = { text: function (item) item.getAttribute("toolbarname"), description: function () "" }; context.completions = util.evaluateXPath("./*[@toolbarname]", document, toolbox); }; completion.window = function window(context) { context.title = ["Window", "Title"] context.keys = { text: function (win) liberator.windows.indexOf(win) + 1, description: function (win) win.document.title }; context.completions = liberator.windows; }; }, load: function () { liberator.triggerObserver("load"); liberator.log("All modules loaded"); services.add("commandLineHandler", "@mozilla.org/commandlinehandler/general-startup;1?type=" + config.name.toLowerCase()); let commandline = services.get("commandLineHandler").optionValue; if (commandline) { let args = liberator.parseCommandLine(commandline); liberator.commandLineOptions.rcFile = args["+u"]; liberator.commandLineOptions.noPlugins = "++noplugin" in args; liberator.commandLineOptions.postCommands = args["+c"]; liberator.commandLineOptions.preCommands = args["++cmd"]; liberator.log("Command-line options: " + util.objectToString(liberator.commandLineOptions)); } // first time intro message const firstTime = "extensions." + config.name.toLowerCase() + ".firsttime"; if (options.getPref(firstTime, true)) { setTimeout(function () { liberator.help(); options.setPref(firstTime, false); }, 1000); } // always start in normal mode modes.reset(); if (liberator.commandLineOptions.preCommands) liberator.commandLineOptions.preCommands.forEach(function (cmd) { liberator.execute(cmd); }); // finally, read the RC file and source plugins // make sourcing asynchronous, otherwise commands that open new tabs won't work setTimeout(function () { let extensionName = config.name.toUpperCase(); let init = services.get("environment").get(extensionName + "_INIT"); let rcFile = io.getRCFile("~"); if (liberator.commandLineOptions.rcFile) { let filename = liberator.commandLineOptions.rcFile; if (!/^(NONE|NORC)$/.test(filename)) io.source(io.File(filename).path, false); // let io.source handle any read failure like Vim } else { if (init) liberator.execute(init); else { if (rcFile) { io.source(rcFile.path, true); services.get("environment").set("MY_" + extensionName + "RC", rcFile.path); } else liberator.log("No user RC file found"); } if (options["exrc"] && !liberator.commandLineOptions.rcFile) { let localRCFile = io.getRCFile(io.getCurrentDirectory().path); if (localRCFile && !localRCFile.equals(rcFile)) io.source(localRCFile.path, true); } } if (liberator.commandLineOptions.rcFile == "NONE" || liberator.commandLineOptions.noPlugins) options["loadplugins"] = false; if (options["loadplugins"]) liberator.loadPlugins(); liberator.initHelp(); // after sourcing the initialization files, this function will set // all gui options to their default values, if they have not been // set before by any RC file // TODO: Let options specify themselves whether they need to be set at startup! for (let option in options) { if (!option.hasChanged && ["popups", "smallicons", "titlestring", "toolbars"].indexOf(option.name) >= 0) option.value = option.defaultValue; // call setter } if (liberator.commandLineOptions.postCommands) liberator.commandLineOptions.postCommands.forEach(function (cmd) { liberator.execute(cmd); }); liberator.triggerObserver("enter", null); autocommands.trigger(config.name + "Enter", {}); }, 0); statusline.update(); liberator.log(config.name + " fully initialized"); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * This class is used for prompting of user input and echoing of messages. * * It consists of a prompt and command field be sure to only create objects of * this class when the chrome is ready. */ const CommandLine = Module("commandline", { requires: ["config", "liberator", "modes", "services", "storage", "template", "util"], init: function () { const self = this; this._callbacks = {}; storage.newArray("history-search", { store: true, privateData: true }); storage.newArray("history-command", { store: true, privateData: true }); // Really inideal. let services = modules.services; // Storage objects are global to all windows, 'modules' isn't. storage.newObject("sanitize", function () { ({ CLEAR: "browser:purge-session-history", QUIT: "quit-application", init: function () { services.get("obs").addObserver(this, this.CLEAR, false); services.get("obs").addObserver(this, this.QUIT, false); }, observe: function (subject, topic, data) { switch (topic) { case this.CLEAR: ["search", "command"].forEach(function (mode) { CommandLine.History(null, mode).sanitize(); }); break; case this.QUIT: services.get("obs").removeObserver(this, this.CLEAR); services.get("obs").removeObserver(this, this.QUIT); break; } } }).init(); }, { store: false }); storage.addObserver("sanitize", function (key, event, value) { autocommands.trigger("Sanitize", {}); }, window); this._messageHistory = { //{{{ _messages: [], get messages() { let max = options["messages"]; // resize if 'messages' has changed if (this._messages.length > max) this._messages = this._messages.splice(this._messages.length - max); return this._messages; }, get length() this._messages.length, clear: function clear() { this._messages = []; }, add: function add(message) { if (!message) return; if (this._messages.length >= options["messages"]) this._messages.shift(); this._messages.push(message); } }; //}}} this._lastMowOutput = null; this._silent = false; this._quiet = false; this._lastEcho = null; /////////////////////////////////////////////////////////////////////////////}}} ////////////////////// TIMERS ////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////{{{ this._statusTimer = new Timer(5, 100, function statusTell() { if (self._completions == null) return; }); this._autocompleteTimer = new Timer(200, 500, function autocompleteTell(tabPressed) { if (!events.feedingKeys && self._completions && options["autocomplete"]) { self._completions.complete(true, false); self._completions.itemList.show(); } }); // This timer just prevents <Tab>s from queueing up when the // system is under load (and, thus, giving us several minutes of // the completion list scrolling). Multiple <Tab> presses are // still processed normally, as the time is flushed on "keyup". this._tabTimer = new Timer(0, 0, function tabTell(event) { if (self._completions) self._completions.tab(event.shiftKey); }); /////////////////////////////////////////////////////////////////////////////}}} ////////////////////// VARIABLES /////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////{{{ this._completionList = ItemList("liberator-completions"); this._completions = null; this._history = null; this._startHints = false; // whether we're waiting to start hints mode this._lastSubstring = ""; // the label for showing the mode message this._modeWidget = document.getElementById("liberator-mode"); // the containing box for the this._promptWidget and this._commandWidget this._commandlineWidget = document.getElementById("liberator-commandline"); // the text part of the prompt for the current command, for example "Find" or "Follow hint". Can be blank this._promptWidget = document.getElementById("liberator-commandline-prompt-text"); // the command bar which contains the current command this._commandWidget = document.getElementById("liberator-commandline-command"); this._messageBox = document.getElementById("liberator-message"); // this._messageBox.addEventListener("transitionend", this.close.bind(this), false); this._commandWidget.inputField.QueryInterface(Ci.nsIDOMNSEditableElement); // the widget used for multiline output this._multilineOutputWidget = document.getElementById("liberator-multiline-output"); this._outputContainer = this._multilineOutputWidget.parentNode; this._multilineOutputWidget.contentDocument.body.id = "liberator-multiline-output-content"; // the widget used for multiline intput this._multilineInputWidget = document.getElementById("liberator-multiline-input"); // the widget used for bottombar this._bottomBarWidget = document.getElementById("liberator-bottombar"); // we need to save the mode which we were in before opening the command line // this is then used if we focus the command line again without the "official" // way of calling "open" this._currentExtendedMode = null; // the extended mode which we last openend the command line for this._currentPrompt = null; this._currentCommand = null; // save the arguments for the inputMultiline method which are needed in the event handler this._multilineRegexp = null; this._multilineCallback = null; this._input = {}; this._keepOpenForInput = false; this._commandlineDisplayTimeoutID = null; this.registerCallback("submit", modes.EX, function (command) { if (self._commandlineDisplayTimeoutID) { window.clearTimeout(self._commandlineDisplayTimeoutID); self._commandlineDisplayTimeoutID = null; } commands.repeat = command; liberator.trapErrors(function () liberator.execute(command)); //if (!(modes.main == modes.COMMAND_LINE) && !commandline._commandlineWidget.classList.contains("hidden")) // this.close(); }); this.registerCallback("complete", modes.EX, function (context) { context.fork("ex", 0, completion, "ex"); }); this.registerCallback("change", modes.EX, function (command) { self._autocompleteTimer.tell(false); }); this.registerCallback("cancel", modes.PROMPT, cancelPrompt); this.registerCallback("submit", modes.PROMPT, closePrompt); this.registerCallback("change", modes.PROMPT, function (str) { if (self._input.complete) self._autocompleteTimer.tell(false); if (self._input.change) self._input.change.call(commandline, str); }); this.registerCallback("complete", modes.PROMPT, function (context) { if (self._input.complete) context.fork("input", 0, commandline, self._input.complete); }); this.hide(); this._setHighlightGroup(this.HL_NORMAL); function cancelPrompt(value) { let callback = self._input.cancel; self._input = {}; if (callback) callback.call(self, value != null ? value : commandline.command); } function closePrompt(value) { self._keepOpenForInput = false; let callback = self._input.submit; self._input = {}; if (callback) callback.call(self, value != null ? value : commandline.command); } }, /** * Highlight the messageBox according to <b>group</b>. */ _setHighlightGroup: function (group) { this._messageBox.setAttributeNS(NS.uri, "highlight", group); // also the underlying element needs to take on our color group // otherwise e.g. a red background doesn't stretch the whole width document.getElementById('liberator-statusline').setAttributeNS(NS.uri, "highlight", group); }, /** * reset messasaBox */ _resetStatusline: function () { this._messageBox.value = ""; this._setHighlightGroup(""); }, /** * Determines whether the command line should be visible. * * @returns {boolean} */ _commandShown: function () modes.main == modes.COMMAND_LINE && !(modes.extended & (modes.INPUT_MULTILINE | modes.OUTPUT_MULTILINE)), /** * Set the command-line prompt. * * @param {string} val * @param {string} highlightGroup */ _setPrompt: function (val, highlightGroup) { this._promptWidget.value = val; this._promptWidget.collapsed = (val == ""); this._promptWidget.style.maxWidth = "-moz-calc(1em * " + val.length + ")"; }, /** * Set the command-line input value. The caret is reset to the * end of the line. * * @param {string} cmd */ _setCommand: function (cmd) { this._commandWidget.value = cmd; this._commandWidget.selectionStart = cmd.length; this._commandWidget.selectionEnd = cmd.length; }, /** * Display a message in the command-line area. * * @param {string} str * @param {string} highlightGroup * @param {boolean} forceSingle If provided, don't let over-long * messages move to the MOW. */ _echoLine: let (timeID = null) function (str, highlightGroup, forceSingle) { if (timeID) { window.clearTimeout(timeID); timeID = null; } if (this._messageBox.classList.contains("liberator-hiding")) this._messageBox.classList.remove("liberator-hiding"); this._setHighlightGroup(highlightGroup); this._messageBox.value = str; if (str && options["messagetimeout"] != -1 && [this.HL_INFOMSG, this.HL_WARNINGMSG].indexOf(highlightGroup) != -1) timeID = this.setTimeout(function(){ this._messageBox.classList.add("liberator-hiding"); }, options["messagetimeout"]); liberator.triggerObserver("echoLine", str, highlightGroup, forceSingle); //if (!this._commandShown()) ;//commandline.hide(); /*let field = this._messageBox.inputField; if (!forceSingle && field.editor.rootElement.scrollWidth > field.scrollWidth) this._echoMultiline(<span highlight="Message">{str}</span>, highlightGroup);*/ }, /** * Display a multiline message. * * @param {string} str * @param {string} highlightGroup */ // TODO: resize upon a window resize _echoMultiline: function (str, highlightGroup) { let doc = this._multilineOutputWidget.contentDocument; let win = this._multilineOutputWidget.contentWindow; liberator.triggerObserver("echoMultiline", str, highlightGroup); this._lastMowOutput = xml`<div class="ex-command-output" style="white-space: nowrap" highlight=${highlightGroup}>${template.maybeXML(str)}</div>`; let output = util.xmlToDom(this._lastMowOutput, doc); // FIXME: need to make sure an open MOW is closed when commands // that don't generate output are executed //if (this._outputContainer.collapsed) doc.body.innerHTML = ""; doc.body.appendChild(output); commandline.updateOutputHeight(true); if (win.scrollMaxY > 0) { // start the last executed command's output at the top of the screen let elements = doc.getElementsByClassName("ex-command-output"); elements[elements.length - 1].scrollIntoView(true); } else win.scrollTo(0, doc.body.clientHeight); win.focus(); modes.set(modes.COMMAND_LINE, modes.OUTPUT_MULTILINE); }, /** * Ensure that the multiline input widget is the correct size. */ _autosizeMultilineInputWidget: function () { let lines = this._multilineInputWidget.value.split("\n").length - 1; this._multilineInputWidget.setAttribute("rows", Math.max(lines, 1)); }, HL_NORMAL: "Normal", HL_ERRORMSG: "ErrorMsg", HL_MODEMSG: "ModeMsg", HL_MOREMSG: "MoreMsg", HL_QUESTION: "Question", HL_INFOMSG: "InfoMsg", HL_WARNINGMSG: "WarningMsg", HL_LINENR: "LineNr", FORCE_MULTILINE : 1 << 0, FORCE_SINGLELINE : 1 << 1, DISALLOW_MULTILINE : 1 << 2, // if an echo() should try to use the single line // but output nothing when the MOW is open; when also // FORCE_MULTILINE is given, FORCE_MULTILINE takes precedence APPEND_TO_MESSAGES : 1 << 3, // add the string to the message this._history get completionContext() this._completions.context, get mode() (modes.extended == modes.EX) ? "cmd" : "search", get silent() this._silent, set silent(val) { this._silent = val; this._quiet = this._quiet; }, get quiet() this._quiet, set quiet(val) { this._quiet = val; Array.forEach(document.getElementById("liberator-commandline").childNodes, function (node) { node.style.opacity = this._quiet || this._silent ? "0" : ""; }); }, // @param type can be: // "submit": when the user pressed enter in the command line // "change" // "cancel" // "complete" registerCallback: function (type, mode, func) { if (!(type in this._callbacks)) this._callbacks[type] = {}; this._callbacks[type][mode] = func; }, triggerCallback: function (type, mode, data) { if (type && mode && this._callbacks[type] && this._callbacks[type][mode]) //this._callbacks[type][mode].call(this, data); this._callbacks[type][mode](data); }, runSilently: function (func, self) { let wasSilent = this._silent; this._silent = true; try { func.call(self); } finally { this._silent = wasSilent; } }, get command() { try { // The long path is because of complications with the // completion preview. return this._commandWidget.inputField.editor.rootElement.firstChild.textContent; } catch (e) { return this._commandWidget.value; } }, set command(cmd) this._commandWidget.value = cmd, get message() this._messageBox.value, get messages() this._messageHistory, /** * Removes any previous output from the command line */ clear: function() { this._commandWidget.value = ""; this._echoLine(""); // this also resets a possible background color from echoerr() }, /** * Show a mode message like "INSERT" in the command line */ setModeMessage: function(message, style) { // we shouldn't need this check, but the XUL caching may not see this // widget until the cache is rebuilt! So at least we don't break modes completely if (this._modeWidget) { this._modeWidget.collapsed = !message; this._modeWidget.value = message; } }, /** * Open the command line. The main mode is set to * COMMAND_LINE, the extended mode to <b>extendedMode</b>. * Further, callbacks defined for <b>extendedMode</b> are * triggered as appropriate (see {@link #registerCallback}). * * @param {string} prompt * @param {string} cmd * @param {number} extendedMode */ open: function open(prompt, cmd, extendedMode) { if (this._commandlineDisplayTimeoutID) { window.clearTimeout(this._commandlineDisplayTimeoutID); this._commandlineDisplayTimeoutID = null; } // save the current prompts, we need it later if the command widget // receives focus without calling the this.open() method this._currentPrompt = prompt || ""; this._currentCommand = cmd || ""; this._currentExtendedMode = extendedMode || null; this._setPrompt(this._currentPrompt); this._setCommand(this._currentCommand); modes.set(modes.COMMAND_LINE, this._currentExtendedMode); this.show(); this._history = CommandLine.History(this._commandWidget.inputField, (modes.extended == modes.EX) ? "command" : "search"); this._completions = CommandLine.Completions(this._commandWidget.inputField); // open the completion list automatically if wanted if (cmd.length) commandline.triggerCallback("change", this._currentExtendedMode, cmd); this._resetStatusline(); }, /** * Closes the command line. This is ordinarily triggered automatically * by a mode change. Will not hide the command line immediately if * called directly after a successful command, otherwise it will. */ close: function close() { this._keepOpenForInput = false; let mode = this._currentExtendedMode; this._currentExtendedMode = null; commandline.triggerCallback("cancel", mode); // FIXME if (this._history) { this._history.save(); this._history = null; } // The completion things must be always reset this.resetCompletions(); // cancels any asynchronous completion still going on, must be before we set completions = null this._completionList.hide(); this._completions = null; // liberator.log('closing with : ' + modes.main + "/" + modes.extended); // hint prompt is available if (this._startHints && modes.extended & modes.PROMPT) { this._startHints = false; return; } this._startHints = false; // don't have input and output widget open at the same time if (modes.extended & modes.INPUT_MULTILINE) this._outputContainer.collapsed = true; else if (modes.extended & modes.OUTPUT_MULTILINE) { this._multilineInputWidget.collapsed = true; liberator.focusContent(); } else { liberator.focusContent(); this._multilineInputWidget.collapsed = true; this._outputContainer.collapsed = true; if (this._messageBox.getAttributeNS(NS.uri, "highlight") === this.HL_MOREMSG) this._messageBox.value = ""; this.hide(); //modes.pop(true); modes.reset(); } }, /** * Hides the command line, and shows any status messages that * are under it. */ hide: function hide() { // liberator.log('hiding commandline'); this._commandlineWidget.classList.add("hidden"); this._commandWidget.blur(); // needed for the sliding animation of the prompt text to be shown correctly // on subsequent calls this._setPrompt(""); }, /** * Make the command line visible, hiding the status messages below * * @param {string} text: Optionally set the command line's text to this string */ show: function (text, prompt) { if (typeof(text) === "string") this._setCommand(text); if (typeof(prompt) === "string") this._setPrompt(prompt); this._commandlineWidget.classList.remove("hidden"); this._commandWidget.focus(); }, /** * Output the given string onto the command line. With no flags, the * message will be shown in the status line if it's short enough to * fit, and contains no new lines, and isn't XML. Otherwise, it will be * shown in the MOW. * * @param {string} str * @param {string} highlightGroup The Highlight group for the * message. * @default "Normal" * @param {number} flags Changes the behavior as follows: * commandline.APPEND_TO_MESSAGES - Causes message to be added to the * messages history, and shown by :messages. * commandline.FORCE_SINGLELINE - Forbids the command from being * pushed to the MOW if it's too long or of there are already * status messages being shown. * commandline.DISALLOW_MULTILINE - Cancels the operation if the MOW * is already visible. * commandline.FORCE_MULTILINE - Forces the message to appear in * the MOW. */ echo: function echo(str, highlightGroup, flags) { if ((flags & this.FORCE_SINGLELINE) && (flags & this.FORCE_MULTILINE)) return liberator.echoerr("Conflicted flags argument for echo(): FORCE_SINGLELINE | FORCE_MULTILINE"); // liberator.echo uses different order of flags as it omits the highlight group, // change commandline.echo argument order? --mst if (this._silent) return; highlightGroup = highlightGroup || this.HL_NORMAL; if (flags & this.APPEND_TO_MESSAGES) this._messageHistory.add({ str: str, highlight: highlightGroup }); // The DOM isn't threadsafe. It must only be accessed from the main thread. liberator.callInMainThread(function () { if ((flags & this.DISALLOW_MULTILINE) && !this._outputContainer.collapsed) return; let single = flags & (this.FORCE_SINGLELINE | this.DISALLOW_MULTILINE); let action = this._echoLine; // TODO: this is all a bit convoluted - clean up. // assume that FORCE_MULTILINE output is fully styled if (!(flags & this.FORCE_MULTILINE) && !single && (!this._outputContainer.collapsed || this._messageBox.value == this._lastEcho)) { highlightGroup += " Message"; action = this._echoMultiline; } if ((flags & this.FORCE_MULTILINE) || (/\n/.test(str) || typeof str == "xml" || str instanceof TemplateSupportsXML ) && !(flags & this.FORCE_SINGLELINE)) action = this._echoMultiline; if (single) this._lastEcho = null; else { if (this._messageBox.value == this._lastEcho) this._echoMultiline(xml`<span highlight="Message">${this._lastEcho}</span>`, this._messageBox.getAttributeNS(NS.uri, "highlight")); this._lastEcho = (action == this._echoLine) && str; } if (action) action.call(this, str, highlightGroup, single); }, this); }, /** * Prompt the user. Sets modes.main to COMMAND_LINE, which the user may * pop at any time to close the prompt. * * @param {string} prompt The input prompt to use. * @param {function(string)} callback * @param {Object} extra * @... {function} onChange - A function to be called with the current * input every time it changes. * @... {function(CompletionContext)} completer - A completion function * for the user's input. * @... {string} promptHighlight - The HighlightGroup used for the * prompt. @default "Question" * @... {string} default - The initial value that will be returned * if the user presses <CR> straightaway. @default "" */ input: function _input(prompt, callback, extra) { extra = extra || {}; this._input = { submit: callback, change: extra.onChange, complete: extra.completer, cancel: extra.onCancel }; this._keepOpenForInput = true; modes.set(modes.COMMAND_LINE, modes.PROMPT); this._currentExtendedMode = modes.PROMPT; this._setPrompt(prompt, extra.promptHighlight || this.HL_QUESTION); this._setCommand(extra.default || ""); // this._commandlineWidget.collapsed = false; this.show(); this._commandWidget.focus(); this._history = CommandLine.History(this._commandWidget.inputField, (modes.extended == modes.EX) ? "command" : "search"); this._completions = CommandLine.Completions(this._commandWidget.inputField); }, /** * Get a multiline input from a user, up to but not including the line * which matches the given regular expression. Then execute the * callback with that string as a parameter. * * @param {RegExp} untilRegexp * @param {function(string)} callbackFunc */ // FIXME: Buggy, especially when pasting. Shouldn't use a RegExp. inputMultiline: function inputMultiline(untilRegexp, callbackFunc) { modes.set(modes.COMMAND_LINE, modes.INPUT_MULTILINE); //this._currentExtendedMode = modes.PROMPT; // like in input: ? // save the arguments, they are needed in the event handler onEvent this._multilineRegexp = untilRegexp; this._multilineCallback = callbackFunc; this._multilineInputWidget.collapsed = false; this._multilineInputWidget.value = ""; this._autosizeMultilineInputWidget(); this.setTimeout(function () { this._multilineInputWidget.focus(); }, 10); }, /** * Handles all command-line events. All key events are passed here when * COMMAND_LINE mode is active, as well as all input, keyup, focus, and * blur events sent to the command-line XUL element. * * @param {Event} event * @private */ onEvent: function onEvent(event) { let command = this.command; if (event.type == "blur") { // prevent losing focus, there should be a better way, but it just didn't work otherwise this.setTimeout(function () { if (this._commandShown() && event.originalTarget == this._commandWidget.inputField) this._commandWidget.inputField.focus(); }, 0); } else if (event.type == "focus") { if (!this._commandShown() && event.originalTarget == this._commandWidget.inputField) { event.originalTarget.blur(); } } else if (event.type == "input") { this.resetCompletions(); commandline.triggerCallback("change", this._currentExtendedMode, command); } else if (event.type == "keypress") { let key = events.toString(event); if (this._completions) this._completions.previewClear(); if (!this._currentExtendedMode) return; // user pressed <Enter> to carry out a command // user pressing <Esc> is handled in the global onEscape // FIXME: <Esc> should trigger "cancel" event if (events.isAcceptKey(key)) { //let currentExtendedMode = this._currentExtendedMode; //this._currentExtendedMode = null; // Don't let modes.pop trigger "cancel" commandline.triggerCallback("submit", this._currentExtendedMode, command); if (!this._keepOpenForInput) this.close(); } // user pressed <Up> or <Down> arrow to cycle this._history completion else if (/^<(Up|Down|S-Up|S-Down|PageUp|PageDown)>$/.test(key)) { // prevent tab from moving to the next field event.preventDefault(); event.stopPropagation(); liberator.assert(this._history); this._history.select(/Up/.test(key), !/(Page|S-)/.test(key)); } // user pressed <Tab> to get completions of a command else if (/^<(Tab|S-Tab)>$/.test(key)) { // prevent tab from moving to the next field event.preventDefault(); event.stopPropagation(); this._tabTimer.tell(event); } else if (key == "<BS>") { // reset the tab completion //this.resetCompletions(); // and blur the command line if there is no text left if (command.length == 0) { commandline.triggerCallback("cancel", this._currentExtendedMode); //modes.pop(); modes.reset(); } } else { // any other key //this.resetCompletions(); } // allow this event to be handled by the host app } else if (event.type == "keyup") { let key = events.toString(event); if (/^<(Tab|S-Tab)>$/.test(key)) this._tabTimer.flush(); } }, /** * Multiline input events, they will come straight from * #liberator-multiline-input in the XUL. * * @param {Event} event */ onMultilineInputEvent: function onMultilineInputEvent(event) { if (event.type == "keypress") { let key = events.toString(event); if (events.isAcceptKey(key)) { let text = this._multilineInputWidget.value.substr(0, this._multilineInputWidget.selectionStart); if (text.match(this._multilineRegexp)) { text = text.replace(this._multilineRegexp, ""); modes.reset(); this._multilineInputWidget.collapsed = true; this._multilineCallback.call(this, text); } } else if (events.isCancelKey(key)) { modes.reset(); this._multilineInputWidget.collapsed = true; } } else if (event.type == "blur") { if (modes.extended & modes.INPUT_MULTILINE) this.setTimeout(function () { this._multilineInputWidget.inputField.focus(); }, 0); } else if (event.type == "input") this._autosizeMultilineInputWidget(); return true; }, /** * Handle events when we are in multiline output mode, these come from * liberator when modes.extended & modes.MULTILINE_OUTPUT and also from * #liberator-multiline-output in the XUL. * * @param {Event} event */ onMultilineOutputEvent: function onMultilineOutputEvent(event) { let win = this._multilineOutputWidget.contentWindow; let key = events.toString(event); if (event.type == "click" && event.target instanceof HTMLAnchorElement) { function openLink(where) { event.preventDefault(); // FIXME: Why is this needed? --djk if (event.target.getAttribute("href") == "#") liberator.open(event.target.textContent, where); else liberator.open(event.target.href, where); } switch (key) { case "<LeftMouse>": if (event.originalTarget.getAttributeNS(NS.uri, "highlight") == "URL buffer-list") { event.preventDefault(); let textContent = event.originalTarget.parentNode.parentNode.firstElementChild.textContent.trim(); tabs.select(parseInt(textContent.replace(/^[^\d]*/, ""), 10) - 1, false, true); } else openLink(liberator.CURRENT_TAB); break; case "<MiddleMouse>": case "<C-LeftMouse>": case "<C-M-LeftMouse>": openLink(liberator.NEW_BACKGROUND_TAB); break; case "<S-MiddleMouse>": case "<C-S-LeftMouse>": case "<C-M-S-LeftMouse>": openLink(liberator.NEW_TAB); break; case "<S-LeftMouse>": openLink(liberator.NEW_WINDOW); break; } return; } let isScrollable = win.scrollMaxY !== 0; let showHelp = false; switch (key) { // close the window case "<Esc>": case "q": modes.reset(); return; // handled globally in events.js:onEscape() // reopen command line case ":": commandline.open("", "", modes.EX); break; // extended hint modes case ";": this._startHints = true; hints.startExtendedHint("", win) return; // down a line case "j": case "<Down>": case "<C-j>": case "<C-m>": case "<Return>": if (isScrollable) win.scrollByLines(1); else showHelp = true; break; // up a line case "k": case "<Up>": case "<BS>": if (isScrollable) win.scrollByLines(-1); else showHelp = true; break; // half page down case "d": if (isScrollable) win.scrollBy(0, win.innerHeight / 2); else showHelp = true; break; // half page up case "u": if (isScrollable) win.scrollBy(0, -(win.innerHeight / 2)); else showHelp = true; break; // page down case "f": case "<C-f>": case "<Space>": case "<PageDown>": if (isScrollable) win.scrollByPages(1); else showHelp = true; break; // page up case "b": case "<C-f>": case "<PageUp>": if (isScrollable) win.scrollByPages(-1); else showHelp = true; break; // top of page case "g": case "<Home>": if (isScrollable) win.scrollTo(0, 0); else showHelp = true; break; // bottom of page case "G": case "<End>": if (isScrollable) win.scrollTo(0, win.scrollMaxY); else showHelp = true; break; case "Y": let (sel = win.getSelection().toString()) { if (sel) util.copyToClipboard(sel, false); else showHelp = true; } break; // unmapped key -> show Help default: showHelp = true; } if (showHelp) { this.hide(); // hide the command line let helpMsg = "Y: yank | ;o: follow hint | ESC/q: quit"; if (isScrollable) helpMsg = "SPACE/d/j: screen/page/line down | b/u/k: screen/page/line up | " + "HOME/g: top | END/G: bottom | " + helpMsg; this._echoLine(helpMsg, this.HL_MOREMSG, true); } else { this.show(); } }, getSpaceNeeded: function getSpaceNeeded() { let rect = this._commandlineWidget.getBoundingClientRect(); let offset = rect.bottom - window.innerHeight; return Math.max(0, offset); }, /** * Changes the height of the message window to fit in the available space. * * @param {boolean} open If true, the widget will be opened if it's not * already so. */ updateOutputHeight: function updateOutputHeight(open) { if (!open && this._outputContainer.collapsed) return; let doc = this._multilineOutputWidget.contentDocument; // xxx: //let availableHeight = config.outputHeight; //if (!this._outputContainer.collapsed) // availableHeight += parseFloat(this._outputContainer.height); doc.body.style.minWidth = this._commandlineWidget.scrollWidth + "px"; this._outputContainer.style.bottom = this.bottombarPosition; this._outputContainer.style.maxHeight = (this._outputContainer.height = Math.min(doc.body.clientHeight, config.outputHeight)) + "px"; doc.body.style.minWidth = ""; this._outputContainer.collapsed = false; }, resetCompletions: function resetCompletions() { if (this._completions) { this._completions.context.cancelAll(); this._completions.wildIndex = -1; this._completions.previewClear(); } if (this._history) this._history.reset(); }, // related floatbox get bottombarPosition() (document.documentElement.boxObject.height - this._bottomBarWidget.boxObject.y) + "px", }, { /** * A class for managing the history of an input field. * * @param {HTMLInputElement} inputField * @param {string} mode The mode for which we need history. */ History: Class("History", { init: function (inputField, mode) { this.mode = mode; this.input = inputField; this.store = storage["history-" + mode]; this.reset(); }, /** * Reset the history index to the first entry. */ reset: function () { this.index = null; }, /** * Save the last entry to the permanent store. All duplicate entries * are removed and the list is truncated, if necessary. */ save: function () { if (events.feedingKeys) return; let str = this.input.value; if (/^\s*$/.test(str)) return; this.store.mutate("filter", function (line) (line.value || line) != str); this.store.push({ value: str, timestamp: Date.now(), privateData: this.checkPrivate(str) }); this.store.truncate(options["history"], true); }, /** * @property {function} Returns whether a data item should be * considered private. */ checkPrivate: function (str) { // Not really the ideal place for this check. if (this.mode == "command") return (commands.get(commands.parseCommand(str)[1]) || {}).privateData; return false; }, /** * Removes any private data from this history. */ sanitize: function (timespan) { let range = [0, Number.MAX_VALUE]; if (liberator.has("sanitizer") && (timespan || options["sanitizetimespan"])) range = sanitizer.getClearRange(timespan || options["sanitizetimespan"]); const self = this; this.store.mutate("filter", function (item) { let timestamp = (item.timestamp || Date.now()/1000) * 1000; return !line.privateData || timestamp < self.range[0] || timestamp > self.range[1]; }); }, /** * Replace the current input field value. * * @param {string} val The new value. */ replace: function (val) { this.input.value = val; commandline.triggerCallback("change", this._currentExtendedMode, val); }, /** * Move forward or backward in history. * * @param {boolean} backward Direction to move. * @param {boolean} matchCurrent Search for matches starting * with the current input value. */ select: function (backward, matchCurrent) { // always reset the tab completion if we use up/down keys commandline._completions.reset(); let diff = backward ? -1 : 1; if (this.index == null) { this.original = this.input.value; this.index = this.store.length; } // search the this._history for the first item matching the current // commandline string while (true) { this.index += diff; if (this.index < 0 || this.index > this.store.length) { this.index = util.Math.constrain(this.index, 0, this.store.length); liberator.beep(); // I don't know why this kludge is needed. It // prevents the caret from moving to the end of // the input field. if (this.input.value == "") { this.input.value = " "; this.input.value = ""; } break; } let hist = this.store.get(this.index); // user pressed DOWN when there is no newer this._history item if (!hist) hist = this.original; else hist = (hist.value || hist); if (!matchCurrent || hist.substr(0, this.original.length) == this.original) { this.replace(hist); break; } } } }), /** * A class for tab completions on an input field. * * @param {Object} input */ Completions: Class("Completions", { init: function (input) { this.context = CompletionContext(input); this.context.onUpdate = this.closure._reset; this.editor = input.editor; this.selected = null; this.wildmode = options.get("wildmode"); this.itemList = commandline._completionList; this.itemList.setItems(this.context); this.reset(); }, UP: {}, DOWN: {}, PAGE_UP: {}, PAGE_DOWN: {}, RESET: null, get completion() { let str = commandline.command; return str.substring(this.prefix.length, str.length - this.suffix.length); }, set completion(completion) { this.previewClear(); // Change the completion text. // The second line is a hack to deal with some substring // preview corner cases. let (str = this.prefix + completion + this.suffix) { commandline._commandWidget.value = str; this.editor.selection.focusNode.textContent = str; } // Reset the caret to one position after the completion. this.caret = this.prefix.length + completion.length; }, get caret() commandline._commandWidget.selectionEnd, set caret(offset) { commandline._commandWidget.selectionStart = offset; commandline._commandWidget.selectionEnd = offset; }, get start() this.context.allItems.start, get items() this.context.allItems.items, get substring() this.context.longestAllSubstring, get wildtype() this.wildtypes[this.wildIndex] || "", get type() ({ list: this.wildmode.checkHas(this.wildtype, "list"), longest: this.wildmode.checkHas(this.wildtype, "longest"), first: this.wildmode.checkHas(this.wildtype, ""), full: this.wildmode.checkHas(this.wildtype, "full") }), complete: function complete(show, tabPressed) { this.context.reset(); this.context.tabPressed = tabPressed; commandline.triggerCallback("complete", commandline._currentExtendedMode, this.context); this.context.updateAsync = true; this.reset(show, tabPressed); this.wildIndex = 0; }, preview: function preview() { this.previewClear(); if (this.wildIndex < 0 || this.suffix || !this.items.length) return; let substring = ""; switch (this.wildtype.replace(/.*:/, "")) { case "": substring = this.items[0].text; break; case "longest": if (this.items.length > 1) { substring = this.substring; break; } // Fallthrough case "full": let item = this.items[this.selected != null ? this.selected + 1 : 0]; if (item) substring = item.text; break; } // Don't show 1-character substrings unless we've just hit backspace if (substring.length < 2 && (!this._lastSubstring || !this._lastSubstring.startsWith(substring))) return; this._lastSubstring = substring; let value = this.completion; if (util.compareIgnoreCase(value, substring.substr(0, value.length))) return; substring = substring.substr(value.length); this.removeSubstring = substring; let node = util.xmlToDom(xml`<span highlight="Preview">${substring}</span>`, document); let start = this.caret; this.editor.insertNode(node, this.editor.rootElement, 1); this.caret = start; }, previewClear: function previewClear() { let node = this.editor.rootElement.firstChild; if (node && node.nextSibling) { try { this.editor.deleteNode(node.nextSibling); } catch (e) { node.nextSibling.textContent = ""; } } else if (this.removeSubstring) { let str = this.removeSubstring; let cmd = commandline._commandWidget.value; if (cmd.substr(cmd.length - str.length) == str) commandline._commandWidget.value = cmd.substr(0, cmd.length - str.length); } delete this.removeSubstring; }, reset: function reset(show) { this.wildIndex = -1; this.prefix = this.context.value.substring(0, this.start); this.value = this.context.value.substring(this.start, this.caret); this.suffix = this.context.value.substring(this.caret); if (show) { this.itemList.reset(); this.selected = null; this.wildIndex = 0; } this.wildtypes = this.wildmode.values; this.preview(); }, // FIXME: having reset() and _reset() really sucks! _reset: function _reset() { this.prefix = this.context.value.substring(0, this.start); this.value = this.context.value.substring(this.start, this.caret); this.suffix = this.context.value.substring(this.caret); if (this.selected >= this.items.length) this.selected = null; this.itemList.reset(); this.itemList.selectItem(this.selected); this.preview(); }, select: function select(idx) { switch (idx) { case this.UP: if (this.selected == null) idx = -2; else idx = this.selected - 1; break; case this.DOWN: if (this.selected == null) idx = 0; else idx = this.selected + 1; break; case this.RESET: idx = null; break; default: idx = util.Math.constrain(idx, 0, this.items.length - 1); break; } if (idx == -1 || this.items.length && idx >= this.items.length || idx == null) { // Wrapped. Start again. this.selected = null; this.completion = this.value; } else { // Wait for contexts to complete if necessary. // FIXME: Need to make idx relative to individual contexts. let list = this.context.contextList; if (idx == -2) list = list.slice().reverse(); let n = 0; try { this.waiting = true; for (let context of list) { function done() !(idx >= n + context.items.length || idx == -2 && !context.items.length); while (context.incomplete && !done()) liberator.threadYield(false, true); if (done()) break; n += context.items.length; } } finally { this.waiting = false; } // See previous FIXME. This will break if new items in // a previous context come in. if (idx < 0) idx = this.items.length - 1; if (this.items.length == 0) return; this.selected = idx; this.completion = this.items[idx].text; } this.itemList.selectItem(idx); }, tabs: [], tab: function tab(reverse) { commandline._autocompleteTimer.flush(); // Check if we need to run the completer. if (this.context.waitingForTab || this.wildIndex == -1) this.complete(true, true); this.tabs.push(reverse); if (this.waiting) return; while (this.tabs.length) { reverse = this.tabs.shift(); switch (this.wildtype.replace(/.*:/, "")) { case "": this.select(0); break; case "longest": if (this.items.length > 1) { if (this.substring && this.substring != this.completion) this.completion = this.substring; break; } // Fallthrough case "full": this.select(reverse ? this.UP : this.DOWN); break; } if (this.type.list) this.itemList.show(); this.wildIndex = util.Math.constrain(this.wildIndex + 1, 0, this.wildtypes.length - 1); this.preview(); commandline._statusTimer.tell(); } if (this.items.length == 0) liberator.beep(); } }), /** * eval() a JavaScript expression and return a string suitable * to be echoed. * * @param {string} arg * @param {boolean} useColor When true, the result is a * highlighted XML object. */ echoArgumentToString: function (arg, useColor) { if (!arg) return ""; try { arg = liberator.eval(arg); } catch (e) { liberator.echoerr(e); return null; } if (arg instanceof TemplateSupportsXML); else if (typeof arg === "object") arg = util.objectToString(arg, useColor); else arg = String(arg); if (typeof arg == "string" && /\n/.test(arg)) arg = xml`<span highlight="CmdOutput">${arg}</span>`; return arg; } }, { commands: function () { [ { name: "ec[ho]", description: "Echo the expression", action: liberator.echo }, { name: "echoe[rr]", description: "Echo the expression as an error message", action: liberator.echoerr }, { name: "echom[sg]", description: "Echo the expression as an informational message", action: liberator.echomsg } ].forEach(function (command) { commands.add([command.name], command.description, function (args) { var str = args.literalArg; let str = CommandLine.echoArgumentToString(str, true); if (str != null) command.action(str); }, { completer: function (context) completion.javascript(context), literal: 0 }); }); commands.add(["mes[sages]"], "Display previously given messages", function () { if (commandline._messageHistory.length == 0) liberator.echomsg("No previous messages"); // TODO: are all messages single line? Some display an aggregation // of single line messages at least. E.g. :source /*if (commandline._messageHistory.length == 1) { let message = commandline._messageHistory.messages[0]; commandline.echo(message.str, message.highlight, commandline.FORCE_SINGLELINE); }*/ else { //if (commandline._messageHistory.length > 1) { let list = template.map2(xml, commandline._messageHistory.messages, function (message) xml`<div highlight=${message.highlight + " Message"}>${message.str}</div>`); liberator.echo(list, commandline.FORCE_MULTILINE); } }, { argCount: "0" }); commands.add(["messc[lear]"], "Clear the :messages list", function () { commandline._messageHistory.clear(); }, { argCount: "0" }); commands.add(["sil[ent]"], "Run a command silently", function (args) { commandline.runSilently(function () liberator.execute(args[0], null, true)); }, { completer: function (context) completion.ex(context), literal: 0 }); }, mappings: function () { var myModes = [modes.COMMAND_LINE]; // TODO: move "<Esc>", "<C-[>" here from mappings mappings.add(myModes, ["<C-c>"], "Focus content", function () { let controller = window.document.commandDispatcher.getControllerForCommand("cmd_copy"); if (controller && controller.isCommandEnabled("cmd_copy")) controller.doCommand("cmd_copy"); else events.onEscape(); }); // Any "non-keyword" character triggers abbreviation expansion // TODO: Add "<CR>" and "<Tab>" to this list // At the moment, adding "<Tab>" breaks tab completion. Adding // "<CR>" has no effect. // TODO: Make non-keyword recognition smarter so that there need not // be two lists of the same characters (one here and a regex in // mappings.js) mappings.add(myModes, ["<Space>", '"', "'"], "Expand command line abbreviation", function () { commandline.resetCompletions(); return editor.expandAbbreviation(modes.COMMAND_LINE); }, { route: true }); mappings.add(myModes, ["<C-]>", "<C-5>"], "Expand command line abbreviation", function () { editor.expandAbbreviation(modes.COMMAND_LINE); }); mappings.add([modes.NORMAL], ["g<"], "Redisplay the last command output", function () { let lastMowOutput = commandline._lastMowOutput; liberator.assert(lastMowOutput); commandline._echoMultiline(lastMowOutput, commandline.HL_NORMAL); }); }, options: function () { options.add(["autocomplete", "ac"], "Automatically list completions while typing", "boolean", true); options.add(["complete", "cpt"], "Items which are completed at the :open prompts", "charlist", typeof(config.defaults["complete"]) == "string" ? config.defaults["complete"] : "slf", { completer: function (context) array(values(completion.urlCompleters)) }); options.add(["history", "hi"], "Number of Ex commands and search patterns to store in the command-line this._history", "number", 500, { validator: function (value) value >= 0 }); options.add(["maxitems"], "Maximum number of items to display at once", "number", 20, { validator: function (value) value >= 1 }); options.add(["messages", "msgs"], "Number of messages to store in the message this._history", "number", 100, { validator: function (value) value >= 0 }); options.add(["messagetimeout", "mto"], "Automatically hide messages after a timeout (in ms)", "number", 10000, { completer: function (context) [ ["-1", "Keep forever"], ["0", "Close immediately"], ], validator: function (value) value >= -1 }); options.add(["showmode", "smd"], "Show the current mode in the command line", "boolean", true); options.add(["suggestengines"], "Engine Alias which has a feature of suggest", "stringlist", "google", { completer: function completer(value) { let engines = services.get("search").getEngines({}) .filter(function (engine) engine.supportsResponseType("application/x-suggestions+json")); return engines.map(function (engine) [engine.alias, engine.description]); } }); options.add(["wildmode", "wim"], "Define how command line completion works", "stringlist", "list:full", { completer: function (context) [ // Why do we need ""? ["", "Complete only the first match"], ["full", "Complete the next full match"], ["longest", "Complete to longest common string"], ["list", "If more than one match, list all matches"], ["list:full", "List all and complete first match"], ["list:longest", "List all and complete common string"] ], checkHas: function (value, val) { let [first, second] = value.split(":", 2); return first == val || second == val; } }); let idList = ["liberator-multiline-output", "liberator-completions"]; function floatBox(id) document.getElementById(id).parentNode let animation = "animation"; options.add(["animations", "ani"], "enabled animation", "boolean", false, { setter: function (value) { let attr = value ? "add" : "remove"; idList.forEach(function (id) { floatBox(id).classList[attr](animation); }); return value; }, getter: function () floatBox(idList[0]).classList.contains(animation), }); }, styles: function () { let fontSize = util.computedStyle(document.getElementById(config.mainWindowId)).fontSize; styles.registerSheet("chrome://liberator/skin/liberator.css"); let error = styles.addSheet(true, "font-size", "chrome://liberator/content/buffer.xhtml", "body { font-size: " + fontSize + "; }"); } }); /** * The list which is used for the completion box (and QuickFix window in * future). * * @param {string} id The id of the <iframe> which will display the list. It * must be in its own container element, whose height it will update as * necessary. */ const ItemList = Class("ItemList", { init: function (id) { this._completionElements = []; var iframe = document.getElementById(id); if (!iframe) { liberator.echoerr("No iframe with id: " + id + " found, strange things may happen!"); // "The truth is out there..." -- djk return; } this._doc = iframe.contentDocument; this._container = iframe.parentNode; this._doc.body.id = id + "-content"; this._doc.body.appendChild(this._doc.createTextNode("")); this._items = null; this._startIndex = -1; // The index of the first displayed item this._endIndex = -1; // The index one *after* the last displayed item this._selIndex = -1; // The index of the currently selected element this._div = null; this._divNodes = {}; this._minHeight = 0; }, _dom: function (xml, map) util.xmlToDom(xml, this._doc, map), _autoSize: function () { if (this._container.collapsed) this._div.style.minWidth = document.getElementById("liberator-commandline").scrollWidth + "px"; this._minHeight = Math.max(this._minHeight, this._divNodes.completions.getBoundingClientRect().bottom); this._container.style.maxHeight = this._minHeight + "px"; this._container.height = this._minHeight; if (this._container.collapsed) this._div.style.minWidth = ""; // FIXME: Belongs elsewhere. commandline.updateOutputHeight(false); this.setTimeout(function () { this._container.height -= commandline.getSpaceNeeded(); }, 0); }, // Our dotted separator does not look good in combination with // the completion window visible // FIXME: Probably not the right thing to do for some themes // Rather set a pseudo style which can be handled with :highlight _updateSeparatorVisibility: function () { let mowVisible = !(document.getElementById("liberator-multiline-output").parentNode.collapsed); let separator = document.getElementById("liberator-separator"); separator.collapsed = this.visible() && !mowVisible; }, _getCompletion: function (index) this._completionElements.snapshotItem(index - this._startIndex), _init: function () { this._div = this._dom( xml`<div class="ex-command-output" highlight="Normal" style="white-space: nowrap"> <div highlight="Completions" key="noCompletions"><span highlight="Title">No Completions</span></div> <div key="completions"/> <div highlight="Completions"> ${ template.map2(xml, util.range(0, options["maxitems"] * 2), function (i) xml`<span highlight="CompItem"> <li highlight="NonText">~</li> </span>`) } </div> </div>`, this._divNodes); this._doc.body.replaceChild(this._div, this._doc.body.firstChild); //div.scrollIntoView(true); this._items.contextList.forEach(function init_eachContext(context) { delete context.cache.nodes; if (!context.items.length && !context.message && !context.incomplete) return; context.cache.nodes = []; this._dom(xml`<div key="root" highlight="CompGroup"> <div highlight="Completions"> ${ context.createRow(context.title || [], "CompTitle") } </div> <div key="message" highlight="CompMsg"/> <div key="items" highlight="Completions"/> <div key="waiting" highlight="CompMsg">${ItemList.WAITING_MESSAGE}</div> </div>`, context.cache.nodes); this._divNodes.completions.appendChild(context.cache.nodes.root); }, this); setTimeout(this.closure._autoSize, 0); }, /** * Uses the entries in "items" to fill the listbox and does incremental * filling to speed up things. * * @param {number} offset Start at this index and show options["maxitems"]. */ _fill: function (offset) { let diff = offset - this._startIndex; if (this._items == null || offset == null || diff == 0 || offset < 0) return false; this._startIndex = offset; this._endIndex = Math.min(this._startIndex + options["maxitems"], this._items.allItems.items.length); let haveCompletions = false; let off = 0; let end = this._startIndex + options["maxitems"]; function getRows(context) { function fix(n) util.Math.constrain(n, 0, len); let len = context.items.length; let start = off; end -= !!context.message + context.incomplete; off += len; let s = fix(offset - start), e = fix(end - start); return [s, e, context.incomplete && e >= offset && off - 1 < end]; } this._items.contextList.forEach(function fill_eachContext(context) { let nodes = context.cache.nodes; if (!nodes) return; haveCompletions = true; let root = nodes.root; let items = nodes.items; let [start, end, waiting] = getRows(context); if (context.message) nodes.message.textContent = context.message; nodes.message.style.display = context.message ? "block" : "none"; nodes.waiting.style.display = waiting ? "block" : "none"; for (let [i, row] in Iterator(context.getRows(start, end, this._doc))) nodes[i] = row; for (let [i, row] in util.Array.iteritems(nodes)) { if (!row) continue; let display = (i >= start && i < end); if (display && row.parentNode != items) { do { var next = nodes[++i]; if (next && next.parentNode != items) next = null; } while (!next && i < end) items.insertBefore(row, next); } else if (!display && row.parentNode == items) items.removeChild(row); } }, this); this._divNodes.noCompletions.style.display = haveCompletions ? "none" : "block"; this._completionElements = util.evaluateXPath("//xhtml:div[@liberator:highlight='CompItem']", this._doc); return true; }, clear: function clear() { this.setItems(); this._doc.body.innerHTML = ""; }, hide: function hide() { this._container.collapsed = true; this._updateSeparatorVisibility(); }, show: function show() { this._container.style.bottom = commandline.bottombarPosition; this._container.collapsed = false; this._updateSeparatorVisibility(); }, visible: function visible() !this._container.collapsed, reset: function () { this._startIndex = this._endIndex = this._selIndex = -1; this._div = null; this.selectItem(-1); }, // if @param selectedItem is given, show the list and select that item setItems: function setItems(newItems, selectedItem) { if (this._container.collapsed) this._minHeight = 0; this._startIndex = this._endIndex = this._selIndex = -1; this._items = newItems; this.reset(); if (typeof selectedItem == "number") { this.selectItem(selectedItem); this.show(); } }, // select index, refill list if necessary selectItem: function selectItem(index) { if (this._div == null) this._init(); let sel = this._selIndex; let len = this._items.allItems.items.length; let newOffset = this._startIndex; let maxItems = options["maxitems"]; let contextLines = Math.min(3, parseInt((maxItems - 1) / 2)); if (index == -1 || index == null || index == len) { // wrapped around if (this._selIndex < 0) newOffset = 0; this._selIndex = -1; index = -1; } else { if (index <= this._startIndex + contextLines) newOffset = index - contextLines; if (index >= this._endIndex - contextLines) newOffset = index + contextLines - maxItems + 1; newOffset = Math.min(newOffset, len - maxItems); newOffset = Math.max(newOffset, 0); this._selIndex = index; } if (sel > -1) this._getCompletion(sel).removeAttribute("selected"); this._fill(newOffset); if (index >= 0) this._getCompletion(index).setAttribute("selected", "true"); }, onEvent: function onEvent(event) false }, { WAITING_MESSAGE: "Generating results..." }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const DEFAULT_FAVICON = "chrome://mozapps/skin/places/defaultFavicon.png"; // also includes methods for dealing with keywords and search engines const Bookmarks = Module("bookmarks", { requires: ["autocommands", "config", "liberator", "storage", "services"], init: function () { const faviconService = services.get("favicon"); const bookmarksService = services.get("bookmarks"); const historyService = services.get("history"); const tagging = PlacesUtils.tagging; function getFavicon (uri) { if (typeof uri === "string") uri = util.newURI(uri); var url = null; faviconService.getFaviconDataForPage(uri, function (iconURI) { url = iconURI ? iconURI.spec : ""; }); while (url === null) liberator.threadYield(false, true); return url; } this.getFavicon = getFavicon; // Fix for strange Firefox bug: // Error: [Exception... "Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIObserverService.addObserver]" // nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" // location: "JS frame :: file://~firefox/components/nsTaggingService.js :: anonymous :: line 89" // data: no] // Source file: file://~firefox/components/nsTaggingService.js tagging.getTagsForURI(window.makeURI("http://mysterious.bug"), {}); const Bookmark = Struct("url", "title", "icon", "keyword", "tags", "id"); const Keyword = Struct("keyword", "title", "icon", "url"); Bookmark.defaultValue("icon", function () getFavicon(this.url)); Bookmark.prototype.__defineGetter__("extra", function () [ ["keyword", this.keyword, "Keyword"], ["tags", this.tags.join(", "), "Tag"] ].filter(function (item) item[1])); const storage = modules.storage; function Cache(name, store) { const rootFolders = [bookmarksService.toolbarFolder, bookmarksService.bookmarksMenuFolder, bookmarksService.unfiledBookmarksFolder]; const sleep = liberator.sleep; // Storage objects are global to all windows, 'liberator' isn't. let bookmarks = []; let self = this; this.__defineGetter__("name", function () name); this.__defineGetter__("store", function () store); this.__defineGetter__("bookmarks", function () this.load()); this.__defineGetter__("keywords", function () [Keyword(k.keyword, k.title, k.icon, k.url) for (k of self.bookmarks) if (k.keyword)]); this.__iterator__ = function () (val for (val of self.bookmarks)); function loadBookmark(node) { if (node.uri == null) // How does this happen? return false; let uri = util.newURI(node.uri); let keyword = bookmarksService.getKeywordForBookmark(node.itemId); let tags = tagging.getTagsForURI(uri, {}) || []; let bmark = Bookmark(node.uri, node.title, node.icon, keyword, tags, node.itemId); bookmarks.push(bmark); return bmark; } function readBookmark(id) { return { itemId: id, uri: bookmarksService.getBookmarkURI(id).spec, title: bookmarksService.getItemTitle(id) }; } function deleteBookmark(id) { let length = bookmarks.length; bookmarks = bookmarks.filter(function (item) item.id != id); return bookmarks.length < length; } this.findRoot = function findRoot(id) { do { var root = id; id = bookmarksService.getFolderIdForItem(id); } while (id != bookmarksService.placesRoot && id != root); return root; }; this.isBookmark = function (id) rootFolders.indexOf(self.findRoot(id)) >= 0; // since we don't use a threaded bookmark loading (by set preload) // anymore, is this loading synchronization still needed? --mst let loading = false; this.load = function load() { if (loading) { while (loading) sleep(10); return bookmarks; } // update our bookmark cache bookmarks = []; loading = true; let folders = rootFolders.slice(); let query = historyService.getNewQuery(); let options = historyService.getNewQueryOptions(); while (folders.length > 0) { query.setFolders(folders, 1); folders.shift(); let result = historyService.executeQuery(query, options); let folder = result.root; folder.containerOpen = true; // iterate over the immediate children of this folder for (let i = 0; i < folder.childCount; i++) { let node = folder.getChild(i); if (node.type == node.RESULT_TYPE_FOLDER) // folder folders.push(node.itemId); else if (node.type == node.RESULT_TYPE_URI) // bookmark loadBookmark(node); } // close a container after using it! folder.containerOpen = false; } this.__defineGetter__("bookmarks", function () bookmarks); loading = false; return bookmarks; }; var observer = { onBeginUpdateBatch: function onBeginUpdateBatch() {}, onEndUpdateBatch: function onEndUpdateBatch() {}, onItemVisited: function onItemVisited() {}, onItemMoved: function onItemMoved() {}, onItemAdded: function onItemAdded(itemId, folder, index) { if (bookmarksService.getItemType(itemId) == bookmarksService.TYPE_BOOKMARK) { if (self.isBookmark(itemId)) { let bmark = loadBookmark(readBookmark(itemId)); storage.fireEvent(name, "add", bmark); statusline.updateField("bookmark"); } } }, onItemRemoved: function onItemRemoved(itemId, folder, index) { if (deleteBookmark(itemId)) { storage.fireEvent(name, "remove", itemId); statusline.updateField("bookmark"); } }, onItemChanged: function onItemChanged(itemId, property, isAnnotation, value) { if (isAnnotation) return; let bookmark = bookmarks.filter(function (item) item.id == itemId)[0]; if (bookmark) { if (property == "tags") value = tagging.getTagsForURI(util.newURI(bookmark.url), {}); if (property in bookmark) bookmark[property] = value; storage.fireEvent(name, "change", itemId); } }, QueryInterface: function QueryInterface(iid) { if (iid.equals(Ci.nsINavBookmarkObserver) || iid.equals(Ci.nsISupports)) return this; throw Cr.NS_ERROR_NO_INTERFACE; } }; bookmarksService.addObserver(observer, false); } let bookmarkObserver = function (key, event, arg) { if (event == "add") autocommands.trigger("BookmarkAdd", arg); }; this._cache = storage.newObject("bookmark-cache", Cache, { store: false }); storage.addObserver("bookmark-cache", bookmarkObserver, window); }, get format() ({ anchored: false, title: ["URL", "Info"], keys: { text: "url", description: "title", icon: function(item) item.icon || DEFAULT_FAVICON, extra: "extra", tags: "tags", keyword: "keyword" }, process: [template.icon, template.bookmarkDescription] }), // TODO: why is this a filter? --djk get: function get(filter, tags, maxItems, extra) { return completion.runCompleter("bookmark", filter, maxItems, tags, extra); }, // if starOnly = true it is saved in the unfiledBookmarksFolder, otherwise in the bookmarksMenuFolder add: function add(starOnly, title, url, keyword, tags, folder, force) { var bs = services.get("bookmarks"); try { let uri = util.createURI(url); if (!force) { for (let bmark in this._cache) { if (bmark[0] == uri.spec) { var id = bmark[5]; if (title) bs.setItemTitle(id, title); break; } } } let folderId = bs[starOnly ? "unfiledBookmarksFolder" : "bookmarksMenuFolder"]; if (folder) { let folders = folder.split("/"); if (!folders[folders.length - 1]) folders.pop(); let rootFolderId = folderId; if (folders[0] === "TOOLBAR") { rootFolderId = bs.toolbarFolder; folders.shift(); } let node = Bookmarks.getBookmarkFolder(folders, rootFolderId); if (node) folderId = node.itemId; else { liberator.echoerr("Bookmark folder is not found: `" + folder + "'"); return false; } } if (id == undefined) id = bs.insertBookmark(folderId, uri, -1, title || url); if (!id) return false; if (keyword) bs.setKeywordForBookmark(id, keyword); if (tags) { PlacesUtils.tagging.untagURI(uri, null); PlacesUtils.tagging.tagURI(uri, tags); } } catch (e) { liberator.echoerr(e); return false; } return true; }, toggle: function toggle(url) { if (!url) return; let count = this.remove(url); if (count > 0) liberator.echomsg("Removed bookmark: " + url); else { let title = buffer.title || url; let extra = ""; if (title != url) extra = " (" + title + ")"; this.add(true, title, url); liberator.echomsg("Added bookmark: " + url); } }, isBookmarked: function isBookmarked(url) services.get("bookmarks").isBookmarked(util.newURI(url)), // returns number of deleted bookmarks remove: function remove(url) { try { let uri = util.newURI(url); let bmarks = services.get("bookmarks").getBookmarkIdsForURI(uri, {}); bmarks.forEach(services.get("bookmarks").removeItem); return bmarks.length; } catch (e) { liberator.echoerr(e); return 0; } }, // TODO: add filtering // also ensures that each search engine has a Liberator-friendly alias getSearchEngines: function getSearchEngines() { let searchEngines = []; for (let [, engine] in Iterator(services.get("search").getVisibleEngines({}))) { let alias = engine.alias; if (!alias || !/^[a-z0-9_-]+$/.test(alias)) alias = engine.name.replace(/^\W*([a-zA-Z_-]+).*/, "$1").toLowerCase(); if (!alias) alias = "search"; // for search engines which we can't find a suitable alias // make sure we can use search engines which would have the same alias (add numbers at the end) let newAlias = alias; for (let j = 1; j <= 10; j++) { // <=10 is intentional if (!searchEngines.some(function (item) item[0] == newAlias)) break; newAlias = alias + j; } // only write when it changed, writes are really slow if (engine.alias != newAlias) engine.alias = newAlias; searchEngines.push([engine.alias, engine.description, engine.iconURI && engine.iconURI.spec]); } return searchEngines; }, getSuggestions: function getSuggestions(engineName, query, callback) { const responseType = "application/x-suggestions+json"; let engine = services.get("search").getEngineByAlias(engineName); if (engine && engine.supportsResponseType(responseType)) var queryURI = engine.getSubmission(query, responseType).uri.spec; if (!queryURI) return []; function process(resp) { let results = []; try { results = JSON.parse(resp.responseText)[1]; results = [[item, ""] for ([k, item] in Iterator(results)) if (typeof item == "string")]; } catch (e) {} if (!callback) return results; return callback(results); } let resp = util.httpGet(queryURI, callback && process); if (!callback) return process(resp); return null; }, // TODO: add filtering // format of returned array: // [keyword, helptext, url] getKeywords: function getKeywords() { return this._cache.keywords; }, // full search string including engine name as first word in @param text // if @param useDefSearch is true, it uses the default search engine // @returns the url for the search string // if the search also requires a postData, [url, postData] is returned getSearchURL: function getSearchURL(text, useDefsearch) { let searchString = (useDefsearch ? options["defsearch"] + " " : "") + text; // we need to make sure our custom alias have been set, even if the user // did not :open <tab> once before this.getSearchEngines(); // ripped from Firefox function getShortcutOrURI(url) { var keyword = url; var param = ""; var offset = url.indexOf(" "); if (offset > 0) { keyword = url.substr(0, offset); param = url.substr(offset + 1); } var engine = services.get("search").getEngineByAlias(keyword); if (engine) { var submission = engine.getSubmission(param, null); return [submission.uri.spec, submission.postData]; } let [shortcutURL, postData] = PlacesUtils.getURLAndPostDataForKeyword(keyword); if (!shortcutURL) return [url, null]; let data = window.unescape(postData || ""); if (/%s/i.test(shortcutURL) || /%s/i.test(data)) { var charset = ""; var matches = shortcutURL.match(/^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/); if (matches) [, shortcutURL, charset] = matches; else { try { charset = services.get("history").getCharsetForURI(window.makeURI(shortcutURL)); } catch (e) {} } var encodedParam; if (charset) encodedParam = escape(window.convertFromUnicode(charset, param)); else encodedParam = encodeURIComponent(param); shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param); if (/%s/i.test(data)) postData = window.getPostDataStream(data, param, encodedParam, "application/x-www-form-urlencoded"); } else if (param) return [shortcutURL, null]; return [shortcutURL, postData]; } let [url, postData] = getShortcutOrURI(searchString); if (url == searchString) return null; if (postData) return [url, postData]; return url; // can be null }, // if openItems is true, open the matching bookmarks items in tabs rather than display list: function list(filter, tags, openItems, maxItems, keyword) { // FIXME: returning here doesn't make sense // Why the hell doesn't it make sense? --Kris // Because it unconditionally bypasses the final error message // block and does so only when listing items, not opening them. In // short it breaks the :bmarks command which doesn't make much // sense to me but I'm old-fashioned. --djk let kw = (keyword == "") ? undefined : {keyword:keyword}; if (!openItems) return completion.listCompleter("bookmark", filter, maxItems, tags, kw, CompletionContext.Filter.textAndDescription); let items = completion.runCompleter("bookmark", filter, maxItems, tags, kw, CompletionContext.Filter.textAndDescription); if (items.length) return liberator.open(items.map(function (i) i.url), liberator.NEW_TAB); if (filter.length > 0 && tags.length > 0) liberator.echoerr("No bookmarks matching tags: \"" + tags + "\" and string: \"" + filter + "\""); else if (filter.length > 0) liberator.echoerr("No bookmarks matching string: \"" + filter + "\""); else if (tags.length > 0) liberator.echoerr("No bookmarks matching tags: \"" + tags + "\""); else liberator.echoerr("No bookmarks set"); return null; } }, { getBookmarkFolder: function (folders, rootFolderId) { var q = PlacesUtils.history.getNewQuery(), o = PlacesUtils.history.getNewQueryOptions(); if (rootFolderId == PlacesUtils.tagsFolderId) o.resultType = o.RESULTS_AS_TAG_QUERY; else { q.setFolders([rootFolderId], 1); o.expandQueries = false; } var res = PlacesUtils.history.executeQuery(q, o); var node = res.root; for (let folder of folders) { node = getFolderFromNode(node, folder); if (!node) break; } return node; function getFolderFromNode (node, title) { for (let child in Bookmarks.iterateFolderChildren(node)) { if (child.title == title && child instanceof Ci.nsINavHistoryContainerResultNode) { node.containerOpen = false; return child; } } return null; } }, iterateFolderChildren: function (node, onlyFolder, onlyWritable) { if (!node.containerOpen) node.containerOpen = true; for (let i = 0, len = node.childCount; i < len; i++) { let child = node.getChild(i); if (PlacesUtils.nodeIsContainer(child)) child.QueryInterface(Ci.nsINavHistoryContainerResultNode); if (PlacesUtils.nodeIsFolder(child)) { if (onlyWritable && child.childrenReadOnly) continue; } else if (onlyFolder) continue; yield child; } }, }, { commands: function () { commands.add(["ju[mps]"], "Show jumplist", function () { let sh = history.session; let jumps = [[idx == sh.index ? ">" : "", Math.abs(idx - sh.index), val.title, let(url=val.URI.spec) xml`<a highlight="URL" href=${url}>${url}</a>`] for ([idx, val] in Iterator(sh))]; let list = template.tabular([{ header: "Jump", style: "color: red", colspan: 2 }, { header: "", style: "text-align: right", highlight: "Number" }, { header: "Title", style: "width: 250px; max-width: 500px; overflow: hidden" }, { header: "URL", highlight: "URL jump-list" }], jumps); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); }, { argCount: "0" }); // TODO: Clean this up. function tags(context, args) { let filter = context.filter; let have = filter.split(","); args.completeFilter = have.pop(); let prefix = filter.substr(0, filter.length - args.completeFilter.length); let tags = util.Array.uniq(util.Array.flatten([b.tags for (b of bookmarks._cache.bookmarks)])); return [[prefix + tag, tag] for (tag of tags) if (have.indexOf(tag) < 0)]; } function title(context, args) { if (!args.bang) return [[content.document.title, "Current Page Title"]]; context.keys.text = "title"; context.keys.description = "url"; return bookmarks.get(args.join(" "), args["-tags"], null, { keyword: args["-keyword"], title: context.filter }); } function keyword(context, args) { let keywords = util.Array.uniq(util.Array.flatten([b.keyword for (b of bookmarks._cache.keywords)])); return [[kw, kw] for (kw of keywords)]; } commands.add(["bma[rk]"], "Add a bookmark", function (args) { let url = args.length == 0 ? buffer.URL : args[0]; let title = args["-title"] || (args.length == 0 ? buffer.title : null); let keyword = args["-keyword"] || null; let tags = args["-tags"] || []; let folder = args["-folder"] || ""; if (bookmarks.add(false, title, url, keyword, tags, folder, args.bang)) { let extra = (title == url) ? "" : " (" + title + ")"; liberator.echomsg("Added bookmark: " + url + extra); } else liberator.echoerr("Could not add bookmark: " + title); }, { argCount: "?", bang: true, completer: function (context, args) { if (!args.bang) { context.completions = [[content.document.documentURI, "Current Location"]]; return; } completion.bookmark(context, args["-tags"], { keyword: args["-keyword"], title: args["-title"] }); }, options: [[["-title", "-t"], commands.OPTION_STRING, null, title], [["-tags", "-T"], commands.OPTION_LIST, null, tags], [["-keyword", "-k"], commands.OPTION_STRING, function (arg) /\w/.test(arg)], [["-folder", "-f"], commands.OPTION_STRING, null, function (context, args) { return completion.bookmarkFolder(context, args, PlacesUtils.bookmarksMenuFolderId, true, true); }]], }); commands.add(["bmarks"], "List or open multiple bookmarks", function (args) { bookmarks.list(args.join(" "), args["-tags"] || [], args.bang, args["-max"], args["-keyword"] || []); }, { bang: true, completer: function completer(context, args) { context.quote = null; context.filter = args.join(" "); context.filters = [CompletionContext.Filter.textAndDescription]; let kw = (args["-keyword"]) ? {keyword: args["-keyword"]} : undefined; completion.bookmark(context, args["-tags"], kw); }, options: [[["-tags", "-T"], commands.OPTION_LIST, null, tags], [["-max", "-m"], commands.OPTION_INT], [["-keyword", "-k"], commands.OPTION_STRING, null, keyword]] }); commands.add(["delbm[arks]"], "Delete a bookmark", function (args) { if (args.bang) { commandline.input("This will delete all bookmarks. Would you like to continue? (yes/[no]) ", function (resp) { if (resp && resp.match(/^y(es)?$/i)) { bookmarks._cache.bookmarks.forEach(function (bmark) { services.get("bookmarks").removeItem(bmark.id); }); liberator.echomsg("All bookmarks deleted"); } }); } else { let url = args.string || buffer.URL; let deletedCount = bookmarks.remove(url); liberator.echomsg("Deleted " + deletedCount + " bookmark(s) with url: " + url.quote()); } }, { argCount: "?", bang: true, completer: function completer(context) completion.bookmark(context), literal: 0 }); }, mappings: function () { var myModes = config.browserModes; mappings.add(myModes, ["a"], "Open a prompt to bookmark the current URL", function () { let options = {}; let bmarks = bookmarks.get(buffer.URL).filter(function (bmark) bmark.url == buffer.URL); if (bmarks.length == 1) { let bmark = bmarks[0]; options["-title"] = bmark.title; if (bmark.keyword) options["-keyword"] = bmark.keyword; if (bmark.tags.length > 0) options["-tags"] = bmark.tags.join(", "); } else { if (buffer.title != buffer.URL) options["-title"] = buffer.title; } commandline.open("", commands.commandToString({ command: "bmark", options: options, arguments: [buffer.URL], bang: bmarks.length > 1 }), modes.EX); }); mappings.add(myModes, ["A"], "Toggle bookmarked state of current URL", function () { bookmarks.toggle(buffer.URL); }); }, options: function () { options.add(["defsearch", "ds"], "Set the default search engine", "string", "google", { completer: function completer(context) { completion.search(context, true); context.completions = [["", "Don't perform searches by default"]].concat(context.completions); } }); var browserSearch = services.get("search"); browserSearch.init(function() { var alias = browserSearch.defaultEngine.alias; if (alias) { let defsearch = options.get("defsearch"); // when already changed, it means the user had been changed in RC file if (defsearch.value === defsearch.defaultValue) defsearch.value = alias defsearch.defaultValue = alias; } }); }, completion: function () { completion.bookmark = function bookmark(context, tags, extra) { context.title = ["Bookmark", "Title"]; context.format = bookmarks.format; for (let val in Iterator(extra || [])) { let [k, v] = val; // Need block scope here for the closure if (v) context.filters.push(function (item) this._match(v, item[k] || "")); } // Need to make a copy because set completions() checks instanceof Array, // and this may be an Array from another window. context.completions = Array.slice(storage["bookmark-cache"].bookmarks); completion.urls(context, tags); }; completion.search = function search(context, noSuggest) { let [, keyword, space, args] = context.filter.match(/^\s*(\S*)(\s*)(.*)$/); let keywords = bookmarks.getKeywords(); let engines = bookmarks.getSearchEngines(); context.title = ["Search Keywords"]; context.completions = keywords.concat(engines); context.keys = { text: 0, description: 1, icon: function(item) item[2] || DEFAULT_FAVICON }; if (!space || noSuggest) return; context.fork("suggest", keyword.length + space.length, this, "searchEngineSuggest", keyword, true); let item = keywords.filter(function (k) k.keyword == keyword)[0]; if (item && item.url.indexOf("%s") > -1) { context.fork("keyword/" + keyword, keyword.length + space.length, null, function (context) { context.format = history.format; context.title = [keyword + " Quick Search"]; // context.background = true; context.compare = CompletionContext.Sort.unsorted; context.generate = function () { let [begin, end] = item.url.split("%s"); return history.get({ uri: window.makeURI(begin), uriIsPrefix: true }).map(function (item) { let rest = item.url.length - end.length; let query = item.url.substring(begin.length, rest); if (item.url.substr(rest) == end && query.indexOf("&") == -1) { query = query.replace(/#.*/, ""); // Countermeasure for "Error: malformed URI sequence". try { item.url = decodeURIComponent(query); } catch (e) { item.url = query; } return item; } return null; }).filter(util.identity); }; }); } }; completion.searchEngineSuggest = function searchEngineSuggest(context, engineAliases, kludge) { if (!context.filter) return; let engineList = (engineAliases || options["suggestengines"] || "google").split(","); engineList.forEach(function (name) { let engine = services.get("search").getEngineByAlias(name); if (!engine) return; let [, word] = /^\s*(\S+)/.exec(context.filter) || []; if (!kludge && word == name) // FIXME: Check for matching keywords return; let ctxt = context.fork(name, 0); ctxt.title = [engine.description + " Suggestions"]; ctxt.compare = CompletionContext.Sort.unsorted; ctxt.incomplete = true; ctxt.match = function (str) str.toLowerCase().indexOf(this.filter.toLowerCase()) === 0; bookmarks.getSuggestions(name, ctxt.filter, function (compl) { ctxt.incomplete = false; ctxt.completions = compl; }); }); }; completion.bookmarkFolder = function bookmarkFolder (context, args, rootFolderId, onlyFolder, onlyWritable) { let filter = context.filter, folders = filter.split("/"), item = folders.pop(); if (!rootFolderId) rootFolderId = PlacesUtils.bookmarksMenuFolderId; let folderPath = folders.length ? folders.join("/") + "/" : ""; if (folders[0] === "TOOLBAR") { rootFolderId = PlacesUtils.toolbarFolderId; folders.shift(); } let folder = Bookmarks.getBookmarkFolder(folders, rootFolderId); context.title = ["Bookmarks", folders.join("/") + "/"]; context._match = function (filter, str) str.toLowerCase().startsWith(filter.toLowerCase()); let results = []; if (folders.length === 0) { results.push(["TOOLBAR", "Bookmarks Toolbar"]); } if (folder) { for (let child in Bookmarks.iterateFolderChildren(folder, onlyFolder, onlyWritable)) { if (PlacesUtils.nodeIsSeparator(child)) continue; results.push([folderPath + PlacesUIUtils.getBestTitle(child), child.uri]); } folder.containerOpen = false; } return context.completions = results; }; completion.addUrlCompleter("S", "Suggest engines", completion.searchEngineSuggest); completion.addUrlCompleter("b", "Bookmarks", completion.bookmark); completion.addUrlCompleter("s", "Search engines and keyword URLs", completion.search); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ // do NOT create instances of this class yourself, use the helper method // options.add() instead /** * A class representing configuration options. Instances are created by the * {@link Options} class. * * @param {string[]} names The names by which this option is identified. * @param {string} description A short one line description of the option. * @param {string} type The option's value data type (see {@link Option#type}). * @param {string} defaultValue The default value for this option. * @param {Object} extraInfo An optional extra configuration hash. The * following properties are supported. * scope - see {@link Option#scope} * setter - see {@link Option#setter} * getter - see {@link Option#getter} * completer - see {@link Option#completer} * validator - see {@link Option#validator} * checkHas - see {@link Option#checkHas} * @optional * @private */ const Option = Class("Option", { init: function (names, description, type, defaultValue, extraInfo) { this.name = names[0]; this.names = names; this.type = type; this.description = description; if (arguments.length > 3) this.defaultValue = defaultValue; if (extraInfo) update(this, extraInfo); // add no{option} variant of boolean {option} to this.names if (this.type == "boolean") this.names = array([name, "no" + name] for (name in values(names))).flatten().__proto__; if (this.globalValue == undefined) this.globalValue = this.defaultValue; }, /** @property {value} The option's global value. @see #scope */ get globalValue() options.store.get(this.name), set globalValue(val) { options.store.set(this.name, val); }, /** * Returns <b>value</b> as an array of parsed values if the option type is * "charlist" or "stringlist" or else unchanged. * * @param {value} value The option value. * @returns {value|string[]} */ parseValues: function (value) { if (this.type == "stringlist") return (value === "") ? [] : value.split(","); if (this.type == "charlist") return Array.slice(value); return value; }, /** * Returns <b>values</b> packed in the appropriate format for the option * type. * * @param {value|string[]} values The option value. * @returns {value} */ joinValues: function (values) { if (this.type == "stringlist") return values.join(","); if (this.type == "charlist") return values.join(""); return values; }, /** @property {value|string[]} The option value or array of values. */ get values() this.parseValues(this.value), set values(values) this.setValues(values, this.scope), /** * Returns the option's value as an array of parsed values if the option * type is "charlist" or "stringlist" or else the simple value. * * @param {number} scope The scope to return these values from (see * {@link Option#scope}). * @returns {value|string[]} */ getValues: function (scope) this.parseValues(this.get(scope)), /** * Sets the option's value from an array of values if the option type is * "charlist" or "stringlist" or else the simple value. * * @param {number} scope The scope to apply these values to (see * {@link Option#scope}). */ setValues: function (values, scope) { this.set(this.joinValues(values), scope || this.scope); }, /** * Returns the value of the option in the specified <b>scope</b>. The * (@link Option#getter) callback, if it exists, is invoked with this value * before it is returned. * * @param {number} scope The scope to return this value from (see * {@link Option#scope}). * @returns {value} */ get: function (scope) { if (scope) { if ((scope & this.scope) == 0) // option doesn't exist in this scope return null; } else scope = this.scope; // Options with a custom getter are always responsible for returning a meaningful value if (this.getter) return liberator.trapErrors(this.getter, this, value); let value; if (liberator.has("tabs") && (scope & Option.SCOPE_LOCAL)) value = tabs.options[this.name]; if ((scope & Option.SCOPE_GLOBAL) && (value == undefined)) value = this.globalValue; return value; }, /** * Sets the option value to <b>newValue</b> for the specified <b>scope</b>. * The (@link Option#setter) callback, if it exists, is invoked with * <b>newValue</b>. * * @param {value} newValue The option's new value. * @param {number} scope The scope to apply this value to (see * {@link Option#scope}). */ set: function (newValue, scope) { scope = scope || this.scope; if ((scope & this.scope) == 0) // option doesn't exist in this scope return; if (this.setter) newValue = liberator.trapErrors(this.setter, this, newValue); if (liberator.has("tabs") && (scope & Option.SCOPE_LOCAL)) tabs.options[this.name] = newValue; if ((scope & Option.SCOPE_GLOBAL) && newValue != this.globalValue) this.globalValue = newValue; this.hasChanged = true; }, /** * @property {value} The option's current value. The option's local value, * or if no local value is set, this is equal to the * (@link #globalValue). */ get value() this.get(), set value(val) this.set(val), /** * Returns whether the option value contains one or more of the specified * arguments. * * @returns {boolean} */ has: function () { let self = this; let test = function (val) values.indexOf(val) >= 0; if (this.checkHas) test = function (val) values.some(function (value) self.checkHas(value, val)); let values = this.values; // return whether some argument matches return Array.some(arguments, function (val) test(val)); }, /** * Returns whether this option is identified by <b>name</b>. * * @param {string} name * @returns {boolean} */ hasName: function (name) this.names.indexOf(name) >= 0, /** * Returns whether the specified <b>values</b> are valid for this option. * @see Option#validator */ isValidValue: function (values) this.validator(values), /** * Resets the option to its default value. */ reset: function () { this.value = this.defaultValue; }, /** * Sets the option's value using the specified set <b>operator</b>. * * @param {string} operator The set operator. * @param {value|string[]} values The value (or values) to apply. * @param {number} scope The scope to apply this value to (see * {@link #scope}). * @param {boolean} invert Whether this is an invert boolean operation. */ op: function (operator, values, scope, invert) { let newValue = null; let self = this; switch (this.type) { case "boolean": if (operator != "=") break; if (invert) newValue = !this.value; else newValue = values; break; case "number": // TODO: support floats? Validators need updating. if (!/^[+-]?(?:0x[0-9a-f]+|0[0-7]+|0|[1-9]\d*)$/i.test(values)) return "Number required after := " + this.name + "=" + values; let value = parseInt(values/* deduce radix */); switch (operator) { case "+": newValue = this.value + value; break; case "-": newValue = this.value - value; break; case "^": newValue = this.value * value; break; case "=": newValue = value; break; } break; case "charlist": case "stringlist": values = Array.concat(values); switch (operator) { case "+": newValue = util.Array.uniq(Array.concat(this.values, values), true); break; case "^": // NOTE: Vim doesn't prepend if there's a match in the current value newValue = util.Array.uniq(Array.concat(values, this.values), true); break; case "-": newValue = this.values.filter(function (item) values.indexOf(item) == -1); break; case "=": newValue = values; if (invert) { let keepValues = this.values.filter(function (item) values.indexOf(item) == -1); let addValues = values.filter(function (item) self.values.indexOf(item) == -1); newValue = addValues.concat(keepValues); } break; } break; case "string": switch (operator) { case "+": newValue = this.value + values; break; case "-": newValue = this.value.replace(values, ""); break; case "^": newValue = values + this.value; break; case "=": newValue = values; break; } break; default: return "Internal error: option type `" + this.type + "' not supported"; } if (newValue == null) return "Operator " + operator + " not supported for option type " + this.type; if (!this.isValidValue(newValue)) return "Invalid argument: " + values; this.setValues(newValue, scope); return null; }, // Properties {{{2 /** @property {string} The option's canonical name. */ name: null, /** @property {string[]} All names by which this option is identified. */ names: null, /** * @property {string} The option's data type. One of: * "boolean" - Boolean E.g. true * "number" - Integer E.g. 1 * "string" - String E.g. "Vimperator" * "charlist" - Character list E.g. "rb" * "stringlist" - String list E.g. "homepage,quickmark,tabopen,paste" */ type: null, /** * @property {number} The scope of the option. This can be local, global, * or both. * @see Option#SCOPE_LOCAL * @see Option#SCOPE_GLOBAL * @see Option#SCOPE_BOTH */ scope: 1, // Option.SCOPE_GLOBAL // XXX set to BOTH by default someday? - kstep /** * @property {string} This option's description, as shown in :usage. */ description: "", /** * @property {value} The option's default value. This value will be used * unless the option is explicitly set either interactively or in an RC * file or plugin. */ defaultValue: null, /** * @property {function} The function called when the option value is set. */ setter: null, /** * @property {function} The function called when the option value is read. */ getter: null, /** * @property {function(CompletionContext, Args)} This option's completer. * @see CompletionContext */ completer: null, /** * @property {function} The function called to validate the option's value * when set. */ validator: function () { if (this.completer) return Option.validateCompleter.apply(this, arguments); return true; }, /** * @property The function called to determine whether the option already * contains a specified value. * @see #has */ checkHas: null, /** * @property {boolean} Set to true whenever the option is first set. This * is useful to see whether it was changed from its default value * interactively or by some RC file. */ hasChanged: false, /** * @property {nsIFile} The script in which this option was last set. null * implies an interactive command. */ setFrom: null }, { /** * @property {number} Global option scope. * @final */ SCOPE_GLOBAL: 1, /** * @property {number} Local option scope. Options in this scope only * apply to the current tab/buffer. * @final */ SCOPE_LOCAL: 2, /** * @property {number} Both local and global option scope. * @final */ SCOPE_BOTH: 3, // TODO: Run this by default? /** * Validates the specified <b>values</b> against values generated by the * option's completer function. * * @param {value|string[]} values The value or array of values to validate. * @returns {boolean} */ validateCompleter: function (values) { let context = CompletionContext(""); let res = context.fork("", 0, this, this.completer); if (!res) res = context.allItems.items.map(function (item) [item.text]); return Array.concat(values).every(function (value) res.some(function (item) item[0] == value)); } }); /** * @instance options */ const Options = Module("options", { requires: ["config", "highlight", "storage"], init: function () { this._optionHash = {}; this._prefContexts = []; for (let pref of this.allPrefs(Options.OLD_SAVED)) { let saved = Options.SAVED + pref.substr(Options.OLD_SAVED.length) if (!this.getPref(saved)) this.setPref(saved, this.getPref(pref)); this.resetPref(pref); } // Host application preferences which need to be changed to work well with // // Work around the popup blocker // TODO: Make this work like safeSetPref var popupAllowedEvents = this._loadPreference("dom.popup_allowed_events", "change click dblclick mouseup reset submit"); if (!/keypress/.test(popupAllowedEvents)) { this._storePreference("dom.popup_allowed_events", popupAllowedEvents + " keypress"); liberator.registerObserver("shutdown", function () { if (this._loadPreference("dom.popup_allowed_events", "") == popupAllowedEvents + " keypress") this._storePreference("dom.popup_allowed_events", popupAllowedEvents); }); } function optionObserver(key, event, option) { // Trigger any setters. let opt = options.get(option); if (event == "change" && opt) opt.set(opt.globalValue, Option.SCOPE_GLOBAL); } storage.newMap("options", { store: false }); storage.addObserver("options", optionObserver, window); this.prefObserver.register(); }, destroy: function () { this.prefObserver.unregister(); }, /** @property {Iterator(Option)} @private */ __iterator__: function () { let sorted = [o for ([i, o] in Iterator(this._optionHash))].sort(function (a, b) String.localeCompare(a.name, b.name)); return (v for (v of sorted)); }, /** @property {Object} Observes preference value changes. */ prefObserver: { register: function () { // better way to monitor all changes? this._branch = services.get("prefs").getBranch("").QueryInterface(Ci.nsIPrefBranch2); this._branch.addObserver("", this, false); }, unregister: function () { if (this._branch) this._branch.removeObserver("", this); }, observe: function (subject, topic, data) { if (topic != "nsPref:changed") return; // subject is the nsIPrefBranch we're observing (after appropriate QI) // data is the name of the pref that's been changed (relative to subject) switch (data) { case "accessibility.browsewithcaret": let value = options.getPref("accessibility.browsewithcaret", false); liberator.mode = value ? modes.CARET : modes.NORMAL; break; } } }, /** * Adds a new option. * * @param {string[]} names All names for the option. * @param {string} description A description of the option. * @param {string} type The option type (see {@link Option#type}). * @param {value} defaultValue The option's default value. * @param {Object} extra An optional extra configuration hash (see * {@link Map#extraInfo}). * @optional * @returns {Option} Returns the instace of Option, if the option was created. */ add: function (names, description, type, defaultValue, extraInfo) { if (!extraInfo) extraInfo = {}; let option = Option(names, description, type, defaultValue, extraInfo); if (!option) return false; if (option.name in this._optionHash) { // never replace for now liberator.echomsg("Option '" + names[0].quote() + "' already exists, NOT replacing existing option."); return false; } // quickly access options with options["wildmode"]: this.__defineGetter__(option.name, function () option.value); this.__defineSetter__(option.name, function (value) { option.value = value; }); this._optionHash[option.name] = option; return option; }, /** * Returns the names of all preferences. * * @param {string} branch The branch in which to search preferences. * @default "" */ allPrefs: function (branch) services.get("prefs").getChildList(branch || "", { value: 0 }), /** * Returns the option with <b>name</b> in the specified <b>scope</b>. * * @param {string} name The option's name. * @param {number} scope The option's scope (see {@link Option#scope}). * @optional * @returns {Option} The matching option. */ get: function (name, scope) { if (!scope) scope = Option.SCOPE_BOTH; if (name in this._optionHash) return (this._optionHash[name].scope & scope) && this._optionHash[name]; for (let opt in options) { if (opt.hasName(name)) return (opt.scope & scope) && opt; } return null; }, /** * Lists all options in <b>scope</b> or only those with changed values * if <b>onlyNonDefault</b> is specified. * * @param {boolean} onlyNonDefault Limit the list to prefs with a * non-default value. * @param {number} scope Only list options in this scope (see * {@link Option#scope}). */ list: function (onlyNonDefault, scope) { if (!scope) scope = Option.SCOPE_BOTH; function opts(opt) { for (let opt in options) { let option = { isDefault: opt.value == opt.defaultValue, name: opt.name, default: opt.defaultValue, pre: "\u00a0\u00a0", // Unicode nonbreaking space. value: xml`` }; if (onlyNonDefault && option.isDefault) continue; if (!(opt.scope & scope)) continue; if (opt.type == "boolean") { if (!opt.value) option.pre = "no"; option.default = (option.default ? "" : "no") + opt.name; } else option.value = xml`=${template.highlight(opt.value)}`; yield option; } }; let list = template.options("Options", opts()); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); }, /** * Lists all preferences matching <b>filter</b> or only those with * changed values if <b>onlyNonDefault</b> is specified. * * @param {boolean} onlyNonDefault Limit the list to prefs with a * non-default value. * @param {string} filter The list filter. A null filter lists all * prefs. * @optional */ listPrefs: function (onlyNonDefault, filter) { if (!filter) filter = ""; let prefArray = options.allPrefs(); prefArray.sort(); function prefs() { for (let pref of prefArray) { let userValue = services.get("prefs").prefHasUserValue(pref); if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1) continue; value = options.getPref(pref); let option = { isDefault: !userValue, default: options._loadPreference(pref, null, true), value: xml`${template.highlight(value, true, 100)}`, name: pref, pre: "\u00a0\u00a0" // Unicode nonbreaking space. }; yield option; } }; let list = template.options(config.hostApplication + " Options", prefs()); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); }, /** * Parses a :set command's argument string. * * @param {string} args The :set command's argument string. * @param {Object} modifiers A hash of parsing modifiers. These are: * scope - see {@link Option#scope} * @optional * @returns {Object} The parsed command object. */ parseOpt: function parseOpt(args, modifiers) { let ret = {}; let matches, prefix, postfix, valueGiven; [matches, prefix, ret.name, postfix, valueGiven, ret.operator, ret.value] = args.match(/^\s*(no|inv)?([a-z_]*)([?&!])?\s*(([-+^]?)=(.*))?\s*$/) || []; ret.args = args; ret.onlyNonDefault = false; // used for :set to print non-default options if (!args) { ret.name = "all"; ret.onlyNonDefault = true; } if (matches) ret.option = options.get(ret.name, ret.scope); ret.prefix = prefix; ret.postfix = postfix; ret.all = (ret.name == "all"); ret.get = (ret.all || postfix == "?" || (ret.option && ret.option.type != "boolean" && !valueGiven)); ret.invert = (prefix == "inv" || postfix == "!"); ret.reset = (postfix == "&"); ret.unsetBoolean = (prefix == "no"); ret.scope = modifiers && modifiers.scope; if (!ret.option) return ret; if (ret.value === undefined) ret.value = ""; ret.optionValue = ret.option.get(ret.scope); ret.optionValues = ret.option.getValues(ret.scope); ret.values = ret.option.parseValues(ret.value); return ret; }, /** * Remove the option with matching <b>name</b>. * * @param {string} name The name of the option to remove. This can be * any of the options's names. */ remove: function (name) { for each (let option in this._optionHash) { if (option.hasName(name)) delete this._optionHash[option.name]; } }, /** @property {Object} The options store. */ get store() storage.options, /** * Returns the value of the preference <b>name</b>. * * @param {string} name The preference name. * @param {value} forcedDefault The default value for this * preference. Used for internal liberator preferences. */ getPref: function (name, forcedDefault) { return this._loadPreference(name, forcedDefault); }, /** * Sets the preference <b>name</b> to </b>value</b> but warns the user * if the value is changed from its default. * * @param {string} name The preference name. * @param {value} value The new preference value. */ // FIXME: Well it used to. I'm looking at you mst! --djk safeSetPref: function (name, value, message) { let val = this._loadPreference(name, null, false); let def = this._loadPreference(name, null, true); let lib = this._loadPreference(Options.SAVED + name); if (lib == null && val != def || val != lib) { let msg = "Warning: setting preference " + name + ", but it's changed from its default value."; if (message) msg += " " + message; liberator.echomsg(msg); } this._storePreference(name, value); this._storePreference(Options.SAVED + name, value); }, /** * Sets the preference <b>name</b> to </b>value</b>. * * @param {string} name The preference name. * @param {value} value The new preference value. */ setPref: function (name, value) { this._storePreference(name, value); }, /** * Resets the preference <b>name</b> to its default value. * * @param {string} name The preference name. */ resetPref: function (name) { try { services.get("prefs").clearUserPref(name); } catch (e) { // ignore - thrown if not a user set value } }, /** * Toggles the value of the boolean preference <b>name</b>. * * @param {string} name The preference name. */ invertPref: function (name) { if (services.get("prefs").getPrefType(name) == Ci.nsIPrefBranch.PREF_BOOL) this.setPref(name, !this.getPref(name)); else liberator.echoerr("Trailing characters: " + name + "!"); }, /** * Pushes a new preference context onto the context stack. * * @see #withContext */ pushContext: function () { this._prefContexts.push({}); }, /** * Pops the top preference context from the stack. * * @see #withContext */ popContext: function () { for (let [k, v] in Iterator(this._prefContexts.pop())) this._storePreference(k, v); }, /** * Executes <b>func</b> with a new preference context. When <b>func</b> * returns, the context is popped and any preferences set via * {@link #setPref} or {@link #invertPref} are restored to their * previous values. * * @param {function} func The function to call. * @param {Object} func The 'this' object with which to call <b>func</b> * @see #pushContext * @see #popContext */ withContext: function (func, self) { try { this.pushContext(); return func.call(self); } finally { this.popContext(); } }, _storePreference: function (name, value) { if (this._prefContexts.length) { let val = this._loadPreference(name, null); if (val != null) this._prefContexts[this._prefContexts.length - 1][name] = val; } let type = services.get("prefs").getPrefType(name); switch (typeof value) { case "string": if (type == Ci.nsIPrefBranch.PREF_INVALID || type == Ci.nsIPrefBranch.PREF_STRING) { let supportString = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString); supportString.data = value; services.get("prefs").setComplexValue(name, Ci.nsISupportsString, supportString); } else if (type == Ci.nsIPrefBranch.PREF_INT) liberator.echoerr("Number required after =: " + name + "=" + value); else liberator.echoerr("Invalid argument: " + name + "=" + value); break; case "number": if (type == Ci.nsIPrefBranch.PREF_INVALID || type == Ci.nsIPrefBranch.PREF_INT) services.get("prefs").setIntPref(name, value); else liberator.echoerr("Invalid argument: " + name + "=" + value); break; case "boolean": if (type == Ci.nsIPrefBranch.PREF_INVALID || type == Ci.nsIPrefBranch.PREF_BOOL) services.get("prefs").setBoolPref(name, value); else if (type == Ci.nsIPrefBranch.PREF_INT) liberator.echoerr("Number required after =: " + name + "=" + value); else liberator.echoerr("Invalid argument: " + name + "=" + value); break; default: liberator.echoerr("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")"); } }, _loadPreference: function (name, forcedDefault, defaultBranch) { let defaultValue = null; // XXX if (forcedDefault != null) // this argument sets defaults for non-user settable options (like extensions.history.comp_history) defaultValue = forcedDefault; let branch = defaultBranch ? services.get("prefs").getDefaultBranch("") : services.get("prefs"); let type = services.get("prefs").getPrefType(name); try { switch (type) { case Ci.nsIPrefBranch.PREF_STRING: let value = branch.getComplexValue(name, Ci.nsISupportsString).data; // try in case it's a localized string (will throw an exception if not) if (!services.get("prefs").prefIsLocked(name) && !services.get("prefs").prefHasUserValue(name) && RegExp("chrome://.+/locale/.+\\.properties").test(value)) value = branch.getComplexValue(name, Ci.nsIPrefLocalizedString).data; return value; case Ci.nsIPrefBranch.PREF_INT: return branch.getIntPref(name); case Ci.nsIPrefBranch.PREF_BOOL: return branch.getBoolPref(name); default: return defaultValue; } } catch (e) { return defaultValue; } } }, { SAVED: "extensions.liberator.saved.", OLD_SAVED: "liberator.saved." }, { commandline: function () { // TODO: maybe reset in .destroy()? // TODO: move to buffer.js // we have our own typeahead find implementation // See: https://bugzilla.mozilla.org/show_bug.cgi?id=348187 options.safeSetPref("accessibility.typeaheadfind.autostart", false); options.safeSetPref("accessibility.typeaheadfind", false); // actually the above setting should do it, but has no effect in Firefox }, commands: function () { function setAction(args, modifiers) { let bang = args.bang; if (!args.length) args[0] = ""; for (let [, arg] in args) { if (bang) { let onlyNonDefault = false; let reset = false; let invertBoolean = false; if (args[0] == "") { var name = "all"; onlyNonDefault = true; } else { var [matches, name, postfix, valueGiven, operator, value] = arg.match(/^\s*?([a-zA-Z0-9\.\-_{}]+)([?&!])?\s*(([-+^]?)=(.*))?\s*$/); reset = (postfix == "&"); invertBoolean = (postfix == "!"); } if (name == "all" && reset) commandline.input("Warning: Resetting all preferences may make " + config.hostApplication + " unusable. Continue (yes/[no]): ", function (resp) { if (resp == "yes") for (let pref in values(options.allPrefs())) options.resetPref(pref); }, { promptHighlight: "WarningMsg" }); else if (name == "all") options.listPrefs(onlyNonDefault, ""); else if (reset) options.resetPref(name); else if (invertBoolean) options.invertPref(name); else if (valueGiven) { switch (value) { case undefined: value = ""; break; case "true": value = true; break; case "false": value = false; break; default: if (/^[+-]?\d+$/.test(value)) value = parseInt(value, 10); } options.setPref(name, value); } else options.listPrefs(onlyNonDefault, name); return; } let opt = options.parseOpt(arg, modifiers); liberator.assert(opt, "Error parsing :set command: " + arg); let option = opt.option; liberator.assert(option != null || opt.all, "Unknown option: " + opt.name); // reset a variable to its default value if (opt.reset) { if (opt.all) { for (let option in options) option.reset(); } else { option.setFrom = modifiers.setFrom || null; option.reset(); } } // read access else if (opt.get) { if (opt.all) options.list(opt.onlyNonDefault, opt.scope); else { if (option.type == "boolean") var msg = (opt.optionValue ? " " : "no") + option.name; else msg = " " + option.name + "=" + opt.optionValue; if (options["verbose"] > 0 && option.setFrom) msg += "\n Last set from " + option.setFrom.path; // FIXME: Message highlight group wrapping messes up the indent up for multi-arg verbose :set queries liberator.echo(xml`<span highlight="CmdOutput">${msg}</span>`); } } // write access // NOTE: the behavior is generally Vim compatible but could be // improved. i.e. Vim's behavior is pretty sloppy to no real benefit else { option.setFrom = modifiers.setFrom || null; if (option.type == "boolean") { if (opt.unsetBoolean) { opt.values = false; } else { switch (opt.value) { case "": case "true": opt.values = true; break; case "false": opt.values = false; break; default: return liberator.echoerr("Invalid argument: " + arg); } } } let res = opt.option.op(opt.operator || "=", opt.values, opt.scope, opt.invert); if (res) liberator.echoerr(res); } } } function setCompleter(context, args, modifiers) { let filter = context.filter; if (args.bang) { // list completions for about:config entries if (filter[filter.length - 1] == "=") { context.advance(filter.length); filter = filter.substr(0, filter.length - 1); context.completions = [ [options._loadPreference(filter, null, false), "Current Value"], [options._loadPreference(filter, null, true), "Default Value"] ].filter(function ([k]) k != null); return null; } return completion.preference(context); } let opt = options.parseOpt(filter, modifiers); let prefix = opt.prefix; if (context.filter.indexOf("=") == -1) { if (prefix) context.filters.push(function ({ item: opt }) opt.type == "boolean" || prefix == "inv" && opt.values instanceof Array); return completion.option(context, opt.scope); } else if (prefix == "no") return null; let option = opt.option; context.advance(context.filter.indexOf("=") + 1); if (!option) { context.message = "No such option: " + opt.name; context.highlight(0, name.length, "SPELLCHECK"); } if (opt.get || opt.reset || !option || prefix) return null; context.fork("default", 0, this, function (context) { context.title = ["Extra Completions"]; let completions = [ [option.value, "Current value"], [option.defaultValue, "Default value"] ]; if (option.type == "boolean") { completions.push([!option.value, "Inverted current value"]); context.completions = completions; } else { context.completions = completions.filter(function (f) f[0] != ""); } }); return context.fork("values", 0, completion, "optionValue", opt.name, opt.operator); } commands.add(["let"], "Set or list a variable", function (args) { args = args.string; if (!args) { var hasRow = false; let str = xml`<table> ${ template.map2(xml, liberator.globalVariables, function ([i, value]) { let prefix = typeof value == "number" ? "#" : typeof value == "function" ? "*" : " "; if (!hasRow) hasRow = true; return xml`<tr> <td style="width: 200px;">${i}</td> <td>${prefix}${value}</td> </tr>`; }) } </table>`; if (hasRow) liberator.echo(str, commandline.FORCE_MULTILINE); else liberator.echomsg("No variables found"); return; } // 1 - type, 2 - name, 3 - +-., 4 - expr let matches = args.match(/([$@&])?([\w:]+)\s*([-+.])?=\s*(.+)/); if (matches) { let [, type, name, stuff, expr] = matches; if (!type) { let reference = liberator.variableReference(name); liberator.assert(reference[0] || !stuff, "Undefined variable: " + name); expr = liberator.evalExpression(expr); liberator.assert(expr !== undefined, "Invalid expression: " + expr); if (!reference[0]) { if (reference[2] == "g") reference[0] = liberator.globalVariables; else return; // for now } if (stuff) { if (stuff == "+") reference[0][reference[1]] += expr; else if (stuff == "-") reference[0][reference[1]] -= expr; else if (stuff == ".") reference[0][reference[1]] += expr.toString(); } else reference[0][reference[1]] = expr; } } // 1 - name else if ((matches = args.match(/^\s*([\w:]+)\s*$/))) { let reference = liberator.variableReference(matches[1]); liberator.assert(reference[0], "Undefined variable: " + matches[1]); let value = reference[0][reference[1]]; let prefix = typeof value == "number" ? "#" : typeof value == "function" ? "*" : " "; liberator.echo(reference[1] + "\t\t" + prefix + value); } }, { literal: 0 } ); commands.add(["setl[ocal]"], "Set local option", function (args, modifiers) { modifiers.scope = Option.SCOPE_LOCAL; setAction(args, modifiers); }, { bang: true, count: true, completer: function (context, args) { return setCompleter(context, args, { scope: Option.SCOPE_LOCAL }); }, literal: 0 } ); commands.add(["setg[lobal]"], "Set global option", function (args, modifiers) { modifiers.scope = Option.SCOPE_GLOBAL; setAction(args, modifiers); }, { bang: true, count: true, completer: function (context, args) { return setCompleter(context, args, { scope: Option.SCOPE_GLOBAL }); }, literal: 0 } ); commands.add(["se[t]"], "Set an option", function (args, modifiers) { setAction(args, modifiers); }, { bang: true, completer: function (context, args) { return setCompleter(context, args); }, serial: function () [ { command: this.name, arguments: [opt.type == "boolean" ? (opt.value ? "" : "no") + opt.name : opt.name + "=" + opt.value] } for (opt in options) if (!opt.getter && opt.value != opt.defaultValue && (opt.scope & Option.SCOPE_GLOBAL)) ] }); commands.add(["unl[et]"], "Delete a variable", function (args) { for (let [, name] in args) { let reference = liberator.variableReference(name); if (!reference[0]) { if (!args.bang) liberator.echoerr("No such variable: " + name); return; } delete reference[0][reference[1]]; } }, { argCount: "+", bang: true }); }, completion: function () { JavaScript.setCompleter(this.get, [function () ([o.name, o.description] for (o in options))]); JavaScript.setCompleter([this.getPref, this.safeSetPref, this.setPref, this.resetPref, this.invertPref], [function () options.allPrefs().map(function (pref) [pref, ""])]); completion.option = function option(context, scope) { context.title = ["Option"]; context.keys = { text: "names", description: "description" }; context.completions = options; if (scope) context.filters.push(function ({ item: opt }) opt.scope & scope); }; completion.optionValue = function (context, name, op, curValue) { let opt = options.get(name); let completer = opt.completer; if (!completer) return; let curValues = curValue != null ? opt.parseValues(curValue) : opt.values; let newValues = opt.parseValues(context.filter); let len = context.filter.length; switch (opt.type) { case "boolean": completer = function () [["true", ""], ["false", ""]]; break; case "stringlist": let target = newValues.pop(); len = target ? target.length : 0; break; case "charlist": len = 0; break; } // TODO: Highlight when invalid context.advance(context.filter.length - len); context.title = ["Option Value"]; let completions = completer(context); if (!completions) return; // Not Vim compatible, but is a significant enough improvement // that it's worth breaking compatibility. if (newValues instanceof Array) { completions = completions.filter(function (val) newValues.indexOf(val[0]) == -1); switch (op) { case "+": completions = completions.filter(function (val) curValues.indexOf(val[0]) == -1); break; case "-": completions = completions.filter(function (val) curValues.indexOf(val[0]) > -1); break; } } context.completions = completions; }; completion.preference = function preference(context) { context.anchored = false; context.title = [config.hostApplication + " Preference", "Value"]; context.keys = { text: function (item) item, description: function (item) options.getPref(item) }; context.completions = options.allPrefs(); }; } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2009 by Kris Maglione <kris@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. function checkFragment() { document.title = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "title")[0].textContent; var frag = document.location.hash.substr(1); var elem = document.getElementById(frag); if (elem) window.content.scrollTo(0, window.content.scrollY + elem.getBoundingClientRect().top - 10); // 10px context } document.addEventListener("load", checkFragment, true); window.addEventListener("message", function (event) { if (event.data == "fragmentChange") checkFragment(); }, true); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. (function () { const modules = {}; const BASE = "liberator://template/chrome://liberator/content/" modules.modules = modules; const loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getService(Components.interfaces.mozIJSSubScriptLoader); function load(script) { for (let [i, base] in Iterator(prefix)) { try { loader.loadSubScript(base + script, modules); return; } catch (e) { if (i + 1 < prefix.length) continue; if (Components.utils.reportError) Components.utils.reportError(e); dump("liberator: Error loading script " + script + ": " + e + "\n"); dump(e.stack + "\n"); } } } let prefix = [BASE]; //Cu.import("resource://liberator/template-tag.js", modules); loader.loadSubScript("resource://liberator/template-tag.js", modules); // TODO: This list is much too long, we should try to minimize // the number of required components for easier porting to new applications ["base.js", "modules.js", "abbreviations.js", "autocommands.js", "buffer.js", "commandline.js", "commands.js", "completion.js", "configbase.js", "config.js", "liberator.js", "editor.js", "events.js", "finder.js", "hints.js", "io.js", "javascript.js", "mappings.js", "marks.js", "modes.js", "options.js", "services.js", "statusline.js", "style.js", "template.js", "util.js", ].forEach(load); prefix.unshift("chrome://" + modules.Config.prototype.name.toLowerCase() + "/content/"); modules.Config.prototype.scripts.forEach(load); })(); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const History = Module("history", { requires: ["config"], get format() bookmarks.format, get service() services.get("history"), get: function get(filter, maxItems) { // no query parameters will get all history let query = services.get("history").getNewQuery(); let options = services.get("history").getNewQueryOptions(); if (typeof filter == "string") filter = { searchTerms: filter }; for (let [k, v] in Iterator(filter)) query[k] = v; options.sortingMode = options.SORT_BY_DATE_DESCENDING; options.resultType = options.RESULTS_AS_URI; if (maxItems > 0) options.maxResults = maxItems; // execute the query let root = services.get("history").executeQuery(query, options).root; root.containerOpen = true; let items = util.map(util.range(0, root.childCount), function (i) { let node = root.getChild(i); return { url: node.uri, title: node.title, icon: node.icon, }; }); root.containerOpen = false; // close a container after using it! return items; }, get session() { let sh = window.getWebNavigation().sessionHistory; let obj = []; obj.index = sh.index; obj.__iterator__ = function () util.Array.iteritems(this); for (let i in util.range(0, sh.count)) { obj[i] = { index: i, __proto__: sh.getEntryAtIndex(i, false) }; util.memoize(obj[i], "icon", function (obj) bookmarks.getFavicon(obj.URI)); } return obj; }, // TODO: better names stepTo: function stepTo(steps) { let start = 0; let end = window.getWebNavigation().sessionHistory.count - 1; let current = window.getWebNavigation().sessionHistory.index; if (current == start && steps < 0 || current == end && steps > 0) liberator.beep(); else { let index = util.Math.constrain(current + steps, start, end); window.getWebNavigation().gotoIndex(index); } }, goToStart: function goToStart() { let index = window.getWebNavigation().sessionHistory.index; if (index > 0) window.getWebNavigation().gotoIndex(0); else liberator.beep(); }, goToEnd: function goToEnd() { let sh = window.getWebNavigation().sessionHistory; let max = sh.count - 1; if (sh.index < max) window.getWebNavigation().gotoIndex(max); else liberator.beep(); }, // if openItems is true, open the matching history items in tabs rather than display list: function list(filter, openItems, maxItems) { // FIXME: returning here doesn't make sense // Why the hell doesn't it make sense? --Kris // See comment at bookmarks.list --djk if (!openItems) return completion.listCompleter("history", filter, maxItems, null, null, CompletionContext.Filter.textAndDescription); let items = completion.runCompleter("history", filter, maxItems, null, null, CompletionContext.Filter.textAndDescription); if (items.length) return liberator.open(items.map(function (i) i.url), liberator.NEW_TAB); if (filter.length > 0) liberator.echoerr("No matching history items for: " + filter); else liberator.echoerr("No history set"); return null; } }, { }, { commands: function () { commands.add(["ba[ck]"], "Go back in the browser history", function (args) { let url = args.literalArg; if (args.bang) history.goToStart(); else { if (url) { let sh = history.session; if (/^\d+(:|$)/.test(url) && sh.index - parseInt(url) in sh) return void window.getWebNavigation().gotoIndex(sh.index - parseInt(url)); for (let [i, ent] in Iterator(sh.slice(0, sh.index).reverse())) if (ent.URI.spec == url) return void window.getWebNavigation().gotoIndex(i); liberator.echoerr("URL not found in history: " + url); } else history.stepTo(-Math.max(args.count, 1)); } return null; }, { argCount: "?", bang: true, completer: function completer(context) { let sh = history.session; context.anchored = false; context.compare = CompletionContext.Sort.unsorted; context.filters = [CompletionContext.Filter.textDescription]; context.completions = sh.slice(0, sh.index).reverse(); context.keys = { text: function (item) (sh.index - item.index) + ": " + item.URI.spec, description: "title", icon: "icon" }; }, count: true, literal: 0 }); commands.add(["fo[rward]", "fw"], "Go forward in the browser history", function (args) { let url = args.literalArg; if (args.bang) history.goToEnd(); else { if (url) { let sh = history.session; if (/^\d+(:|$)/.test(url) && sh.index + parseInt(url) in sh) return void window.getWebNavigation().gotoIndex(sh.index + parseInt(url)); for (let [i, ent] in Iterator(sh.slice(sh.index + 1))) if (ent.URI.spec == url) return void window.getWebNavigation().gotoIndex(i); liberator.echoerr("URL not found in history: " + url); } else history.stepTo(Math.max(args.count, 1)); } return null; }, { argCount: "?", bang: true, completer: function completer(context) { let sh = history.session; context.anchored = false; context.compare = CompletionContext.Sort.unsorted; context.filters = [CompletionContext.Filter.textDescription]; context.completions = sh.slice(sh.index + 1); context.keys = { text: function (item) (item.index - sh.index) + ": " + item.URI.spec, description: "title", icon: "icon" }; }, count: true, literal: 0 }); commands.add(["hist[ory]", "hs"], "Show recently visited URLs", function (args) { if (args["-remove"]) { let items = completion.runCompleter("history", args.join(" "), args["-max"] || 1000); if (items.length == 0) liberator.echoerr("No matching history items for: " + args.join(" ")); else { var browserHistory = Components.classes["@mozilla.org/browser/nav-history-service;1"] .getService(Components.interfaces.nsIBrowserHistory); var urls = []; items.map(function (i) { urls.push(makeURI(i.url)) }); browserHistory.removePages(urls, urls.length); if (urls.length == 1) liberator.echo("Removed history item " + urls[0].spec); else liberator.echo("Removed " + urls.length + " history items matching " + args.join(" ")); } } else history.list(args.join(" "), args.bang, args["-max"] || 1000); }, { bang: true, completer: function (context, args) { context.filter = args.join(" "); context.filters = [CompletionContext.Filter.textAndDescription]; context.quote = null; completion.history(context); }, options: [[["-max", "-m"], commands.OPTION_INT], [["-remove", "-r"], commands.OPTION_NOARG]] }); }, completion: function () { completion.history = function _history(context, maxItems) { context.format = history.format; context.title = ["History"]; context.compare = CompletionContext.Sort.unsorted; if (context.maxItems == null) context.maxItems = 100; context.regenerate = true; context.generate = function () history.get(context.filter, this.maxItems); }; completion.addUrlCompleter("h", "History", completion.history); }, mappings: function () { var myModes = config.browserModes; mappings.add(myModes, ["<C-o>"], "Go to an older position in the jump list", function (count) { history.stepTo(-Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["<C-i>"], "Go to a newer position in the jump list", function (count) { history.stepTo(Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["H", "<A-Left>", "<M-Left>"], "Go back in the browser history", function (count) { history.stepTo(-Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["L", "<A-Right>", "<M-Right>"], "Go forward in the browser history", function (count) { history.stepTo(Math.max(count, 1)); }, { count: true }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2008-2010 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ Cu.import("resource://gre/modules/XPCOMUtils.jsm", modules); const Point = Struct("x", "y"); /** * A class to manage the primary web content buffer. The name comes * from Vim's term, 'buffer', which signifies instances of open * files. * @instance buffer */ const Buffer = Module("buffer", { requires: ["config"], init: function () { this.pageInfo = {}; this.addPageInfoSection("f", "Feeds", function (verbose) { let doc = config.browser.contentDocument; 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 = ["application/rss+xml", "application/atom+xml"].indexOf(type) >= 0 || // really slimy: general XML types with magic letters in the title type in feedTypes && /\brss\b/i.test(data.title); } if (isFeed) { try { window.urlSecurityCheck(data.href, principal, Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL); } catch (e) { isFeed = false; } } if (type) data.type = type; return isFeed; } let nFeed = 0; for (let link in util.evaluateXPath(["link[@href and (@rel='feed' or (@rel='alternate' and @type))]"], doc)) { let rel = link.rel.toLowerCase(); let feed = { title: link.title, href: link.href, type: link.type || "" }; if (isValidFeed(feed, doc.nodePrincipal, rel == "feed")) { nFeed++; let type = feedTypes[feed.type] || "RSS"; if (verbose) yield [feed.title, xml`${template.highlightURL(feed.href, true)}<span class="extra-info">&#xa0;(${type})</span>`]; } } if (!verbose && nFeed) yield nFeed + " feed" + (nFeed > 1 ? "s" : ""); }); this.addPageInfoSection("g", "Document", function (verbose) { let doc = config.browser.contentDocument; // get file size const ACCESS_READ = Ci.nsICache.ACCESS_READ; let cacheKey = doc.location.toString().replace(/#.*$/, ""); for (let proto of ["HTTP", "FTP"]) { try { var cacheEntryDescriptor = services.get("cache").createSession(proto, 0, true) .openCacheEntry(cacheKey, ACCESS_READ, false); break; } catch (e) {} } let pageSize = []; // [0] bytes; [1] kbytes if (cacheEntryDescriptor) { pageSize[0] = util.formatBytes(cacheEntryDescriptor.dataSize, 0, false); pageSize[1] = util.formatBytes(cacheEntryDescriptor.dataSize, 2, true); if (pageSize[1] == pageSize[0]) pageSize.length = 1; // don't output "xx Bytes" twice } let lastModVerbose = new Date(doc.lastModified).toLocaleString(); let lastMod = new Date(doc.lastModified).toLocaleFormat("%x %X"); if (lastModVerbose == "Invalid Date" || new Date(doc.lastModified).getFullYear() == 1970) lastModVerbose = lastMod = null; if (!verbose) { if (pageSize[0]) yield (pageSize[1] || pageSize[0]) + " bytes"; yield lastMod; return; } yield ["Title", doc.title]; yield ["URL", template.highlightURL(doc.location.toString(), true)]; let ref = "referrer" in doc && doc.referrer; if (ref) yield ["Referrer", template.highlightURL(ref, true)]; if (pageSize[0]) yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")" : pageSize[0]]; yield ["Mime-Type", doc.contentType]; yield ["Encoding", doc.characterSet]; yield ["Compatibility", doc.compatMode == "BackCompat" ? "Quirks Mode" : "Full/Almost Standards Mode"]; if (lastModVerbose) yield ["Last Modified", lastModVerbose]; }); this.addPageInfoSection("m", "Meta Tags", function (verbose) { // get meta tag data, sort and put into pageMeta[] let metaNodes = config.browser.contentDocument.getElementsByTagName("meta"); return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv), template.highlightURL(node.content)]) .sort(function (a, b) util.compareIgnoreCase(a[0], b[0])); }); }, destroy: function () { }, _triggerLoadAutocmd: function _triggerLoadAutocmd(name, doc) { let args = { url: doc.location.href, title: doc.title }; if (liberator.has("tabs")) { args.tab = tabs.getContentIndex(doc) + 1; args.doc = "tabs.getTab(" + (args.tab - 1) + ").linkedBrowser.contentDocument"; } autocommands.trigger(name, args); }, // called when the active document is scrolled _updateBufferPosition: function _updateBufferPosition() { statusline.updateField("position"); // modes.show(); }, onDOMContentLoaded: function onDOMContentLoaded(event) { let doc = event.originalTarget; if (doc instanceof HTMLDocument && !doc.defaultView.frameElement) this._triggerLoadAutocmd("DOMLoad", doc); }, // TODO: see what can be moved to onDOMContentLoaded() // event listener which is is called on each page load, even if the // page is loaded in a background tab onPageLoad: function onPageLoad(event) { if (event.originalTarget instanceof HTMLDocument) { let doc = event.originalTarget; // document is part of a frameset if (doc.defaultView.frameElement) { return; } // code which should happen for all (also background) newly loaded tabs goes here: // mark the buffer as loaded, we can't use buffer.loaded // since that always refers to the current buffer, while doc can be // any buffer, even in a background tab doc.pageIsFullyLoaded = 1; // code which is only relevant if the page load is the current tab goes here: if (doc == config.browser.contentDocument) { // we want to stay in command mode after a page has loaded // TODO: move somewhere else, as focusing can already happen earlier than on "load" if (options["focuscontent"]) { setTimeout(function () { let focused = liberator.focus; if (focused && (focused.value != null) && focused.value.length == 0) focused.blur(); }, 0); } } // else // background tab // liberator.echomsg("Background tab loaded: " + doc.title || doc.location.href); this._triggerLoadAutocmd("PageLoad", doc); } }, /** * @property {Object} The document loading progress listener. */ progressListener: { QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIWebProgressListener, Ci.nsIMsgStatusFeedback, Ci.nsIActivityMgrListener, Ci.nsIActivityListener]), // XXX: function may later be needed to detect a canceled synchronous openURL() onStateChange: function onStateChange(webProgress, request, flags, status) { onStateChange.superapply(this, arguments); // STATE_IS_DOCUMENT | STATE_IS_WINDOW is important, because we also // receive statechange events for loading images and other parts of the web page if (flags & (Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | Ci.nsIWebProgressListener.STATE_IS_WINDOW)) { // This fires when the load event is initiated // only thrown for the current tab, not when another tab changes if (flags & Ci.nsIWebProgressListener.STATE_START) { webProgress.DOMWindow.document.pageIsFullyLoaded = 0; buffer.loaded = 0; autocommands.trigger("PageLoadPre", { url: buffer.URL }); // don't reset mode if a frame of the frameset gets reloaded which // is not the focused frame if (document.commandDispatcher.focusedWindow == webProgress.DOMWindow) { setTimeout(function () { modes.reset(false); }, liberator.mode == modes.HINTS ? 500 : 0); } } else if (flags & Ci.nsIWebProgressListener.STATE_STOP) { webProgress.DOMWindow.document.pageIsFullyLoaded = (status == 0 ? 1 : 2); buffer.loaded = (status == 0 ? 1 : 2); } } }, // for notifying the user about secure web pages onSecurityChange: function onSecurityChange(webProgress, request, state) { onSecurityChange.superapply(this, arguments); statusline.updateField("ssl", state); }, onStatusChange: function onStatusChange(webProgress, request, status, message) { onStatusChange.superapply(this, arguments); }, onProgressChange: function onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) { onProgressChange.superapply(this, arguments); }, // happens when the users switches tabs onLocationChange: function onLocationChange() { onLocationChange.superapply(this, arguments); statusline.updateField("location"); statusline.updateField("bookmark"); statusline.updateField("history"); // This is a bit scary but we trigger ignore mode when the new URL is in the list // of pages with ignored keys and then exit it on a new page but ONLY, if: // a) The new page hasn't ignore as well and // b) We initiated ignore mode, and not the user manually with <Insert> if (modules.ignoreKeys != undefined) { let ignoredKeyExceptions = ignoreKeys.hasIgnoredKeys(buffer.URL); if (ignoredKeyExceptions !== null) modes.passAllKeysExceptSome(ignoredKeyExceptions); else if (modes._passKeysExceptions !== null) modes.passAllKeys = false; } autocommands.trigger("LocationChange", { url: buffer.URL }); // if this is not delayed we get the position of the old buffer setTimeout(function () { statusline.updateField("position"); }, 250); }, // called at the very end of a page load asyncUpdateUI: function asyncUpdateUI() { asyncUpdateUI.superapply(this, arguments); }, setOverLink: function setOverLink(link, b) { setOverLink.superapply(this, arguments); let ssli = options["showstatuslinks"]; if (link && ssli) { if (ssli == 1) { statusline.updateField("location", "Link: " + link); statusline.updateField("bookmark", link); } else if (ssli == 2) liberator.echo("Link: " + link, commandline.DISALLOW_MULTILINE); } if (link == "") { if (ssli == 1) { statusline.updateField("location"); statusline.updateField("bookmark"); } else if (ssli == 2) modes.show(); } }, }, /** * @property {Array} The alternative style sheets for the current * buffer. Only returns style sheets for the 'screen' media type. */ get alternateStyleSheets() { let stylesheets = window.getAllStyleSheets(config.browser.contentWindow); return stylesheets.filter( function (stylesheet) /^(screen|all|)$/i.test(stylesheet.media.mediaText) && !/^\s*$/.test(stylesheet.title) ); }, /** * @property {Array[Window]} All frames in the current buffer. */ getAllFrames: function(win) { let frames = []; (function rec(frame) { if (frame.document.body instanceof HTMLBodyElement) frames.push(frame); Array.forEach(frame.frames, rec); })(win || config.browser.contentWindow); return frames; }, /** * @property {Object} A map of page info sections to their * content generating functions. */ pageInfo: null, /** * @property {number} A value indicating whether the buffer is loaded. * Values may be: * 0 - Loading. * 1 - Fully loaded. * 2 - Load failed. */ get loaded() { let doc = config.browser.contentDocument; if (doc.pageIsFullyLoaded !== undefined) return doc.pageIsFullyLoaded; return 0; // in doubt return "loading" }, set loaded(value) { config.browser.contentDocument.pageIsFullyLoaded = value; }, /** * @property {Object} The local state store for the currently selected * tab. */ get localStore() { let content = config.browser.contentWindow; if (!content.liberatorStore) content.liberatorStore = {}; return content.liberatorStore; }, /** * @property {Node} The last focused input field in the buffer. Used * by the "gi" key binding. */ get lastInputField() config.browser.contentDocument.lastInputField || null, set lastInputField(value) { config.browser.contentDocument.lastInputField = value; }, /** * @property {string} The current top-level document's URL. */ get URL() window.content ? window.content.location.href : config.browser.currentURI.spec, /** * @property {string} The current top-level document's URL, sans any * fragment identifier. */ get URI() { let loc = config.browser.contentWindow.location; return loc.href.substr(0, loc.href.length - loc.hash.length); }, /** * @property {String} The current document's character set */ get charset() { try { return config.browser.docShell.charset; } catch (e) { return "UTF-8"; } }, /** * @property {number} The buffer's height in pixels. */ get pageHeight() window.content ? window.content.innerHeight : config.browser.contentWindow.innerHeight, /** * @property {number} The current browser's text zoom level, as a * percentage with 100 as 'normal'. Only affects text size. */ get textZoom() config.browser.markupDocumentViewer.textZoom * 100, set textZoom(value) { Buffer.setZoom(value, false); }, /** * @property {number} The current browser's text zoom level, as a * percentage with 100 as 'normal'. Affects text size, as well as * image size and block size. */ get fullZoom() config.browser.markupDocumentViewer.fullZoom * 100, set fullZoom(value) { Buffer.setZoom(value, true); }, /** * @property {string} The current document's title. */ get title() config.browser.contentTitle, /** * @property {number} The buffer's horizontal scroll percentile. */ get scrollXPercent() { let win = Buffer.findScrollableWindow(); if (win.scrollMaxX > 0) return Math.round(win.scrollX / win.scrollMaxX * 100); else return 0; }, /** * @property {number} The buffer's vertical scroll percentile. */ get scrollYPercent() { let win = Buffer.findScrollableWindow(); if (win.scrollMaxY > 0) return Math.round(win.scrollY / win.scrollMaxY * 100); else return 0; }, /** * Adds a new section to the page information output. * * @param {string} option The section's value in 'pageinfo'. * @param {string} title The heading for this section's * output. * @param {function} func The function to generate this * section's output. */ addPageInfoSection: function addPageInfoSection(option, title, func) { this.pageInfo[option] = [func, title]; }, /** * Returns the currently selected word. If the selection is * null, it tries to guess the word that the caret is * positioned in. * * NOTE: might change the selection * * @returns {string} */ // FIXME: getSelection() doesn't always preserve line endings, see: // https://www.mozdev.org/bugs/show_bug.cgi?id=19303 getCurrentWord: function () { function _getCurrentWord (win) { let elem = win.frameElement; if (elem && elem.getClientRects().length === 0) return; let selection = win.getSelection(); if (selection.rangeCount <= 0) return; let range = selection.getRangeAt(0); if (selection.isCollapsed) { let selController = buffer.selectionController; let caretmode = selController.getCaretEnabled(); selController.setCaretEnabled(true); // Only move backwards if the previous character is not a space. if (range.startOffset > 0 && !/\s/.test(range.startContainer.textContent[range.startOffset - 1])) selController.wordMove(false, false); selController.wordMove(true, true); selController.setCaretEnabled(caretmode); return String.match(selection, /\w*/)[0]; } if (util.computedStyle(range.startContainer).whiteSpace == "pre" && util.computedStyle(range.endContainer).whiteSpace == "pre") return String(range); return String(selection); } return util.Array.compact(buffer.getAllFrames().map(_getCurrentWord)).join("\n"); }, /** * Focuses the given element. In contrast to a simple * elem.focus() call, this function works for iframes and * image maps. * * @param {Node} elem The element to focus. */ focusElement: function (elem) { if (elem instanceof HTMLFrameElement || elem instanceof HTMLIFrameElement) Buffer.focusedWindow = elem.contentWindow; else if (elem instanceof HTMLInputElement && elem.type == "file") { Buffer.openUploadPrompt(elem); buffer.lastInputField = elem; } else { elem.focus(); // for imagemap if (elem instanceof HTMLAreaElement) { let doc = config.browser.contentDocument; try { let [x, y] = elem.getAttribute("coords").split(",").map(parseFloat); elem.dispatchEvent(events.create(doc, "mouseover", { screenX: x, screenY: y })); } catch (e) {} } } }, /** * Tries to guess links the like of "next" and "prev". Though it has a * singularly horrendous name, it turns out to be quite useful. * * @param {string} rel The relationship to look for. Looks for * links with matching @rel or @rev attributes, and, * failing that, looks for an option named rel + * "pattern", and finds the last link matching that * RegExp. */ followDocumentRelationship: function (rel) { let regexes = options.get(rel + "pattern").values .map(function (re) RegExp(re, "i")); function followFrame(frame) { function iter(elems) { for (let i = 0; i < elems.length; i++) if (elems[i].rel.toLowerCase() == rel || elems[i].rev.toLowerCase() == rel) yield elems[i]; } // <link>s have higher priority than normal <a> hrefs let elems = frame.document.getElementsByTagName("link"); for (let elem in iter(elems)) { liberator.open(elem.href); return true; } // no links? ok, look for hrefs elems = frame.document.getElementsByTagName("a"); for (let elem in iter(elems)) { buffer.followLink(elem, liberator.CURRENT_TAB); return true; } let res = util.evaluateXPath(options.get("hinttags").value, frame.document); for (let regex of regexes) { for (let i in util.range(res.snapshotLength, 0, -1)) { let elem = res.snapshotItem(i); if (regex.test(elem.textContent) || regex.test(elem.title) || Array.some(elem.childNodes, function (child) regex.test(child.alt))) { buffer.followLink(elem, liberator.CURRENT_TAB); return true; } } } return false; } let ret = followFrame(config.browser.contentWindow); if (!ret) { // only loop through frames (ordered by size) if the main content didn't match let frames = buffer.getAllFrames().slice(1) .sort( function(a, b) { return ((b.scrollMaxX+b.innerWidth)*(b.scrollMaxY+b.innerHeight)) - ((a.scrollMaxX+a.innerWidth)*(a.scrollMaxY+a.innerHeight)) } ); ret = Array.some(frames, followFrame); } if (!ret) liberator.beep(); }, /** * Fakes a click on a link. * * @param {Node} elem The element to click. * @param {number} where Where to open the link. See * {@link liberator.open}. */ followLink: function (elem, where) { let doc = elem.ownerDocument; let view = doc.defaultView; let offsetX = 1; let offsetY = 1; if (elem instanceof HTMLFrameElement || elem instanceof HTMLIFrameElement) { elem.contentWindow.focus(); return; } else if (elem instanceof HTMLAreaElement) { // for imagemap let coords = elem.getAttribute("coords").split(","); offsetX = Number(coords[0]) + 1; offsetY = Number(coords[1]) + 1; } else if (elem instanceof HTMLInputElement && elem.type == "file") { Buffer.openUploadPrompt(elem); return; } let ctrlKey = false, shiftKey = false; switch (where) { case liberator.NEW_TAB: case liberator.NEW_BACKGROUND_TAB: ctrlKey = true; shiftKey = (where != liberator.NEW_BACKGROUND_TAB); break; case liberator.NEW_WINDOW: shiftKey = true; break; case liberator.CURRENT_TAB: break; default: liberator.echoerr("Invalid where argument for followLink(): " + where); } elem.focus(); options.withContext(function () { options.setPref("browser.tabs.loadInBackground", true); ["mousedown", "mouseup", "click"].forEach(function (event) { elem.dispatchEvent(events.create(doc, event, { screenX: offsetX, screenY: offsetY, ctrlKey: ctrlKey, shiftKey: shiftKey, metaKey: ctrlKey })); }); }); }, /** * @property {nsISelectionController} The current document's selection * controller. */ get selectionController() Buffer.focusedWindow .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell) .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsISelectionDisplay) .QueryInterface(Ci.nsISelectionController), /** * Opens the appropriate context menu for <b>elem</b>. * * @param {Node} elem The context element. */ openContextMenu: function (elem) { document.popupNode = elem; let menu = document.getElementById("contentAreaContextMenu"); menu.showPopup(elem, -1, -1, "context", "bottomleft", "topleft"); }, /** * Saves a page link to disk. * * @param {HTMLAnchorElement} elem The page link to save. * @param {boolean} skipPrompt Whether to open the "Save Link As..." * dialog. */ saveLink: function (elem, skipPrompt) { let doc = elem.ownerDocument; let url = window.makeURLAbsolute(elem.baseURI, elem.href ? elem.href : elem.src); let text = elem.textContent; try { window.urlSecurityCheck(url, doc.nodePrincipal); // we always want to save that link relative to the current working directory options.setPref("browser.download.lastDir", io.getCurrentDirectory().path); window.saveURL(url, text, null, true, skipPrompt, makeURI(url, doc.characterSet), doc); } catch (e) { liberator.echoerr(e); } }, /** * Scrolls to the bottom of the current buffer. */ scrollBottom: function () { Buffer.scrollToPercent(null, 100); }, /** * Scrolls the buffer laterally <b>cols</b> columns. * * @param {number} cols The number of columns to scroll. A positive * value scrolls right and a negative value left. */ scrollColumns: function (cols) { Buffer.scrollHorizontal(null, "columns", cols); }, /** * Scrolls to the top of the current buffer. */ scrollEnd: function () { Buffer.scrollToPercent(100, null); }, /** * Scrolls the buffer vertically <b>lines</b> rows. * * @param {number} lines The number of lines to scroll. A positive * value scrolls down and a negative value up. */ scrollLines: function (lines) { Buffer.scrollVertical(null, "lines", lines); }, /** * Scrolls the buffer vertically <b>pages</b> pages. * * @param {number} pages The number of pages to scroll. A positive * value scrolls down and a negative value up. */ scrollPages: function (pages) { Buffer.scrollVertical(null, "pages", pages); }, /** * Scrolls the buffer vertically 'scroll' lines. * * @param {boolean} direction The direction to scroll. If true then * scroll up and if false scroll down. * @param {number} count The multiple of 'scroll' lines to scroll. * @optional */ scrollByScrollSize: function (direction, count) { direction = direction ? 1 : -1; count = count || 1; let win = Buffer.findScrollableWindow(); Buffer.checkScrollYBounds(win, direction); if (options["scroll"] > 0) this.scrollLines(options["scroll"] * direction); else // scroll half a page down in pixels win.scrollBy(0, win.innerHeight / 2 * direction); }, _scrollByScrollSize: function _scrollByScrollSize(count, direction) { if (count > 0) options["scroll"] = count; buffer.scrollByScrollSize(direction); }, /** * Scrolls the buffer to the specified screen percentiles. * * @param {number} x The horizontal page percentile. * @param {number} y The vertical page percentile. */ scrollToPercent: function (x, y) { Buffer.scrollToPercent(x, y); }, /** * Scrolls the buffer to the specified screen pixels. * * @param {number} x The horizontal pixel. * @param {number} y The vertical pixel. */ scrollTo: function (x, y) { marks.add("'", true); config.browser.contentWindow.scrollTo(x, y); }, /** * Scrolls the current buffer laterally to its leftmost. */ scrollStart: function () { Buffer.scrollToPercent(0, null); }, /** * Scrolls the current buffer vertically to the top. */ scrollTop: function () { Buffer.scrollToPercent(null, 0); }, // TODO: allow callback for filtering out unwanted frames? User defined? /** * Shifts the focus to another frame within the buffer. Each buffer * contains at least one frame. * * @param {number} count The number of frames to skip through. * @param {boolean} forward The direction of motion. */ shiftFrameFocus: function (count, forward) { let content = config.browser.contentWindow; if (!(content.document instanceof HTMLDocument)) return; count = Math.max(count, 1); let frames = []; // find all frames - depth-first search (function findFrames(frame) { if (frame.document.body instanceof HTMLBodyElement) frames.push(frame); Array.forEach(frame.frames, findFrames); })(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 let start = document.commandDispatcher.focusedWindow; frames = frames.filter(function (frame) { frame.focus(); return document.commandDispatcher.focusedWindow == 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. let current = frames.indexOf(document.commandDispatcher.focusedWindow); // calculate the next frame to focus let next = current; if (forward) { next = current + count; if (next > frames.length - 1) { if (current == frames.length - 1) liberator.beep(); next = frames.length - 1; // still allow the frame indicator to be activated } } else { next = current - count; if (next < 0) { if (current == 0) liberator.beep(); next = 0; // still allow the frame indicator to be activated } } // focus next frame and scroll into view frames[next].focus(); if (frames[next] != window.content) frames[next].frameElement.scrollIntoView(false); // add the frame indicator let doc = frames[next].document; let indicator = util.xmlToDom(xml`<div highlight="FrameIndicator"/>`, doc); doc.body.appendChild(indicator); setTimeout(function () { doc.body.removeChild(indicator); }, 500); // Doesn't unattach //doc.body.setAttributeNS(NS.uri, "activeframe", "true"); //setTimeout(function () { doc.body.removeAttributeNS(NS.uri, "activeframe"); }, 500); }, // similar to pageInfo // TODO: print more useful information, just like the DOM inspector /** * Displays information about the specified element. * * @param {Node} elem The element to query. */ showElementInfo: function (elem) { liberator.echo(xml`Element:<br/>${util.objectToString(elem, true)}`, commandline.FORCE_MULTILINE); }, /** * Displays information about the current buffer. * * @param {boolean} verbose Display more verbose information. * @param {string} sections A string limiting the displayed sections. * @default The value of 'pageinfo'. */ showPageInfo: function (verbose, sections) { // Ctrl-g single line output if (!verbose) { let content = config.browser.contentWindow; let file = content.document.location.pathname.split("/").pop() || "[No Name]"; let title = content.document.title || "[No Title]"; let info = template.map2(xml, "gf", function (opt) template.map2(xml, buffer.pageInfo[opt][0](), util.identity, ", "), ", "); if (bookmarks.isBookmarked(this.URL)) xml["+="](info, ", bookmarked"); let pageInfoText = xml`${file.quote()} [${info}] ${title}`; liberator.echo(pageInfoText, commandline.FORCE_SINGLELINE); return; } let option = sections || options["pageinfo"]; let list = template.map2(xml, option, function (option) { let opt = buffer.pageInfo[option]; return opt ? template.table2(xml, opt[1], opt[0](true)) : undefined; }, xml`<br/>`); liberator.echo(template.genericOutput("Page Information", list), commandline.FORCE_MULTILINE); }, /** * Opens a viewer to inspect the source of the currently selected * range. */ viewSelectionSource: function () { // copied (and tuned somebit) from browser.jar -> nsContextMenu.js let focusedWindow = document.commandDispatcher.focusedWindow; if (focusedWindow == window) focusedWindow = config.browser.contentWindow; let docCharset = null; if (focusedWindow) docCharset = "charset=" + focusedWindow.document.characterSet; let reference = null; reference = focusedWindow.getSelection(); let docUrl = null; window.openDialog("chrome://global/content/viewPartialSource.xul", "_blank", "scrollbars,resizable,chrome,dialog=no", docUrl, docCharset, reference, "selection"); }, /** * Opens a viewer to inspect the source of the current buffer or the * specified <b>url</b>. Either the default viewer or the configured * external editor is used. * * @param {string} url The URL of the source. * @default The current buffer. * @param {boolean} useExternalEditor View the source in the external editor. */ viewSource: function (url, useExternalEditor) { url = url || buffer.URI; if (useExternalEditor) editor.editFileExternally(url); else { const PREFIX = "view-source:"; if (url.startsWith(PREFIX)) url = url.substr(PREFIX.length); else url = PREFIX + url; liberator.open(url, { hide: true }); } }, /** * Increases the zoom level of the current buffer. * * @param {number} steps The number of zoom levels to jump. * @param {boolean} fullZoom Whether to use full zoom or text zoom. */ zoomIn: function (steps, fullZoom) { Buffer.bumpZoomLevel(steps, fullZoom); }, /** * Decreases the zoom level of the current buffer. * * @param {number} steps The number of zoom levels to jump. * @param {boolean} fullZoom Whether to use full zoom or text zoom. */ zoomOut: function (steps, fullZoom) { Buffer.bumpZoomLevel(-steps, fullZoom); } }, { ZOOM_MIN: "ZoomManager" in window && Math.round(ZoomManager.MIN * 100), ZOOM_MAX: "ZoomManager" in window && Math.round(ZoomManager.MAX * 100), get focusedWindow() this.getFocusedWindow(), set focusedWindow(win) { if (win === document.commandDispatcher.focusedWindow) return; // XXX: if win has frame and win is not content's focus window, win.focus() cannot focus. var e = win.document.activeElement; if (e && e.contentWindow) { services.get("focus").clearFocus(win); } win.focus(); }, getFocusedWindow: function (win) { win = win || config.browser.contentWindow; let elem = win.document.activeElement; let doc; while (doc = elem.contentDocument) { elem = doc.activeElement; } return elem.ownerDocument.defaultView; }, setZoom: function setZoom(value, fullZoom) { liberator.assert(value >= Buffer.ZOOM_MIN || value <= Buffer.ZOOM_MAX, "Zoom value out of range (" + Buffer.ZOOM_MIN + " - " + Buffer.ZOOM_MAX + "%)"); ZoomManager.useFullZoom = fullZoom; ZoomManager.zoom = value / 100; if ("FullZoom" in window) FullZoom._applySettingToPref(); liberator.echomsg((fullZoom ? "Full" : "Text") + " zoom: " + value + "%"); }, bumpZoomLevel: function bumpZoomLevel(steps, fullZoom) { let values = ZoomManager.zoomValues; let cur = values.indexOf(ZoomManager.snap(ZoomManager.zoom)); let i = util.Math.constrain(cur + steps, 0, values.length - 1); if (i == cur && fullZoom == ZoomManager.useFullZoom) liberator.beep(); Buffer.setZoom(Math.round(values[i] * 100), fullZoom); }, checkScrollYBounds: 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(); }, findScrollableWindow: function findScrollableWindow() { let win = this.focusedWindow; if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0)) return win; win = config.browser.contentWindow; if (win.scrollMaxX > 0 || win.scrollMaxY > 0) return win; for (let frame in util.Array.itervalues(win.frames)) if (frame.scrollMaxX > 0 || frame.scrollMaxY > 0) return frame; return win; }, findScrollable: function findScrollable(dir, horizontal) { let pos = "scrollTop", maxPos = "scrollTopMax", clientSize = "clientHeight"; if (horizontal) pos = "scrollLeft", maxPos = "scrollLeftMax", clientSize = "clientWidth"; function find(elem) { if (!(elem instanceof Element)) elem = elem.parentNode; for (; elem && elem.parentNode instanceof Element; elem = elem.parentNode) { if (elem[clientSize] == 0) continue; if (dir < 0 && elem[pos] > 0 || dir > 0 && elem[pos] < elem[maxPos]) break; } return elem; } let win = this.focusedWindow; if (win.getSelection().rangeCount) var elem = find(win.getSelection().getRangeAt(0).startContainer); if (!(elem instanceof Element)) { let doc = Buffer.findScrollableWindow().document; elem = find(doc.body || doc.getElementsByTagName("body")[0] || doc.documentElement); } return elem; }, scrollVertical: function scrollVertical(elem, increment, number) { elem = elem || Buffer.findScrollable(number, false); let fontSize = parseInt(util.computedStyle(elem).fontSize); if (increment == "lines") increment = fontSize; else if (increment == "pages") increment = elem.clientHeight - fontSize; else throw Error() elem.scrollTop += number * increment; }, scrollHorizontal: function scrollHorizontal(elem, increment, number) { elem = elem || Buffer.findScrollable(number, true); let fontSize = parseInt(util.computedStyle(elem).fontSize); if (increment == "columns") increment = fontSize; // Good enough, I suppose. else if (increment == "pages") increment = elem.clientWidth - fontSize; else throw Error() elem.scrollLeft += number * increment; }, scrollElemToPercent: function scrollElemToPercent(elem, horizontal, vertical) { elem = elem || Buffer.findScrollable(); marks.add("'", true); if (horizontal != null) elem.scrollLeft = (elem.scrollWidth - elem.clientWidth) * (horizontal / 100); if (vertical != null) elem.scrollTop = (elem.scrollHeight - elem.clientHeight) * (vertical / 100); }, scrollToPercent: function scrollToPercent(horizontal, vertical) { let win = Buffer.findScrollableWindow(); let h, v; if (horizontal == null) h = win.scrollX; else h = win.scrollMaxX / 100 * horizontal; if (vertical == null) v = win.scrollY; else v = win.scrollMaxY / 100 * vertical; marks.add("'", true); win.scrollTo(h, v); }, openUploadPrompt: function openUploadPrompt(elem) { commandline.input("Upload file: ", function (path) { let file = io.File(path); liberator.assert(file.exists()); elem.value = file.path; }, { completer: completion.file, default: elem.value }); } }, { commands: function () { commands.add(["frameo[nly]"], "Show only the current frame's page", function (args) { liberator.open(buffer.localStore.focusedFrame.document.documentURI); }, { argCount: "0" }); commands.add(["ha[rdcopy]"], "Print current document", function (args) { let arg = args[0]; // FIXME: arg handling is a bit of a mess, check for filename liberator.assert(!arg || arg[0] == ">" && !liberator.has("Windows"), "Trailing characters"); options.withContext(function () { if (arg) { options.setPref("print.print_to_file", "true"); options.setPref("print.print_to_filename", io.File(arg.substr(1)).path); liberator.echomsg("Printing to file: " + arg.substr(1)); } else liberator.echomsg("Sending to printer..."); options.setPref("print.always_print_silent", args.bang); options.setPref("print.show_print_progress", !args.bang); config.browser.contentWindow.print(); }); if (arg) liberator.echomsg("Printed: " + arg.substr(1)); else liberator.echomsg("Print job sent."); }, { argCount: "?", literal: 0, bang: true }); commands.add(["pa[geinfo]"], "Show various page information", function (args) { buffer.showPageInfo(true, args[0]); }, { argCount: "?", completer: function (context) { completion.optionValue(context, "pageinfo", "+", ""); context.title = ["Page Info"]; } }); commands.add(["pagest[yle]", "pas"], "Select the author style sheet to apply", function (args) { let arg = args.literalArg; let titles = buffer.alternateStyleSheets.map(function (stylesheet) stylesheet.title); liberator.assert(!arg || titles.indexOf(arg) >= 0, "Invalid argument: " + arg); if (options["usermode"]) options["usermode"] = false; window.stylesheetSwitchAll(config.browser.contentWindow, arg); }, { argCount: "?", completer: function (context) completion.alternateStyleSheet(context), literal: 0 }); commands.add(["re[load]"], "Reload the current web page", function (args) { tabs.reload(config.browser.mCurrentTab, args.bang); }, { bang: true, argCount: "0" }); // TODO: we're prompted if download.useDownloadDir isn't set and no arg specified - intentional? commands.add(["sav[eas]", "w[rite]"], "Save current document to disk", function (args) { let doc = config.browser.contentDocument; let chosenData = null; let filename = args[0]; if (filename) { let file = io.File(filename); liberator.assert(!file.exists() || args.bang, "File exists (add ! to override)"); chosenData = { file: file, uri: window.makeURI(doc.location.href, doc.characterSet) }; } // if browser.download.useDownloadDir = false then the "Save As" // dialog is used with this as the default directory // TODO: if we're going to do this shouldn't it be done in setCWD or the value restored? options.setPref("browser.download.lastDir", io.getCurrentDirectory().path); try { var contentDisposition = config.browser.contentWindow .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils) .getDocumentMetadata("content-disposition"); } catch (e) {} window.internalSave(doc.location.href, doc, null, contentDisposition, doc.contentType, false, null, chosenData, doc.referrer ? window.makeURI(doc.referrer) : null, doc, true); }, { argCount: "?", bang: true, completer: function (context) completion.file(context) }); commands.add(["st[op]"], "Stop loading the current web page", function () { tabs.stop(config.browser.mCurrentTab); }, { argCount: "0" }); commands.add(["vie[wsource]"], "View source code of current document", function (args) { buffer.viewSource(args[0], args.bang); }, { argCount: "?", bang: true, completer: function (context) completion.url(context, "bhf") }); commands.add(["zo[om]"], "Set zoom value of current web page", function (args) { let arg = args[0]; let level; if (!arg) level = 100; else if (/^\d+$/.test(arg)) level = parseInt(arg, 10); else if (/^[+-]\d+$/.test(arg)) { if (args.bang) level = buffer.fullZoom + parseInt(arg, 10); else level = buffer.textZoom + parseInt(arg, 10); // relative args shouldn't take us out of range level = util.Math.constrain(level, Buffer.ZOOM_MIN, Buffer.ZOOM_MAX); } else liberator.assert(false, "Trailing characters"); if (args.bang) buffer.fullZoom = level; else buffer.textZoom = level; }, { argCount: "?", bang: true }); }, completion: function () { completion.alternateStyleSheet = function alternateStylesheet(context) { context.title = ["Stylesheet", "Location"]; // unify split style sheets let styles = {}; buffer.alternateStyleSheets.forEach(function (style) { if (!(style.title in styles)) styles[style.title] = []; styles[style.title].push(style.href || "inline"); }); context.completions = [[s, styles[s].join(", ")] for (s in styles)]; }; const UNTITLED_LABEL = "(Untitled)"; function getIndicator (tab) { if (tab == config.tabbrowser.mCurrentTab) return "%"; else if (tab == tabs.alternate) return "#"; return " "; } function getURLFromTab (tab) { if ("linkedBrowser" in tab) return tab.linkedBrowser.contentDocument.location.href; else { let i = config.tabbrowser.mTabContainer.getIndexOfItem(tab); let info = config.tabbrowser.tabInfo[i]; return info.browser ? info.browser.contentDocument.location.href : info.mode.getBrowser(tab).contentDocument.location.href; } } function createItem (prefix, label, url, indicator, icon) { return { text: [prefix + label, prefix + url], url: template.highlightURL(url, true, "buffer-list"), indicator: indicator, icon: icon || DEFAULT_FAVICON }; } function generateTabs (tabs) { for (let i = 0, tab; tab = tabs[i]; i++) { let indicator = getIndicator(tab) + (tab.pinned ? "@" : " "), label = tab.label || UNTITLED_LABEL, url = getURLFromTab(tab), index = ((tab._tPos || i) + 1) + ": "; let item = createItem(index, label, url, indicator, tab.image); if (!tab.pinned && tab._tabViewTabItem && tab._tabViewTabItem.parent) { let groupName = tab._tabViewTabItem.parent.getTitle(); if (groupName) { let prefix = groupName + "." + (i + 1) + ": "; item.text.push(prefix + label, prefix + url); } } yield item; } } function generateGroupList (group, groupName) { let hasName = !!groupName; for (let [i, tabItem] in Iterator(group.getChildren())) { let index = (tabItem.tab._tPos + 1) + ": ", label = tabItem.tab.label || UNTITLED_LABEL, url = getURLFromTab(tabItem.tab); let item = createItem(index, label, url, getIndicator(tabItem.tab), tabItem.tab.image); if (hasName) { let gPrefix = groupName + "." + (i + 1) + ": "; item.text.push(gPrefix + label, gPrefix + url); } yield item; } } completion.buffer = function buffer(context, flags) { context.anchored = false; context.keys = { text: "text", description: "url", icon: "icon" }; context.compare = CompletionContext.Sort.number; let process = context.process[0]; context.process = [function (item, text) xml` <span highlight="Indicator" style="display: inline-block; width: 2ex; padding-right: 0.5ex; text-align: right">${item.item.indicator}</span> ${ process.call(this, item, text) } `]; let tabs; if (!flags) { flags = this.buffer.VISIBLE; tabs = config.tabbrowser.mTabs; } if (flags & this.buffer.VISIBLE) { context.title = ["Buffers"]; context.completions = [item for (item in generateTabs(tabs || config.tabbrowser.visibleTabs))]; } if (!liberator.has("tabgroup")) return; let groups = tabGroup.tabView.GroupItems; if (flags & this.buffer.GROUPS) { let activeGroup = groups.getActiveGroupItem(); let activeGroupId = activeGroup === null ? null : activeGroup.id; for (let group of groups.groupItems) { if (group.id != activeGroupId) { let groupName = group.getTitle(); context.fork("GROUP_" + group.id, 0, this, function (context) { context.title = [groupName || UNTITLED_LABEL]; context.completions = [item for (item in generateGroupList(group, groupName))]; }); } } } }; completion.buffer.ALL = 1 << 0 | 1 << 1 | 1 << 2; completion.buffer.VISIBLE = 1 << 0; completion.buffer.GROUPS = 1 << 1; }, events: function () { let browserWindow; if (config.hostApplication == "Thunderbird") { browserWindow = "MsgStatusFeedback"; let activityManager = Cc["@mozilla.org/activity-manager;1"].getService(Ci.nsIActivityManager); activityManager.removeListener(window.MsgStatusFeedback); this.progressListener = update(Object.create(window.MsgStatusFeedback), this.progressListener); statusFeedback.setWrappedStatusFeedback(this.progressListener); activityManager.addListener(this.progressListener); } else { browserWindow = "XULBrowserWindow"; this.progressListener = update(Object.create(window.XULBrowserWindow), this.progressListener); } window[browserWindow] = this.progressListener; window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShellTreeItem) .treeOwner .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIXULWindow) .XULBrowserWindow = this.progressListener; try { config.browser.addProgressListener(this.progressListener); } catch (e) {} // Why? --djk let appContent = document.getElementById("appcontent"); if (appContent) { events.addSessionListener(appContent, "DOMContentLoaded", this.closure.onDOMContentLoaded, true); events.addSessionListener(appContent, "load", this.closure.onPageLoad, true); events.addSessionListener(appContent, "scroll", this.closure._updateBufferPosition, false); } }, mappings: function () { var myModes = config.browserModes; mappings.add(myModes, ["."], "Repeat the last key event", function (count) { if (mappings.repeat) { for (let i in util.interruptibleRange(0, Math.max(count, 1), 100)) mappings.repeat(); } }, { count: true }); mappings.add(myModes, ["c"], "Start caret mode", function () { if (Editor.windowIsEditable()) { if (options["insertmode"]) modes.set(modes.INSERT); else if (win.getSelection().toString() != "") modes.set(modes.VISUAL, modes.TEXTAREA); else modes.main = modes.TEXTAREA; } else { // setting this option notifies an observer which takes care of the // mode setting options.setPref("accessibility.browsewithcaret", true); } }); mappings.add(myModes, ["<C-c>"], "Stop loading the current web page", function () { let controller = window.document.commandDispatcher.getControllerForCommand("cmd_copy"); if (controller && controller.isCommandEnabled("cmd_copy")) { controller.doCommand("cmd_copy"); // clear any selection made let selection = Buffer.focusedWindow.getSelection(); try { // a simple if (selection) does not seem to work selection.collapseToStart(); } catch (e) {} } else { // stop loading page tabs.stop(config.browser.mCurrentTab); } }); // scrolling mappings.add(myModes, ["j", "<Down>", "<C-e>"], "Scroll document down", function (count) { buffer.scrollLines(Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["k", "<Up>", "<C-y>"], "Scroll document up", function (count) { buffer.scrollLines(-Math.max(count, 1)); }, { count: true }); mappings.add(myModes, liberator.has("mail") ? ["h"] : ["h", "<Left>"], "Scroll document to the left", function (count) { buffer.scrollColumns(-Math.max(count, 1)); }, { count: true }); mappings.add(myModes, liberator.has("mail") ? ["l"] : ["l", "<Right>"], "Scroll document to the right", function (count) { buffer.scrollColumns(Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["0", "^"], "Scroll to the absolute left of the document", function () { buffer.scrollStart(); }); mappings.add(myModes, ["$"], "Scroll to the absolute right of the document", function () { buffer.scrollEnd(); }); mappings.add(myModes, ["gg", "<Home>"], "Go to the top of the document", function (count) { buffer.scrollToPercent(buffer.scrollXPercent, Math.max(count, 0)); }, { count: true }); mappings.add(myModes, ["G", "<End>"], "Go to the end of the document", function (count) { buffer.scrollToPercent(buffer.scrollXPercent, count != null ? count : 100); }, { count: true }); mappings.add(myModes, ["%"], "Scroll to {count} percent of the document", function (count) { liberator.assert(count > 0 && count <= 100); buffer.scrollToPercent(buffer.scrollXPercent, count); }, { count: true }); mappings.add(myModes, ["<C-d>"], "Scroll window downwards in the buffer", function (count) { buffer._scrollByScrollSize(count, true); }, { count: true }); mappings.add(myModes, ["<C-u>"], "Scroll window upwards in the buffer", function (count) { buffer._scrollByScrollSize(count, false); }, { count: true }); mappings.add(myModes, ["<C-b>", "<PageUp>", "<S-Space>"], "Scroll up a full page", function (count) { buffer.scrollPages(-Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["<C-f>", "<PageDown>", "<Space>"], "Scroll down a full page", function (count) { buffer.scrollPages(Math.max(count, 1)); }, { count: true }); mappings.add(myModes, ["]f"], "Focus next frame", function (count) { buffer.shiftFrameFocus(Math.max(count, 1), true); }, { count: true }); mappings.add(myModes, ["[f"], "Focus previous frame", function (count) { buffer.shiftFrameFocus(Math.max(count, 1), false); }, { count: true }); mappings.add(myModes, ["]]"], "Follow the link labeled 'next' or '>' if it exists", function (count) { buffer.followDocumentRelationship("next"); }, { count: true }); mappings.add(myModes, ["[["], "Follow the link labeled 'prev', 'previous' or '<' if it exists", function (count) { buffer.followDocumentRelationship("previous"); }, { count: true }); mappings.add(myModes, ["gf"], "View source", function () { buffer.viewSource(null, false); }); mappings.add(myModes, ["gF"], "View source with an external editor", function () { buffer.viewSource(null, true); }); mappings.add(myModes, ["gi"], "Focus last used input field", function (count) { if (count < 1 && buffer.lastInputField) buffer.focusElement(buffer.lastInputField); else { let xpath = ["input[not(@type) or @type='text' or @type='password' or @type='file' or @type='datetime' or @type='datetime-local' or @type='date' or @type='month' or @type='time' or @type='week' or @type='number' or @type='range' or @type='email' or @type='url' or @type='search' or @type='tel' or @type='color']", "textarea[not(@disabled) and not(@readonly)]", "iframe"]; let elements = [m for (m in util.evaluateXPath(xpath)) if(m.getClientRects().length && (!(m instanceof HTMLIFrameElement) || Editor.windowIsEditable(m.contentWindow))) ]; liberator.assert(elements.length > 0); buffer.focusElement(elements[util.Math.constrain(count, 1, elements.length) - 1]); } }, { count: true }); mappings.add(myModes, ["gP"], "Open (put) a URL based on the current clipboard contents in a new buffer", function () { liberator.open(util.readFromClipboard(), liberator[options.get("activate").has("paste") ? "NEW_BACKGROUND_TAB" : "NEW_TAB"]); }); mappings.add(myModes, ["p", "<MiddleMouse>"], "Open (put) a URL based on the current clipboard contents in the current buffer", function () { let url = util.readFromClipboard(); liberator.assert(url); liberator.open(url); }); mappings.add(myModes, ["P"], "Open (put) a URL based on the current clipboard contents in a new buffer", function () { let url = util.readFromClipboard(); liberator.assert(url); liberator.open(url, { from: "paste", where: liberator.NEW_TAB }); }); // reloading mappings.add(myModes, ["r"], "Reload the current web page", function () { tabs.reload(config.browser.mCurrentTab, false); }); mappings.add(myModes, ["R"], "Reload while skipping the cache", function () { tabs.reload(config.browser.mCurrentTab, true); }); // yanking mappings.add(myModes, ["Y"], "Copy selected text or current word", function () { let sel = buffer.getCurrentWord(); liberator.assert(sel); util.copyToClipboard(sel, true); }); // zooming mappings.add(myModes, ["zi", "+"], "Enlarge text zoom of current web page", function (count) { buffer.zoomIn(Math.max(count, 1), false); }, { count: true }); mappings.add(myModes, ["zm"], "Enlarge text zoom of current web page by a larger amount", function (count) { buffer.zoomIn(Math.max(count, 1) * 3, false); }, { count: true }); mappings.add(myModes, ["zo", "-"], "Reduce text zoom of current web page", function (count) { buffer.zoomOut(Math.max(count, 1), false); }, { count: true }); mappings.add(myModes, ["zr"], "Reduce text zoom of current web page by a larger amount", function (count) { buffer.zoomOut(Math.max(count, 1) * 3, false); }, { count: true }); mappings.add(myModes, ["zz"], "Set text zoom value of current web page", function (count) { buffer.textZoom = count > 1 ? count : 100; }, { count: true }); mappings.add(myModes, ["zI"], "Enlarge full zoom of current web page", function (count) { buffer.zoomIn(Math.max(count, 1), true); }, { count: true }); mappings.add(myModes, ["zM"], "Enlarge full zoom of current web page by a larger amount", function (count) { buffer.zoomIn(Math.max(count, 1) * 3, true); }, { count: true }); mappings.add(myModes, ["zO"], "Reduce full zoom of current web page", function (count) { buffer.zoomOut(Math.max(count, 1), true); }, { count: true }); mappings.add(myModes, ["zR"], "Reduce full zoom of current web page by a larger amount", function (count) { buffer.zoomOut(Math.max(count, 1) * 3, true); }, { count: true }); mappings.add(myModes, ["zZ"], "Set full zoom value of current web page", function (count) { buffer.fullZoom = count > 1 ? count : 100; }, { count: true }); // page info mappings.add(myModes, ["<C-g>"], "Print the current file name", function (count) { buffer.showPageInfo(false); }, { count: true }); mappings.add(myModes, ["g<C-g>"], "Print file information", function () { buffer.showPageInfo(true); commandline.show("pageinfo"); }); }, options: function () { options.add(["nextpattern"], // \u00BB is » (>> in a single char) "Patterns to use when guessing the 'next' page in a document sequence", "stringlist", "\\bnext\\b,^>$,^(>>|\u00BB)$,^(>|\u00BB),(>|\u00BB)$,\\bmore\\b"); options.add(["previouspattern"], // \u00AB is « (<< in a single char) "Patterns to use when guessing the 'previous' page in a document sequence", "stringlist", "\\bprev|previous\\b,^<$,^(<<|\u00AB)$,^(<|\u00AB),(<|\u00AB)$"); options.add(["pageinfo", "pa"], "Desired info in the :pageinfo output", "charlist", "gfm", { completer: function (context) [[k, v[1]] for ([k, v] in Iterator(buffer.pageInfo))] }); options.add(["scroll", "scr"], "Number of lines to scroll with <C-u> and <C-d> commands", "number", 0, { validator: function (value) value >= 0 }); options.add(["showstatuslinks", "ssli"], "Show the destination of the link under the cursor in the status bar", "number", 1, { completer: function (context) [ ["0", "Don't show link destination"], ["1", "Show the link in the status line"], ["2", "Show the link in the command line"] ] }); // TODO: Fix the compose window if (!config.isComposeWindow) { options.add(["usermode", "um"], "Show current website with a minimal style sheet to make it easily accessible", "boolean", false, { setter: function (value) config.browser.markupDocumentViewer.authorStyleDisabled = value, getter: function () config.browser.markupDocumentViewer.authorStyleDisabled }); } } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * Cached XPCOM services and classes. * * @constructor */ const Services = Module("services", { init: function () { this.classes = {}; this.jsm = window.Services; this.services = { "autoCompleteSearch": { class_: "@mozilla.org/autocomplete/search;1?name=history", iface: Ci.nsIAutoCompleteSearch }, "bookmarks": { class_: "@mozilla.org/browser/nav-bookmarks-service;1", iface: Ci.nsINavBookmarksService }, "liberator:": { class_: "@mozilla.org/network/protocol;1?name=liberator" }, "debugger": { class_: "@mozilla.org/js/jsd/debugger-service;1", iface: Ci.jsdIDebuggerService }, "environment": { class_: "@mozilla.org/process/environment;1", iface: Ci.nsIEnvironment }, "favicon": { class_: "@mozilla.org/browser/favicon-service;1", iface: Ci.nsIFaviconService }, "history": { class_: "@mozilla.org/browser/nav-history-service;1", iface: [Ci.nsINavHistoryService, Ci.nsIBrowserHistory] }, "privateBrowsing": { class_: "@mozilla.org/privatebrowsing;1", iface: Ci.nsIPrivateBrowsingService }, "profile": { class_: "@mozilla.org/toolkit/profile-service;1", iface: Ci.nsIToolkitProfileService }, "rdf": { class_: "@mozilla.org/rdf/rdf-service;1", iface: Ci.nsIRDFService }, "sessionStore": { class_: "@mozilla.org/browser/sessionstore;1", iface: Ci.nsISessionStore }, "threadManager": { class_: "@mozilla.org/thread-manager;1", iface: Ci.nsIThreadManager }, "UUID": { class_: "@mozilla.org/uuid-generator;1", iface: Ci.nsIUUIDGenerator }, "textToSubURI": { class_: "@mozilla.org/intl/texttosuburi;1", iface: Ci.nsITextToSubURI }, }; this.addClass("file", "@mozilla.org/file/local;1", Ci.nsILocalFile); this.addClass("file:", "@mozilla.org/network/protocol;1?name=file", Ci.nsIFileProtocolHandler); this.addClass("find", "@mozilla.org/embedcomp/rangefind;1", Ci.nsIFind); this.addClass("process", "@mozilla.org/process/util;1", Ci.nsIProcess); this.addClass("timer", "@mozilla.org/timer;1", Ci.nsITimer); }, _create: function (classes, ifaces, meth) { try { let res = Cc[classes][meth || "getService"](); if (!ifaces) return res.wrappedJSObject; ifaces = Array.concat(ifaces); ifaces.forEach(function (iface) res.QueryInterface(iface)); return res; } catch (e) { // liberator.log() is not defined at this time, so just dump any error dump("Service creation failed for '" + classes + "': " + e + "\n"); return null; } }, /** * Adds a new XPCOM service to the cache. * * @param {string} name The service's cache key. * @param {string} class The class's contract ID. * @param {nsISupports|nsISupports[]} ifaces The interface or array of * interfaces implemented by this service. * @param {string} meth The name of the function used to instanciate * the service. */ add: function (name, class_, ifaces, meth) { this.services[name] = {"class_": class_, "iface": ifaces, "meth": meth}; }, /** * Adds a new XPCOM class to the cache. * * @param {string} name The class's cache key. * @param {string} class The class's contract ID. * @param {nsISupports|nsISupports[]} ifaces The interface or array of * interfaces implemented by this class. */ addClass: function (name, class_, ifaces) { const self = this; return this.classes[name] = function () self._create(class_, ifaces, "createInstance"); }, /** * Returns the cached service with the specified name. * * @param {string} name The service's cache key. */ get: function (name) { if (this.jsm.hasOwnProperty(name)) return this.jsm[name]; if (!this.services.hasOwnProperty(name)) throw Error("Could not get service: " + name); if (!this.services[name]["reference"]) { var currentService = this.services[name]; this.services[name]["reference"] = this._create(currentService["class_"], currentService["iface"], currentService["meth"]); } return this.services[name]["reference"]; }, /** * Returns a new instance of the cached class with the specified name. * * @param {string} name The class's cache key. */ create: function (name) this.classes[name]() }, window.Services, { completion: function () { JavaScript.setCompleter(this.get, [ function () Object.keys(services.jsm).concat(Object.keys(services.services)).map(function(key) [key, ""]) ]); JavaScript.setCompleter(this.create, [function () [[c, ""] for (c in services.classes)]]); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. const ConfigBase = Class(ModuleBase, { /** * @property {[["string", "string"]]} A sequence of names and descriptions * of the autocommands available in this application. Primarily used * for completion results. */ autocommands: [], get browser() window.gBrowser, get tabbrowser() window.gBrowser, get browserModes() [modes.NORMAL], /** * @property {Object} Application specific defaults for option values. The * property names must be the options' canonical names, and the values * must be strings as entered via :set. */ defaults: { toolbars: "" }, /** * @property {[["string", "string", "function"]]} An array of * dialogs available via the :dialog command. * [0] name - The name of the dialog, used as the first * argument to :dialog. * [1] description - A description of the dialog, used in * command completion results for :dialog. * [2] action - The function executed by :dialog. */ dialogs: [], /** * @property {string[]} A list of features available in this * application. Used extensively in feature test macros. Use * liberator.has(feature) to check for a feature's presence * in this array. */ features: new Set, guioptions: {}, hasTabbrowser: false, /** * @property {string} The name of the application that hosts the * “liberated” application. E.g., "Firefox" or "Xulrunner". */ hostApplication: null, /** * @property {function} Called on liberator startup to allow for any * arbitrary application-specific initialization code. */ init: function () {}, /** * @property {Object} A map between key names for key events should be ignored, * and a mask of the modes in which they should be ignored. */ ignoreKeys: {}, // XXX: be aware you can't put useful values in here, as "modes.NORMAL" etc. are not defined at this time /** * @property {string} The ID of the application's main XUL window. */ mainWindowId: document.documentElement.id, /** * @property {[[]]} An array of application specific mode specifications. * The values of each mode are passed to modes.addMode during * liberator startup. */ modes: [], /** * @property {string} The name of “liberated” application. * Required. */ name: null, /** * @property {number} The height (px) that is available to the output * window. */ get outputHeight() config.browser.mPanelContainer.boxObject.height, /** * @property {[string]} A list of extra scripts in the liberator or * application namespaces which should be loaded before liberator * initialization. */ scripts: [], /** * @property {Object} A list of toolbars which can be shown/hidden * with :set toolbars */ toolbars: {}, /** * @property {string} The leaf name of any temp files created by * {@link io.createTempFile}. */ get tempFile() this.name.toLowerCase() + ".tmp" }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ /** * @instance quickmarks */ const QuickMarks = Module("quickmarks", { requires: ["config", "storage"], init: function () { this._qmarks = storage.newMap("quickmarks", { store: true, privateData: true }); }, /** * Adds a new quickmark with name <b>qmark</b> referencing * the URL <b>location</b>. Any existing quickmark with the same name * will be replaced. * * @param {string} qmark The name of the quickmark {A-Z}. * @param {string} location The URL accessed by this quickmark. */ add: function add(qmark, location) { this._qmarks.set(qmark, location); liberator.echomsg("Added QuickMark '" + qmark + "': " + location); }, /** * Deletes the specified quickmarks. The <b>filter</b> is a list of * quickmarks and ranges are supported. Eg. "ab c d e-k". * * @param {string} filter The list of quickmarks to delete. * */ remove: function remove(filter) { let pattern = RegExp("[" + filter.replace(/\s+/g, "") + "]"); for (let [qmark, ] in this._qmarks) { if (pattern.test(qmark)) this._qmarks.remove(qmark); } }, /** * Removes all quickmarks. */ removeAll: function removeAll() { this._qmarks.clear(); }, /** * Opens the URL referenced by the specified <b>qmark</b>. * * @param {string} qmark The quickmark to open. * @param {number} where A constant describing where to open the page. * See {@link Liberator#open}. */ jumpTo: function jumpTo(qmark, where) { let url = this._qmarks.get(qmark); if (url) liberator.open(url, where); else liberator.echoerr("QuickMark not set: " + qmark); }, /** * Lists all quickmarks matching <b>filter</b> in the message window. * * @param {string} filter The list of quickmarks to display. Eg. "abc" * Ranges are not supported. */ // FIXME: filter should match that of quickmarks.remove or vice versa list: function list(filter) { let marks = [k for ([k, v] in this._qmarks)]; let lowercaseMarks = marks.filter(function (x) /[a-z]/.test(x)).sort(); let uppercaseMarks = marks.filter(function (x) /[A-Z]/.test(x)).sort(); let numberMarks = marks.filter(function (x) /[0-9]/.test(x)).sort(); marks = Array.concat(lowercaseMarks, uppercaseMarks, numberMarks); liberator.assert(marks.length > 0, "No QuickMarks set"); if (filter.length > 0) { marks = marks.filter(function (qmark) filter.indexOf(qmark) >= 0); liberator.assert(marks.length >= 0, "No matching QuickMarks for: " + filter); } let items = [[mark, this._qmarks.get(mark)] for (mark of marks)]; template.genericTable(items, { title: ["QuickMark", "URL"] }); } }, { }, { commands: function () { commands.add(["delqm[arks]"], "Delete the specified QuickMarks", function (args) { // TODO: finish arg parsing - we really need a proper way to do this. :) // assert(args.bang ^ args.string) liberator.assert( args.bang || args.string, "Argument required"); liberator.assert(!args.bang || !args.string, "Invalid argument"); if (args.bang) quickmarks.removeAll(); else quickmarks.remove(args.string); }, { bang: true, completer: function (context) { context.title = ["QuickMark", "URL"]; context.completions = quickmarks._qmarks; } }); commands.add(["qma[rk]"], "Mark a URL with a letter for quick access", function (args) { let matches = args.string.match(/^([a-zA-Z0-9])(?:\s+(.+))?$/); if (!matches) liberator.echoerr("Trailing characters"); else if (!matches[2]) quickmarks.add(matches[1], buffer.URL); else quickmarks.add(matches[1], matches[2]); }, { argCount: "+" }); commands.add(["qmarks"], "Show all QuickMarks", function (args) { args = args.string; // ignore invalid qmark characters unless there are no valid qmark chars liberator.assert(!args || /[a-zA-Z0-9]/.test(args), "No matching QuickMarks for: " + args); let filter = args.replace(/[^a-zA-Z0-9]/g, ""); quickmarks.list(filter); }); }, mappings: function () { var myModes = config.browserModes; mappings.add(myModes, ["go"], "Jump to a QuickMark", function (arg) { quickmarks.jumpTo(arg, liberator.CURRENT_TAB); }, { arg: true }); mappings.add(myModes, ["gn"], "Jump to a QuickMark in a new tab", function (arg) { quickmarks.jumpTo(arg, options.get("activate").has("all", "quickmark") ? liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB); }, { arg: true }); mappings.add(myModes, ["M"], "Add new QuickMark for current URL", function (arg) { liberator.assert(/^[a-zA-Z0-9]$/.test(arg)); quickmarks.add(arg, buffer.URL); }, { arg: true }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. // TODO: Clean this up. const JavaScript = Module("javascript", { init: function () { this._stack = []; this._functions = []; this._top = {}; // The element on the top of the stack. this._last = ""; // The last opening char pushed onto the stack. this._lastNonwhite = ""; // Last non-whitespace character we saw. this._lastChar = ""; // Last character we saw, used for \ escaping quotes. this._str = ""; this._lastIdx = 0; this._cacheKey = null; }, get completers() JavaScript.completers, // For backward compatibility // Some object members are only accessible as function calls getKey: function (obj, key) { try { return obj[key]; } catch (e) { return undefined; } }, iter: function iter(obj, toplevel) { toplevel = !!toplevel; let seen = {}; try { let orig = obj; function iterObj(obj, toplevel) { function isXPCNativeWrapper(obj) isobject(obj) && XPCNativeWrapper.unwrap(obj) !== obj if (isXPCNativeWrapper(obj)) { if (toplevel) { yield {get wrappedJSObject() 0}; } // according to http://getfirebug.com/wiki/index.php/Using_win.wrappedJSObject // using a wrappedJSObject itself is safe, as potential functions are always // run in page context, not in chrome context. // However, as we really need to make sure, values coming // from content scope are never used in unsecured eval(), // we dissallow unwrapping objects for now, unless the user // uses an (undocumented) option 'unwrapjsobjects' else if (options["inspectcontentobjects"]) { obj = obj.wrappedJSObject; } } if (toplevel) yield obj; else for (let o = obj.__proto__; o; o = o.__proto__) yield o; } for (let obj in iterObj(orig, toplevel)) { for (let k of Object.getOwnPropertyNames(obj)) { let name = "|" + k; if (name in seen) continue; seen[name] = 1; yield [k, this.getKey(orig, k)]; } } } catch (ex) { // TODO: report error? } }, // Search the object for strings starting with @key. // If @last is defined, key is a quoted string, it's // wrapped in @last after @offset characters are sliced // off of it and it's quoted. objectKeys: function objectKeys(obj, toplevel) { // Things we can dereference if (["object", "string", "function"].indexOf(typeof obj) == -1) return []; if (!obj) return []; let completions; if (modules.isPrototypeOf(obj)) completions = [v for (v in Iterator(obj))]; else { completions = [k for (k in this.iter(obj, toplevel))]; if (!toplevel) completions = util.Array.uniq(completions, true); } // Add keys for sorting later. // Numbers are parsed to ints. // Constants, which should be unsorted, are found and marked null. completions.forEach(function (item) { let key = item[0]; if (!isNaN(key)) key = parseInt(key); else if (/^[A-Z_][A-Z0-9_]*$/.test(key)) key = ""; item.key = key; }); return completions; }, eval: function eval(arg, key, tmp) { let cache = this.context.cache.eval; let context = this.context.cache.evalContext; if (!key) key = arg; if (key in cache) return cache[key]; context[JavaScript.EVAL_TMP] = tmp; try { return cache[key] = liberator.eval(arg, context); } catch (e) { return null; } finally { delete context[JavaScript.EVAL_TMP]; } }, // Get an element from the stack. If @frame is negative, // count from the top of the stack, otherwise, the bottom. // If @nth is provided, return the @mth value of element @type // of the stack entry at @frame. _get: function (frame, nth, type) { let a = this._stack[frame >= 0 ? frame : this._stack.length + frame]; if (type != null) a = a[type]; if (nth == null) return a; return a[a.length - nth - 1]; }, // Push and pop the stack, maintaining references to 'top' and 'last'. _push: function push(arg) { this._top = { offset: this._i, char: arg, statements: [this._i], dots: [], fullStatements: [], comma: [], functions: [] }; this._last = this._top.char; this._stack.push(this._top); }, _pop: function pop(arg) { if (this._top.char != arg) { this.context.highlight(this._top.offset, this._i - this._top.offset, "SPELLCHECK"); this.context.highlight(this._top.offset, 1, "FIND"); throw new Error("Invalid JS"); } if (this._i == this.context.caret - 1) this.context.highlight(this._top.offset, 1, "FIND"); // The closing character of this stack frame will have pushed a new // statement, leaving us with an empty statement. This doesn't matter, // now, as we simply throw away the frame when we pop it, but it may later. if (this._top.statements[this._top.statements.length - 1] == this._i) this._top.statements.pop(); this._top = this._get(-2); this._last = this._top.char; let ret = this._stack.pop(); return ret; }, _buildStack: function (filter) { let self = this; // Todo: Fix these one-letter variable names. this._i = 0; this._c = ""; // Current index and character, respectively. // Reuse the old stack. if (this._str && filter.substr(0, this._str.length) == this._str) { this._i = this._str.length; if (this.popStatement) this._top.statements.pop(); } else { this._stack = []; this._functions = []; this._push("#root"); } // Build a parse stack, discarding entries as opening characters // match closing characters. The stack is walked from the top entry // and down as many levels as it takes us to figure out what it is // that we're completing. this._str = filter; let length = this._str.length; for (; this._i < length; this._lastChar = this._c, this._i++) { this._c = this._str[this._i]; if (this._last == '"' || this._last == "'" || this._last == "/") { if (this._lastChar == "\\") { // Escape. Skip the next char, whatever it may be. this._c = ""; this._i++; } else if (this._c == this._last) this._pop(this._c); } else if (this._last === "`") { if (this._lastChar == "\\") { // Escape. Skip the next char, whatever it may be. this._c = ""; this._i++; } else if (this._c == "`") { this._pop("`"); this._pop("``"); } else if (this._c === "{" && this._lastChar === "$") { this._pop("`"); this._push("{"); } } else { // A word character following a non-word character, or simply a non-word // character. Start a new statement. if (/[a-zA-Z_$]/.test(this._c) && !/[\w$]/.test(this._lastChar) || !/[\w\s$]/.test(this._c)) this._top.statements.push(this._i); // A "." or a "[" dereferences the last "statement" and effectively // joins it to this logical statement. if ((this._c == "." || this._c == "[") && /[\w$\])"']/.test(this._lastNonwhite) || this._lastNonwhite == "." && /[a-zA-Z_$]/.test(this._c)) this._top.statements.pop(); switch (this._c) { case "(": // Function call, or if/while/for/... if (/[\w$]/.test(this._lastNonwhite)) { this._functions.push(this._i); this._top.functions.push(this._i); this._top.statements.pop(); } case '"': case "'": case "/": case "{": this._push(this._c); break; case "[": this._push(this._c); break; case ".": this._top.dots.push(this._i); break; case ")": this._pop("("); break; case "]": this._pop("["); break; case "}": this._pop("{"); // Fallthrough if (this._last === "``") { this._push("`"); break; } case ";": this._top.fullStatements.push(this._i); break; case ",": this._top.comma.push(this._i); break; case "`": this._push("``"); this._push("`"); break; } if (/\S/.test(this._c)) this._lastNonwhite = this._c; } } this.popStatement = false; if (!/[\w$]/.test(this._lastChar) && this._lastNonwhite != ".") { this.popStatement = true; this._top.statements.push(this._i); } this._lastIdx = this._i; }, // Don't eval any function calls unless the user presses tab. _checkFunction: function (start, end, key) { let res = this._functions.some(function (idx) idx >= start && idx < end); if (!res || this.context.tabPressed || key in this.cache.eval) return false; this.context.waitingForTab = true; return true; }, // For each DOT in a statement, prefix it with TMP, eval it, // and save the result back to TMP. The point of this is to // cache the entire path through an object chain, mainly in // the presence of function calls. There are drawbacks. For // instance, if the value of a variable changes in the course // of inputting a command (let foo=bar; frob(foo); foo=foo.bar; ...), // we'll still use the old value. But, it's worth it. _getObj: function (frame, stop) { let statement = this._get(frame, 0, "statements") || 0; // Current statement. let prev = statement; let obj; let cacheKey; for (let dot of this._get(frame).dots.concat(stop)) { if (dot < statement) continue; if (dot > stop || dot <= prev) break; let s = this._str.substring(prev, dot); if (prev != statement) s = JavaScript.EVAL_TMP + "." + s; cacheKey = this._str.substring(statement, dot); if (this._checkFunction(prev, dot, cacheKey)) return []; prev = dot + 1; obj = this.eval(s, cacheKey, obj); } return [[obj, cacheKey]]; }, _getObjKey: function (frame) { let dot = this._get(frame, 0, "dots") || -1; // Last dot in frame. let statement = this._get(frame, 0, "statements") || 0; // Current statement. let end = (frame == -1 ? this._lastIdx : this._get(frame + 1).offset); this._cacheKey = null; let obj = [[this.cache.evalContext, "Local Variables"], [userContext, "Global Variables"], [modules, "modules"], [window, "window"]]; // Default objects; // Is this an object dereference? if (dot < statement) // No. dot = statement - 1; else // Yes. Set the object to the string before the dot. obj = this._getObj(frame, dot); let [, space, key] = this._str.substring(dot + 1, end).match(/^(\s*)(.*)/); return [dot + 1 + space.length, obj, key]; }, _fill: function (context, obj, name, compl, anchored, key, last, offset) { context.title = [name]; context.anchored = anchored; context.filter = key; context.itemCache = context.parent.itemCache; context.key = name; if (last != null) context.quote = [last, function (text) util.escapeString(text.substr(offset), ""), last]; else // We're not looking for a quoted string, so filter out anything that's not a valid identifier context.filters.push(function (item) /^[a-zA-Z_$][\w$]*$/.test(item.text)); compl.call(self, context, obj); }, _complete: function (objects, key, compl, string, last) { const self = this; let orig = compl; if (!compl) { compl = function (context, obj, recurse) { context.process = [null, function highlight(item, v) template.highlight(v, true)]; // Sort in a logical fashion for object keys: // Numbers are sorted as numbers, rather than strings, and appear first. // Constants are unsorted, and appear before other non-null strings. // Other strings are sorted in the default manner. let compare = context.compare; function isnan(item) item != '' && isNaN(item); context.compare = function (a, b) { if (!isnan(a.item.key) && !isnan(b.item.key)) return a.item.key - b.item.key; return isnan(b.item.key) - isnan(a.item.key) || compare(a, b); }; if (!context.anchored) // We've already listed anchored matches, so don't list them again here. context.filters.push(function (item) util.compareIgnoreCase(item.text.substr(0, this.filter.length), this.filter)); if (obj == self.cache.evalContext) context.regenerate = true; context.generate = function () self.objectKeys(obj, !recurse); }; } // TODO: Make this a generic completion helper function. let filter = key + (string || ""); for (let obj of objects) { this.context.fork(obj[1], this._top.offset, this, this._fill, obj[0], obj[1], compl, true, filter, last, key.length); } if (orig) return; for (let obj of objects) { let name = obj[1] + " (prototypes)"; this.context.fork(name, this._top.offset, this, this._fill, obj[0], name, function (a, b) compl(a, b, true), true, filter, last, key.length); } for (let obj of objects) { let name = obj[1] + " (substrings)"; this.context.fork(name, this._top.offset, this, this._fill, obj[0], name, compl, false, filter, last, key.length); } for (let obj of objects) { let name = obj[1] + " (prototype substrings)"; this.context.fork(name, this._top.offset, this, this._fill, obj[0], name, function (a, b) compl(a, b, true), false, filter, last, key.length); } }, _getKey: function () { if (this._last == "") return ""; // After the opening [ upto the opening ", plus '' to take care of any operators before it let key = this._str.substring(this._get(-2, 0, "statements"), this._get(-1, null, "offset")) + "''"; // Now eval the key, to process any referenced variables. return this.eval(key); }, get cache() this.context.cache, complete: function _complete(context) { const self = this; this.context = context; try { this._buildStack.call(this, context.filter); } catch (e) { if (e.message != "Invalid JS") liberator.echoerr(e); this._lastIdx = 0; return null; } this.context.getCache("eval", Object); this.context.getCache("evalContext", function () Object.create(userContext)); // Okay, have parse stack. Figure out what we're completing. // Find any complete statements that we can eval before we eval our object. // This allows for things like: let doc = window.content.document; let elem = doc.createElement...; elem.<Tab> let prev = 0; for (let v of this._get(0).fullStatements) { let key = this._str.substring(prev, v + 1); if (this._checkFunction(prev, v, key)) return null; this.eval(key); prev = v + 1; } // In a string. Check if we're dereferencing an object. // Otherwise, do nothing. if (this._last == "'" || this._last == '"' || this._last == "`") { // // str = "foo[bar + 'baz" // obj = "foo" // key = "bar + ''" // // The top of the stack is the sting we're completing. // Wrap it in its delimiters and eval it to process escape sequences. let string = this._str.substring(this._get(-1).offset + 1, this._lastIdx); string = eval(this._last + string + this._last); // Is this an object accessor? if (this._get(-2).char == "[") { // Are we inside of []? // Stack: // [-1]: "... // [-2]: [... // [-3]: base statement // Yes. If the [ starts at the beginning of a logical // statement, we're in an array literal, and we're done. if (this._get(-3, 0, "statements") == this._get(-2).offset) return null; // Beginning of the statement upto the opening [ let obj = this._getObj(-3, this._get(-2).offset); return this._complete(obj, this._getKey(), null, string, this._last); } // Is this a function call? if (this._get(-2).char == "(") { // Stack: // [-1]: "... // [-2]: (... // [-3]: base statement // Does the opening "(" mark a function call? if (this._get(-3, 0, "functions") != this._get(-2).offset) return null; // No. We're done. let [offset, obj, func] = this._getObjKey(-3); if (!obj.length) return null; obj = obj.slice(0, 1); try { var completer = obj[0][0][func].liberatorCompleter; } catch (e) {} if (!completer) completer = JavaScript.completers[func]; if (!completer) return null; // Split up the arguments let prev = this._get(-2).offset; let args = []; let i = 0; for (let idx of this._get(-2).comma) { let arg = this._str.substring(prev + 1, idx); prev = idx; util.memoize(args, i, function () self.eval(arg)); ++i; } let key = this._getKey(); args.push(key + string); var compl = function (context, obj) { let res = completer.call(self, context, func, obj, args); if (res) context.completions = res; }; obj[0][1] += "." + func + "(... [" + args.length + "]"; return this._complete(obj, key, compl, string, this._last); } // In a string that's not an obj key or a function arg. // Nothing to do. return null; } // // str = "foo.bar.baz" // obj = "foo.bar" // key = "baz" // // str = "foo" // obj = [modules, window] // key = "foo" // let [offset, obj, key] = this._getObjKey(-1); // Wait for a keypress before completing the default objects. if (!this.context.tabPressed && key == "" && obj.length > 1) { this.context.waitingForTab = true; this.context.message = "Waiting for key press"; return null; } if (!/^(?:[a-zA-Z_$][\w$]*)?$/.test(key)) return null; // Not a word. Forget it. Can this even happen? try { // FIXME var o = this._top.offset; this._top.offset = offset; return this._complete(obj, key); } finally { this._top.offset = o; } return null; } }, { EVAL_TMP: "__liberator_eval_tmp", /** * A map of argument completion functions for named methods. The * signature and specification of the completion function * are fairly complex and yet undocumented. * * @see JavaScript.setCompleter */ completers: {}, /** * Installs argument string completers for a set of functions. * The second argument is an array of functions (or null * values), each corresponding the argument of the same index. * Each provided completion function receives as arguments a * CompletionContext, the 'this' object of the method, and an * array of values for the preceding arguments. * * It is important to note that values in the arguments array * provided to the completers are lazily evaluated the first * time they are accessed, so they should be accessed * judiciously. * * @param {function|function[]} funcs The functions for which to * install the completers. * @param {function[]} completers An array of completer * functions. */ setCompleter: function (funcs, completers) { funcs = Array.concat(funcs); for (let func of funcs) { func.liberatorCompleter = function (context, func, obj, args) { let completer = completers[args.length - 1]; if (!completer) return []; return completer.call(this, context, obj, args); }; } } }, { completion: function () { completion.javascript = this.closure.complete; completion.javascriptCompleter = JavaScript; // Backwards compatibility. }, options: function () { options.add(["inspectcontentobjects"], "Allow completion of JavaScript objects coming from web content. POSSIBLY INSECURE!", "boolean", false); options.add(["expandtemplate"], "Expand TemplateLiteral", "boolean", !("XMLList" in window)); } })
JavaScript
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /* Adds support for data: URIs with chrome privileges * and fragment identifiers. * * "chrome-data:" <content-type> [; <flag>]* "," [<data>] * * By Kris Maglione, ideas from Ed Anuff's nsChromeExtensionHandler. */ const { classes: Cc, interfaces: Ci, utils: Cu } = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyGetter(this, "convert", function () { var obj = new Object; Cu.import("resource://liberator/template.js", obj); return obj.convert; }); const NS_BINDING_ABORTED = 0x804b0002; const nsIProtocolHandler = Ci.nsIProtocolHandler; const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); let channel = Components.classesByID["{61ba33c0-3031-11d3-8cd0-0060b0fc14a3}"] .getService(Ci.nsIProtocolHandler) .newChannel(ioService.newURI("chrome://liberator/content/data", null, null)) .QueryInterface(Ci.nsIRequest); const systemPrincipal = channel.owner; channel.cancel(NS_BINDING_ABORTED); delete channel; function dataURL(type, data) "data:" + (type || "application/xml;encoding=UTF-8") + "," + encodeURIComponent(data); function makeChannel(url, orig) { if (typeof url == "function") url = dataURL.apply(null, url()); let uri = ioService.newURI(url, null, null); let channel = ioService.newChannelFromURI(uri); channel.owner = systemPrincipal; channel.originalURI = orig; return channel; } function fakeChannel(orig) makeChannel("chrome://liberator/content/does/not/exist", orig); function redirect(to, orig) { //xxx: escape let html = '<html><head><meta http-equiv="Refresh" content="' + ("0;" + to).replace(/"/g, "&quot;") + '"/></head></html>'; return makeChannel(dataURL('text/html', html), ioService.newURI(to, null, null)); } XPCOMUtils.defineLazyGetter(this, "cache", function () { var dir = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile); dir.append("liberatorCache"); if (!dir.exists()) { dir.create(dir.DIRECTORY_TYPE, -1); } return dir; }); XPCOMUtils.defineLazyGetter(this, "version", function () { return Services.appinfo.version; }); function ChromeData() {} ChromeData.prototype = { contractID: "@mozilla.org/network/protocol;1?name=chrome-data", classID: Components.ID("{c1b67a07-18f7-4e13-b361-2edcc35a5a0d}"), classDescription: "Data URIs with chrome privileges", QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]), _xpcom_factory: { createInstance: function (outer, iid) { if (!ChromeData.instance) ChromeData.instance = new ChromeData(); if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION; return ChromeData.instance.QueryInterface(iid); } }, scheme: "chrome-data", defaultPort: -1, allowPort: function (port, scheme) false, protocolFlags: nsIProtocolHandler.URI_NORELATIVE | nsIProtocolHandler.URI_NOAUTH | nsIProtocolHandler.URI_IS_UI_RESOURCE, newURI: function (spec, charset, baseURI) { var uri = Cc["@mozilla.org/network/standard-url;1"] .createInstance(Ci.nsIStandardURL) .QueryInterface(Ci.nsIURI); uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, null); return uri; }, newChannel: function (uri) { try { if (uri.scheme == this.scheme) return makeChannel(uri.spec.replace(/^.*?:\/*(.*)(?:#.*)?/, "data:$1"), uri); } catch (e) {} return fakeChannel(); } }; function Liberator() { this.wrappedJSObject = this; const self = this; this.HELP_TAGS = {}; this.FILE_MAP = {}; this.OVERLAY_MAP = {}; } Liberator.prototype = { contractID: "@mozilla.org/network/protocol;1?name=liberator", classID: Components.ID("{9c8f2530-51c8-4d41-b356-319e0b155c44}"), classDescription: "Liberator utility protocol", QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]), _xpcom_factory: { createInstance: function (outer, iid) { if (!Liberator.instance) Liberator.instance = new Liberator(); if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION; return Liberator.instance.QueryInterface(iid); } }, init: function (obj) { for each (let prop in ["HELP_TAGS", "FILE_MAP", "OVERLAY_MAP"]) { this[prop] = this[prop].constructor(); for (let [k, v] in Iterator(obj[prop] || {})) this[prop][k] = v } }, scheme: "liberator", defaultPort: -1, allowPort: function (port, scheme) false, protocolFlags: 0 | nsIProtocolHandler.URI_IS_UI_RESOURCE | nsIProtocolHandler.URI_IS_LOCAL_RESOURCE, newURI: function (spec, charset, baseURI) { var uri = Cc["@mozilla.org/network/standard-url;1"] .createInstance(Ci.nsIStandardURL) .QueryInterface(Ci.nsIURI); uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, baseURI); if (uri.host !== "template") return uri; try { spec = uri.spec; //uri.init(uri.URLTYPE_STANDARD, this.defaultPort, uri.path.substr(1), charset, null); // xxx: uri = ioService.newURI(uri.path.replace(new RegExp("^/+"), ""), charset, null); // recursible when override while (uri.scheme === "chrome") { uri = Cc["@mozilla.org/chrome/chrome-registry;1"] .getService(Ci.nsIChromeRegistry) .convertChromeURL(uri); } var nest = Cc["@mozilla.org/network/util;1"].getService(Ci.nsINetUtil).newSimpleNestedURI(uri); nest.spec = spec; } catch (ex) { Cu.reportError(ex); } return nest; }, newChannel: function (uri) { try { if ((uri instanceof Ci.nsINestedURI)) { var m = (new RegExp("^/{2,}([^/]+)/([^?]+)")).exec(uri.path); if (m) { var host = m[1]; var path = m[2]; switch (host) { case "template": try { var nest = ioService.newURI(path, uri.charset, null); var channel = ioService.newChannelFromURI(nest); // xxx: support template if (0) return channel; // xxx: NG: Firefox 16, 17 // NG: Cu.import if (parseFloat(version) < 17) { var stream = Cc["@mozilla.org/scriptableinputstream;1"] .createInstance(Ci.nsIScriptableInputStream); var cstream = channel.open(); stream.init(cstream); var text = stream.read(-1); stream.close(); cstream.close(); stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream); stream.setData(convert(text), -1); var channel = Cc["@mozilla.org/network/input-stream-channel;1"] .createInstance(Ci.nsIInputStreamChannel); channel.contentStream = stream; channel.QueryInterface(Ci.nsIChannel); channel.setURI(uri); return channel; } var innerURI = uri.innerURI; var temp = cache.clone(); var path = nest.spec.replace(/[:\/]/g, "_"); var lastModifiedTime; if (innerURI.scheme === "resource") { innerURI = Cc["@mozilla.org/network/protocol;1?name=resource"] .getService(Ci.nsIResProtocolHandler).resolveURI(innerURI); innerURI = ioService.newURI(innerURI, null, null); } if (innerURI.scheme === "jar") { innerURI = innerURI.QueryInterface(Ci.nsIJARURI).JARFile; } if (innerURI.scheme === "file") { lastModifiedTime = innerURI.QueryInterface(Ci.nsIFileURL).file.lastModifiedTime; } else { Cu.reportError("do not support:" + innerURI.spec); } temp.append(path); if (!temp.exists() || temp.lastModifiedTime !== lastModifiedTime) { var stream = Cc["@mozilla.org/scriptableinputstream;1"] .createInstance(Ci.nsIScriptableInputStream); var cstream = channel.open(); stream.init(cstream); var text = stream.read(-1); stream.close(); cstream.close(); text = convert(text); var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream); Services.console.logStringMessage("create:" + temp.leafName); stream.init(temp, 0x2 | 0x8 | 0x20, 0644, 0); stream.write(text, text.length); stream.close(); temp.lastModifiedTime = lastModifiedTime; } else { Services.console.logStringMessage("use cache:" + uri.spec); } return ioService.newChannelFromURI(ioService.newFileURI(temp)); } catch (ex) { Cu.reportError(ex); } } } return fakeChannel(uri); } switch(uri.host) { case "help": let url = this.FILE_MAP[uri.path.replace(/^\/|#.*/g, "")]; return makeChannel(url, uri); case "help-overlay": url = this.OVERLAY_MAP[uri.path.replace(/^\/|#.*/g, "")]; return makeChannel(url, uri); case "help-tag": let tag = uri.path.substr(1); if (tag in this.HELP_TAGS) return redirect("liberator://help/" + this.HELP_TAGS[tag] + "#" + tag, uri); } } catch (e) { Cu.reportError(e); } return fakeChannel(uri); } }; var components = [ChromeData, Liberator]; if(XPCOMUtils.generateNSGetFactory) var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); else function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule(components); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
(function (){ var tmp = window.location.pathname, //URL= tmp.substr(0,tmp.lastIndexOf("\/")+1).replace("_examples/","").replace("website/",""); URL=URLALL UEDITOR_CONFIG = { imagePath : URL + 'server/upload/', compressSide:0, maxImageSideLength:900, relativePath:true, filePath:URL + "server/upload/", catchRemoteImageEnable:true, catcherUrl:URL +"server/submit/php/getRemoteImage.php", localDomain:"baidu.com", imageManagerPath:URL + "server/submit/php/imageManager.php", UEDITOR_HOME_URL:URL, toolbars: [ ['Source','JustifyLeft','JustifyCenter','JustifyRight','Bold','Underline','Italic','Spechars','Link','Unlink','InsertImage','ImageLeft','ImageNone','ImageRight','ImageCenter','Preview','Undo','Redo','ClearDoc'] ], labelMap: { 'source':'源码','justifyleft':'左对齐','justifycenter':'居中','justifyright':'右对齐','bold':'加粗','underline':'下划线','italic':'斜体','spechars':'特殊字符','link':'超链接','unlink':'取消链接','insertimage':'图片','imageleft':'图片居左','imagenone':'图片默认','imageright':'图片居右','imagecenter':'图片居中','preview':'预览','undo':'撤销','redo':'恢复','cleardoc':'清空文档' }, iframeUrlMap: { 'anchor':'~/dialogs/anchor/anchor.html', 'insertimage':'~/dialogs/image/image.html', 'inserttable':'~/dialogs/table/table.html', 'link':'~/dialogs/link/link.html', 'spechars':'~/dialogs/spechars/spechars.html', 'searchreplace':'~/dialogs/searchreplace/searchreplace.html', 'map':'~/dialogs/map/map.html', 'gmap':'~/dialogs/gmap/gmap.html', 'insertvideo':'~/dialogs/video/video.html', 'help':'~/dialogs/help/help.html', 'highlightcode':'~/dialogs/code/code.html', 'emotion':'~/dialogs/emotion/emotion.html', 'wordimage':'~/dialogs/wordimage/wordimage.html', 'insertframe':'~/dialogs/insertframe/insertframe.html', 'attachment':'~/dialogs/attachment/attachment.html', 'edittd':'~/dialogs/table/edittd.html', 'snapscreen':'~/dialogs/snapscreen/snapscreen.html' }, listMap: { 'fontfamily': ['宋体', '楷体', '隶书', '黑体','andale mono','arial','arial black','comic sans ms','impact','times new roman'], 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36], 'paragraph': ['p:段落', 'h1:标题 1', 'h2:标题 2', 'h3:标题 3', 'h4:标题 4', 'h5:标题 5', 'h6:标题 6'], 'rowspacing' : ['5', '10', '15', '20', '25'], 'lineheight' : ['1', '1.25','1.5','2', '3', '4', '5'], 'customstyle':[ {tag:'h1', label:'居中标题', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'}, {tag:'h1', label:'居左标题', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'}, {tag:'span', label:'强调', style:'font-style:italic;font-weight:bold;color:#000'}, {tag:'span', label:'明显强调', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'} ] }, fontMap: { '宋体': ['宋体', 'SimSun'], '楷体': ['楷体', '楷体_GB2312', 'SimKai'], '黑体': ['黑体', 'SimHei'], '隶书': ['隶书', 'SimLi'], 'andale mono' : ['andale mono'], 'arial' : ['arial','helvetica','sans-serif'], 'arial black' : ['arial black','avant garde'], 'comic sans ms' : ['comic sans ms'], 'impact' : ['impact','chicago'], 'times new roman' : ['times new roman'] }, initialStyle: '.selectTdClass{background-color:#3399FF !important}'+ 'table{margin-bottom:10px;border-collapse:collapse;}td{padding:2px;}'+ '.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}'+ '.anchorclass{background: url("' + URL + 'themes/default/images/anchor.gif") no-repeat scroll left center transparent;border: 1px dotted #0000FF;cursor: auto;display: inline-block;height: 16px;width: 15px;}' + '.view{padding:0;word-wrap:break-word;word-break:break-all;cursor:text;height:100%;}' + 'body{margin:8px;font-family:"宋体";font-size:16px;}' + 'li{clear:both}' + 'p{margin:.5em 0}', initialContent: '<span style="color:red">欢迎使用ueditor</span>', autoClearinitialContent:false, iframeCssUrl :'themes/default/iframe.css', removeFormatTags : 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var', removeFormatAttributes : 'class,style,lang,width,height,align,hspace,valign', enterTag : 'p', maxUndoCount : 20, maxInputCount : 20, selectedTdClass : 'selectTdClass', pasteplain : true, textarea : 'editorValue', focus : true, indentValue : '2em', pageBreakTag : '_baidu_page_break_tag_', minFrameHeight: 320, autoHeightEnabled:true, autoFloatEnabled: false, elementPathEnabled : true, wordCount:true, maximumWords:10000, tabSize : 4, tabNode : '&nbsp;', imagePopup:true, emotionLocalization:true, sourceEditor: 'codemirror', tdHeight : '20', highlightJsUrl:URL+'third-party/SyntaxHighlighter/shCore.js', highlightCssUrl:URL+'third-party/SyntaxHighlighter/shCoreDefault.css', codeMirrorJsUrl:URL + 'third-party/codemirror2.15/codemirror.js', codeMirrorCssUrl:URL + 'third-party/codemirror2.15/codemirror.css', zIndex : 999, //编辑器z-index的基数 fullscreen : false, //是否上来就是全屏 snapscreenHost: 'localhost', snapscreenServerFile: URL +"server/upload/php/snapImgUp.php", snapscreenServerPort: 80, snapscreenImgAlign: 'center', snapscreenImgIsUseImagePath: 1, messages:{ pasteMsg:'编辑器将过滤掉您粘贴内容中的不支持格式!', wordCountMsg:'当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符 ', wordOverFlowMsg:'你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!', pasteWordImgMsg:'您粘贴的内容中包含本地图片,需要转存后才能正确显示!', snapScreenNotIETip: '截图功能需要在ie浏览器下使用', snapScreenMsg:'截图上传失败,请检查你的PHP环境。 ' }, serialize : function(){ return { blackList: {style:1,script:1,link:1,object:1,applet:1,input:1,meta:1,base:1,button:1,select:1,textarea:1,'#comment':1,'map':1,'area':1} }; }(), ComboxInitial: { FONT_FAMILY: '字体', FONT_SIZE: '字号', PARAGRAPH: '段落格式', CUSTOMSTYLE :'自定义样式' }, autotypeset:{ mergeEmptyline : true, //合并空行 removeClass : true, //去掉冗余的class removeEmptyline : false, //去掉空行 textAlign : "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版 lineHeight : "1", //段内间距 %单位 去掉这个属性表示不执行排版 imageBlockLine : "center", //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版 pasteFilter : false, //根据规则过滤没事粘贴进来的内容 clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号 clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体 removeEmptyNode : false, // 去掉空节点 //可以去掉的标签 removeTagNames : {div:1,a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,"var":1}, indent : false, // 行首缩进 indentValue : "2em" //行首缩进的大小 } }; })();
JavaScript
(function(){UEDITOR_CONFIG = window.UEDITOR_CONFIG || {}; var baidu = window.baidu || {}; window.baidu = baidu; window.UE = baidu.editor = {}; UE.plugins = {}; UE.commands = {}; UE.version = "1.2.0.0"; var dom = UE.dom = {};///import editor.js /** * @class baidu.editor.browser 判断浏览器 */ var browser = UE.browser = function(){ var agent = navigator.userAgent.toLowerCase(), opera = window.opera, browser = { /** * 检测浏览器是否为IE * @name baidu.editor.browser.ie * @property 检测浏览器是否为IE * @grammar baidu.editor.browser.ie * @return {Boolean} 返回是否为ie浏览器 */ ie : !!window.ActiveXObject, /** * 检测浏览器是否为Opera * @name baidu.editor.browser.opera * @property 检测浏览器是否为Opera * @grammar baidu.editor.browser.opera * @return {Boolean} 返回是否为opera浏览器 */ opera : ( !!opera && opera.version ), /** * 检测浏览器是否为WebKit内核 * @name baidu.editor.browser.webkit * @property 检测浏览器是否为WebKit内核 * @grammar baidu.editor.browser.webkit * @return {Boolean} 返回是否为WebKit内核 */ webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ), /** * 检查是否为Macintosh系统 * @name baidu.editor.browser.mac * @property 检查是否为Macintosh系统 * @grammar baidu.editor.browser.mac * @return {Boolean} 返回是否为Macintosh系统 */ mac : ( agent.indexOf( 'macintosh' ) > -1 ), /** * 检查浏览器是否为quirks模式 * @name baidu.editor.browser.quirks * @property 检查浏览器是否为quirks模式 * @grammar baidu.editor.browser.quirks * @return {Boolean} 返回是否为quirks模式 */ quirks : ( document.compatMode == 'BackCompat' ) }; /** * 检测浏览器是否为Gecko内核,如Firefox * @name baidu.editor.browser.gecko * @property 检测浏览器是否为Gecko内核 * @grammar baidu.editor.browser.gecko * @return {Boolean} 返回是否为Gecko内核 */ browser.gecko = ( navigator.product == 'Gecko' && !browser.webkit && !browser.opera ); var version = 0; // Internet Explorer 6.0+ if ( browser.ie ) { version = parseFloat( agent.match( /msie (\d+)/ )[1] ); /** * 检测浏览器是否为 IE8 浏览器 * @name baidu.editor.browser.IE8 * @property 检测浏览器是否为 IE8 浏览器 * @grammar baidu.editor.browser.IE8 * @return {Boolean} 返回是否为 IE8 浏览器 */ browser.ie8 = !!document.documentMode; /** * 检测浏览器是否为 IE8 模式 * @name baidu.editor.browser.ie8Compat * @property 检测浏览器是否为 IE8 模式 * @grammar baidu.editor.browser.ie8Compat * @return {Boolean} 返回是否为 IE8 模式 */ browser.ie8Compat = document.documentMode == 8; /** * 检测浏览器是否运行在 兼容IE7模式 * @name baidu.editor.browser.ie7Compat * @property 检测浏览器是否为兼容IE7模式 * @grammar baidu.editor.browser.ie7Compat * @return {Boolean} 返回是否为兼容IE7模式 */ browser.ie7Compat = ( ( version == 7 && !document.documentMode ) || document.documentMode == 7 ); /** * 检测浏览器是否IE6模式或怪异模式 * @name baidu.editor.browser.ie6Compat * @property 检测浏览器是否IE6 模式或怪异模式 * @grammar baidu.editor.browser.ie6Compat * @return {Boolean} 返回是否为IE6 模式或怪异模式 */ browser.ie6Compat = ( version < 7 || browser.quirks ); } // Gecko. if ( browser.gecko ) { var geckoRelease = agent.match( /rv:([\d\.]+)/ ); if ( geckoRelease ) { geckoRelease = geckoRelease[1].split( '.' ); version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1; } } /** * 检测浏览器是否为chrome * @name baidu.editor.browser.chrome * @property 检测浏览器是否为chrome * @grammar baidu.editor.browser.chrome * @return {Boolean} 返回是否为chrome浏览器 */ if (/chrome\/(\d+\.\d)/i.test(agent)) { browser.chrome = + RegExp['\x241']; } /** * 检测浏览器是否为safari * @name baidu.editor.browser.safari * @property 检测浏览器是否为safari * @grammar baidu.editor.browser.safari * @return {Boolean} 返回是否为safari浏览器 */ if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){ browser.safari = + (RegExp['\x241'] || RegExp['\x242']); } // Opera 9.50+ if ( browser.opera ) version = parseFloat( opera.version() ); // WebKit 522+ (Safari 3+) if ( browser.webkit ) version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] ); /** * 浏览器版本 * * gecko内核浏览器的版本会转换成这样(如 1.9.0.2 -> 10900). * * webkit内核浏览器版本号使用其build号 (如 522). * @name baidu.editor.browser.version * @grammar baidu.editor.browser.version * @return {Boolean} 返回浏览器版本号 * @example * if ( baidu.editor.browser.ie && <b>baidu.editor.browser.version</b> <= 6 ) * alert( "Ouch!" ); */ browser.version = version; /** * 是否是兼容模式的浏览器 * @name baidu.editor.browser.isCompatible * @grammar baidu.editor.browser.isCompatible * @return {Boolean} 返回是否是兼容模式的浏览器 * @example * if ( baidu.editor.browser.isCompatible ) * alert( "Your browser is pretty cool!" ); */ browser.isCompatible = !browser.mobile && ( ( browser.ie && version >= 6 ) || ( browser.gecko && version >= 10801 ) || ( browser.opera && version >= 9.5 ) || ( browser.air && version >= 1 ) || ( browser.webkit && version >= 522 ) || false ); return browser; }(); //快捷方式 var ie = browser.ie, webkit = browser.webkit, gecko = browser.gecko;///import editor.js ///import core/utils.js /** * @class baidu.editor.utils 工具类 */ var utils = UE.utils = /**@lends baidu.editor.utils.prototype*/ { /** * 以obj为原型创建实例 * @public * @function * @param {Object} obj * @return {Object} 返回新的对象 */ makeInstance: function(obj) { var noop = new Function(); noop.prototype = obj; obj = new noop; noop.prototype = null; return obj; }, /** * 将s对象中的属性扩展到t对象上 * @public * @function * @param {Object} t * @param {Object} s * @param {Boolean} b 是否保留已有属性 * @returns {Object} t 返回扩展了s对象属性的t */ extend: function(t, s, b) { if (s) { for (var k in s) { if (!b || ! t.hasOwnProperty(k)) { t[k] = s[k]; } } } return t; }, /** * 判断是否为数组 * @public * @function * @param {Object} array * @return {Boolean} true:为数组,false:不为数组 */ isArray: function(array) { return Object.prototype.toString.apply(array) === '[object Array]' }, /** * 判断是否为字符串 * @public * @function * @param {Object} str * @return {Boolean} true:为字符串。 false:不为字符串 */ isString: function(str) { return typeof str == 'string' || str.constructor == String; }, /** * subClass继承superClass * @public * @function * @param {Object} subClass 子类 * @param {Object} superClass 超类 * @return {Object} 扩展后的新对象 */ inherits: function(subClass, superClass) { var oldP = subClass.prototype, newP = utils.makeInstance(superClass.prototype); utils.extend(newP, oldP, true); subClass.prototype = newP; return (newP.constructor = subClass); }, /** * 为对象绑定函数 * @public * @function * @param {Function} fn 函数 * @param {Object} this_ 对象 * @return {Function} 绑定后的函数 */ bind: function(fn, this_) { return function() { return fn.apply(this_, arguments); }; }, /** * 创建延迟执行的函数 * @public * @function * @param {Function} fn 要执行的函数 * @param {Number} delay 延迟时间,单位为毫秒 * @param {Boolean} exclusion 是否互斥执行,true则执行下一次defer时会先把前一次的延迟函数删除 * @return {Function} 延迟执行的函数 */ defer: function(fn, delay, exclusion) { var timerID; return function() { if (exclusion) { clearTimeout(timerID); } timerID = setTimeout(fn, delay); }; }, /** * 查找元素在数组中的索引, 若找不到返回-1 * @public * @function * @param {Array} array 要查找的数组 * @param {*} item 查找的元素 * @param {Number} at 开始查找的位置 * @returns {Number} 返回在数组中的索引 */ indexOf: function(array, item, at) { for(var i=at||0,l = array.length;i<l;i++){ if(array[i] === item){ return i; } } return -1; }, findNode : function(nodes,tagNames,fn){ for(var i=0,ci;ci=nodes[i++];){ if(fn? fn(ci) : this.indexOf(tagNames,ci.tagName.toLowerCase())!=-1){ return ci; } } }, /** * 移除数组中的元素 * @public * @function * @param {Array} array 要删除元素的数组 * @param {*} item 要删除的元素 */ removeItem: function(array, item) { for(var i=0,l = array.length;i<l;i++){ if(array[i] === item){ array.splice(i,1); i--; } } }, /** * 删除字符串首尾空格 * @public * @function * @param {String} str 字符串 * @return {String} str 删除空格后的字符串 */ trim: function(str) { return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, ''); }, /** * 将字符串转换成hashmap * @public * @function * @param {String/Array} list 字符串,以‘,’隔开 * @returns {Object} 转成hashmap的对象 */ listToMap: function(list) { if(!list)return {}; list = utils.isArray(list) ? list : list.split(','); for(var i=0,ci,obj={};ci=list[i++];){ obj[ci.toUpperCase()] = obj[ci] = 1; } return obj; }, /** * 将str中的html符号转义 * @public * @function * @param {String} str 需要转义的字符串 * @returns {String} 转义后的字符串 */ unhtml: function(str) { return str ? str.replace(/[&<">]/g, function(m){ return { '<': '&lt;', '&': '&amp', '"': '&quot;', '>': '&gt;' }[m] }) : ''; }, /** * 将css样式转换为驼峰的形式。如font-size -> fontSize * @public * @function * @param {String} cssName 需要转换的样式 * @returns {String} 转换后的样式 */ cssStyleToDomStyle: function() { var test = document.createElement('div').style, cache = { 'float': test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat': 'float' }; return function(cssName) { return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function(match){return match.charAt(1).toUpperCase();})); }; }(), /** * 加载css文件,执行回调函数 * @public * @function * @param {document} doc document对象 * @param {String} path 文件路径 * @param {Function} fun 回调函数 * @param {String} id 元素id */ loadFile : function(doc,obj,fun){ if (obj.id && doc.getElementById(obj.id)) { return; } var element = doc.createElement(obj.tag); delete obj.tag; for(var p in obj){ element.setAttribute(p,obj[p]); } element.onload = element.onreadystatechange = function() { if (!this.readyState || /loaded|complete/.test(this.readyState)) { fun && fun(); element.onload = element.onreadystatechange = null; } }; doc.getElementsByTagName("head")[0].appendChild(element); }, /** * 判断对象是否为空 * @param {Object} obj * @return {Boolean} true 空,false 不空 */ isEmptyObject : function(obj){ for ( var p in obj ) { return false; } return true; }, fixColor : function (name, value) { if (/color/i.test(name) && /rgba?/.test(value)) { var array = value.split(","); if (array.length > 3) return ""; value = "#"; for (var i = 0, color; color = array[i++];) { color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16); value += color.length == 1 ? "0" + color : color; } value = value.toUpperCase(); } return value; }, /** * 只针对border,padding,margin做了处理,因为性能问题 * @public * @function * @param {String} val style字符串 */ optCss : function(val){ var padding,margin,border; val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi,function(str,key,name,val){ if(val.split(' ').length == 1){ switch (key){ case 'padding': !padding && (padding = {}); padding[name] = val; return ''; case 'margin': !margin && (margin = {}); margin[name] = val; return ''; case 'border': return val == 'initial' ? '' : str; } } return str }); function opt(obj,name){ if(!obj) return '' var t = obj.top ,b = obj.bottom,l = obj.left,r = obj.right,val = ''; if(!t || !l || !b || !r){ for(var p in obj){ val +=';'+name+'-' + p + ':' + obj[p]+';'; } }else{ val += ';'+name+':' + (t == b && b == l && l == r ? t : t == b && l == r ? (t + ' ' + l) : l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l))+';' } return val; } val += opt(padding,'padding') + opt(margin,'margin'); return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/,'').replace(/;([ \n\r\t]+)|\1;/g,';') .replace(/(&((l|g)t|quot|#39))?;{2,}/g,function(a,b){ return b ? b + ";;" : ';' }) } }; ///import editor.js ///import core/utils.js /** * 事件基础类 * @public * @class * @name baidu.editor.EventBase */ var EventBase = UE.EventBase = function(){}; EventBase.prototype = /**@lends baidu.editor.EventBase.prototype*/{ /** * 注册事件监听器 * @public * @function * @param {String} type 事件名 * @param {Function} listener 监听器数组 */ addListener : function ( type, listener ) { getListener( this, type, true ).push( listener ); }, /** * 移除事件监听器 * @public * @function * @param {String} type 事件名 * @param {Function} listener 监听器数组 */ removeListener : function ( type, listener ) { var listeners = getListener( this, type ); listeners && utils.removeItem( listeners, listener ); }, /** * 触发事件 * @public * @function * @param {String} type 事件名 * */ fireEvent : function ( type ) { var listeners = getListener( this, type ), r, t, k; if ( listeners ) { k = listeners.length; while ( k -- ) { t = listeners[k].apply( this, arguments ); if ( t !== undefined ) { r = t; } } } if ( t = this['on' + type.toLowerCase()] ) { r = t.apply( this, arguments ); } return r; } }; /** * 获得对象所拥有监听类型的所有监听器 * @public * @function * @param {Object} obj 查询监听器的对象 * @param {String} type 事件类型 * @param {Boolean} force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组 * @returns {Array} 监听器数组 */ function getListener( obj, type, force ) { var allListeners; type = type.toLowerCase(); return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) ) && ( allListeners[type] || force && ( allListeners[type] = [] ) ) ); } ///import editor.js ///import core/dom/dom.js /** * dtd html语义化的体现类 * @constructor * @namespace dtd */ var dtd = dom.dtd = (function() { function _( s ) { for (var k in s) { s[k.toUpperCase()] = s[k]; } return s; } function X( t ) { var a = arguments; for ( var i=1; i<a.length; i++ ) { var x = a[i]; for ( var k in x ) { if (!t.hasOwnProperty(k)) { t[k] = x[k]; } } } return t; } var A = _({isindex:1,fieldset:1}), B = _({input:1,button:1,select:1,textarea:1,label:1}), C = X( _({a:1}), B ), D = X( {iframe:1}, C ), E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}), F = _({ins:1,del:1,script:1,style:1}), G = X( _({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ), H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ), I = X( _({p:1}), H ), J = X( _({iframe:1}), H, B ), K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}), L = X( _({a:0}), J ),//a不能被切开,所以把他 M = _({tr:1}), N = _({'#':1}), O = X( _({param:1}), K ), P = X( _({form:1}), A, D, E, I ), Q = _({li:1}), R = _({style:1,script:1}), S = _({base:1,link:1,meta:1,title:1}), T = X( S, R ), U = _({head:1,body:1}), V = _({html:1}); var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}), //针对优酷的embed他添加了结束标识,导致粘贴进来会变成两个,暂时去掉 ,embed:1 empty = _({area:1,base:1,br:1,col:1,hr:1,img:1,input:1,link:1,meta:1,param:1,embed:1}); return _({ // $ 表示自定的属性 // body外的元素列表. $nonBodyContent: X( V, U, S ), //块结构元素列表 $block : block, //内联元素列表 $inline : L, $body : X( _({script:1,style:1}), block ), $cdata : _({script:1,style:1}), //自闭和元素 $empty : empty, //不是自闭合,但不能让range选中里边 $nonChild : _({iframe:1}), //列表元素列表 $listItem : _({dd:1,dt:1,li:1}), //列表根元素列表 $list: _({ul:1,ol:1,dl:1}), //不能认为是空的元素 $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1}), //如果没有子节点就可以删除的元素列表,像span,a $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}), $removeEmptyBlock : _({'p':1,'div':1}), //在table元素里的元素列表 $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}), //不转换的标签 $notTransContent : _({pre:1,script:1,style:1,textarea:1}), html: U, head: T, style: N, script: N, body: P, base: {}, link: {}, meta: {}, title: N, col : {}, tr : _({td:1,th:1}), img : {}, embed: {}, colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}), noscript : P, td : P, br : {}, th : P, center : P, kbd : L, button : X( I, E ), basefont : {}, h5 : L, h4 : L, samp : L, h6 : L, ol : Q, h1 : L, h3 : L, option : N, h2 : L, form : X( A, D, E, I ), select : _({optgroup:1,option:1}), font : L, ins : L, menu : Q, abbr : L, label : L, table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}), code : L, tfoot : M, cite : L, li : P, input : {}, iframe : P, strong : L, textarea : N, noframes : P, big : L, small : L, span :_({'#':1,br:1}), hr : L, dt : L, sub : L, optgroup : _({option:1}), param : {}, bdo : L, 'var' : L, div : P, object : O, sup : L, dd : P, strike : L, area : {}, dir : Q, map : X( _({area:1,form:1,p:1}), A, F, E ), applet : O, dl : _({dt:1,dd:1}), del : L, isindex : {}, fieldset : X( _({legend:1}), K ), thead : M, ul : Q, acronym : L, b : L, a : X( _({a:1}), J ), blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P), caption : L, i : L, u : L, tbody : M, s : L, address : X( D, I ), tt : L, legend : L, q : L, pre : X( G, C ), p : X(_({'a':1}),L), em :L, dfn : L }); })(); ///import editor.js ///import core/utils.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js /** * @class baidu.editor.dom.domUtils dom工具类 */ //for getNextDomNode getPreviousDomNode function getDomNode(node, start, ltr, startFromChild, fn, guard) { var tmpNode = startFromChild && node[start], parent; !tmpNode && (tmpNode = node[ltr]); while (!tmpNode && (parent = (parent || node).parentNode)) { if (parent.tagName == 'BODY' || guard && !guard(parent)) return null; tmpNode = parent[ltr]; } if (tmpNode && fn && !fn(tmpNode)) { return getDomNode(tmpNode, start, ltr, false, fn) } return tmpNode; } var attrFix = ie && browser.version < 9 ? { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder" } : { tabindex: "tabIndex", readonly: "readOnly" }, styleBlock = utils.listToMap([ '-webkit-box','-moz-box','block' , 'list-item' ,'table' ,'table-row-group' , 'table-header-group','table-footer-group' , 'table-row' ,'table-column-group' ,'table-column' , 'table-cell' ,'table-caption' ]); var domUtils = dom.domUtils = { //节点常量 NODE_ELEMENT : 1, NODE_DOCUMENT : 9, NODE_TEXT : 3, NODE_COMMENT : 8, NODE_DOCUMENT_FRAGMENT : 11, //位置关系 POSITION_IDENTICAL : 0, POSITION_DISCONNECTED : 1, POSITION_FOLLOWING : 2, POSITION_PRECEDING : 4, POSITION_IS_CONTAINED : 8, POSITION_CONTAINS : 16, //ie6使用其他的会有一段空白出现 fillChar : ie && browser.version == '6' ? '\ufeff' : '\u200B', //-------------------------Node部分-------------------------------- keys : { /*Backspace*/ 8:1, /*Delete*/ 46:1, /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1, 37:1, 38:1, 39:1, 40:1, 13:1 /*enter*/ }, /** * 获取两个节点的位置关系 * @function * @param {Node} nodeA 节点A * @param {Node} nodeB 节点B * @returns {Number} 返回位置关系 */ getPosition : function (nodeA, nodeB) { // 如果两个节点是同一个节点 if (nodeA === nodeB) { // domUtils.POSITION_IDENTICAL return 0; } var node, parentsA = [nodeA], parentsB = [nodeB]; node = nodeA; while (node = node.parentNode) { // 如果nodeB是nodeA的祖先节点 if (node === nodeB) { // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING return 10; } parentsA.push(node); } node = nodeB; while (node = node.parentNode) { // 如果nodeA是nodeB的祖先节点 if (node === nodeA) { // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING return 20; } parentsB.push(node); } parentsA.reverse(); parentsB.reverse(); if (parentsA[0] !== parentsB[0]) // domUtils.POSITION_DISCONNECTED return 1; var i = -1; while (i++,parentsA[i] === parentsB[i]) ; nodeA = parentsA[i]; nodeB = parentsB[i]; while (nodeA = nodeA.nextSibling) { if (nodeA === nodeB) { // domUtils.POSITION_PRECEDING return 4 } } // domUtils.POSITION_FOLLOWING return 2; }, /** * 返回节点索引,zero-based * @function * @param {Node} node 节点 * @returns {Number} 节点的索引 */ getNodeIndex : function (node) { var child = node.parentNode.firstChild,i = 0; while(node!==child){ i++; child = child.nextSibling; } return i; }, /** * 判断节点是否在树上 * @param node */ inDoc: function (node, doc){ while (node = node.parentNode) { if (node === doc) { return true; } } return false; }, /** * 查找祖先节点 * @function * @param {Node} node 节点 * @param {Function} tester 以函数为规律 * @param {Boolean} includeSelf 包含自己 * @returns {Node} 返回祖先节点 */ findParent : function (node, tester, includeSelf) { if (!domUtils.isBody(node)) { node = includeSelf ? node : node.parentNode; while (node) { if (!tester || tester(node) || this.isBody(node)) { return tester && !tester(node) && this.isBody(node) ? null : node; } node = node.parentNode; } } return null; }, /** * 查找祖先节点 * @function * @param {Node} node 节点 * @param {String} tagName 标签名称 * @param {Boolean} includeSelf 包含自己 * @returns {Node} 返回祖先节点 */ findParentByTagName : function(node, tagName, includeSelf,excludeFn) { if (node && node.nodeType && !this.isBody(node) && (node.nodeType == 1 || node.nodeType)) { tagName = utils.listToMap(utils.isArray(tagName) ? tagName : [tagName]); node = node.nodeType == 3 || !includeSelf ? node.parentNode : node; while (node && node.tagName && node.nodeType != 9) { if(excludeFn && excludeFn(node)) break; if (tagName[node.tagName]) return node; node = node.parentNode; } } return null; }, /** * 查找祖先节点集合 * @param {Node} node 节点 * @param {Function} tester 函数 * @param {Boolean} includeSelf 是否从自身开始找 * @param {Boolean} closerFirst * @returns {Array} 祖先节点集合 */ findParents: function (node, includeSelf, tester, closerFirst) { var parents = includeSelf && ( tester && tester(node) || !tester ) ? [node] : []; while (node = domUtils.findParent(node, tester)) { parents.push(node); } return closerFirst ? parents : parents.reverse(); }, /** * 往后插入节点 * @function * @param {Node} node 基准节点 * @param {Node} nodeToInsert 要插入的节点 * @return {Node} 返回node */ insertAfter : function (node, nodeToInsert) { return node.parentNode.insertBefore(nodeToInsert, node.nextSibling); }, /** * 删除该节点 * @function * @param {Node} node 要删除的节点 * @param {Boolean} keepChildren 是否保留子节点不删除 * @return {Node} 返回要删除的节点 */ remove : function (node, keepChildren) { var parent = node.parentNode, child; if (parent) { if (keepChildren && node.hasChildNodes()) { while (child = node.firstChild) { parent.insertBefore(child, node); } } parent.removeChild(node); } return node; }, /** * 取得node节点在dom树上的下一个节点 * @function * @param {Node} node 节点 * @param {Boolean} startFromChild 为true从子节点开始找 * @param {Function} fn fn为真的节点 * @return {Node} 返回下一个节点 */ getNextDomNode : function(node, startFromChild, filter, guard) { return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filter, guard); }, /** * 是bookmark节点 * @param {Node} node 判断是否为书签节点 * @return {Boolean} 返回是否为书签节点 */ isBookmarkNode : function(node) { return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id); }, /** * 获取节点所在window对象 * @param {Node} node 节点 * @return {window} 返回window对象 */ getWindow : function (node) { var doc = node.ownerDocument || node; return doc.defaultView || doc.parentWindow; }, /** * 得到公共的祖先节点 * @param {Node} nodeA 节点A * @param {Node} nodeB 节点B * @return {Node} nodeA和nodeB的公共节点 */ getCommonAncestor : function(nodeA, nodeB) { if (nodeA === nodeB) return nodeA; var parentsA = [nodeA] ,parentsB = [nodeB], parent = nodeA, i = -1; while (parent = parent.parentNode) { if (parent === nodeB) return parent; parentsA.push(parent) } parent = nodeB; while (parent = parent.parentNode) { if (parent === nodeA) return parent; parentsB.push(parent) } parentsA.reverse(); parentsB.reverse(); while (i++,parentsA[i] === parentsB[i]); return i == 0 ? null : parentsA[i - 1]; }, /** * 清除该节点左右空的inline节点 * @function * @param {Node} node * @param {Boolean} ingoreNext 默认为false清除右边为空的inline节点。true为不清除右边为空的inline节点 * @param {Boolean} ingorePre 默认为false清除左边为空的inline节点。true为不清除左边为空的inline节点 * @exmaple <b></b><i></i>xxxx<b>bb</b> --> xxxx<b>bb</b> */ clearEmptySibling : function(node, ingoreNext, ingorePre) { function clear(next, dir) { var tmpNode; while(next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next) || domUtils.isWhitespace(next) )){ tmpNode = next[dir]; domUtils.remove(next); next = tmpNode; } } !ingoreNext && clear(node.nextSibling, 'nextSibling'); !ingorePre && clear(node.previousSibling, 'previousSibling'); }, //---------------------------Text---------------------------------- /** * 将一个文本节点拆分成两个文本节点 * @param {TextNode} node 文本节点 * @param {Integer} offset 拆分的位置 * @return {TextNode} 拆分后的后一个文本节 */ split: function (node, offset) { var doc = node.ownerDocument; if (browser.ie && offset == node.nodeValue.length) { var next = doc.createTextNode(''); return domUtils.insertAfter(node, next); } var retval = node.splitText(offset); //ie8下splitText不会跟新childNodes,我们手动触发他的更新 if (browser.ie8) { var tmpNode = doc.createTextNode(''); domUtils.insertAfter(retval, tmpNode); domUtils.remove(tmpNode); } return retval; }, /** * 判断是否为空白节点 * @param {TextNode} node 节点 * @return {Boolean} 返回是否为文本节点 */ isWhitespace : function(node) { return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue); }, //------------------------------Element------------------------------------------- /** * 获取元素相对于viewport的像素坐标 * @param {Element} element 元素 * @returns {Object} 返回坐标对象{x:left,y:top} */ getXY : function (element) { var x = 0,y = 0; while (element.offsetParent) { y += element.offsetTop; x += element.offsetLeft; element = element.offsetParent; } return { 'x': x, 'y': y }; }, /** * 绑原生DOM事件 * @param {Element|Window|Document} target 元素 * @param {Array|String} type 事件类型 * @param {Function} handler 执行函数 */ on : function (obj, type, handler) { var types = type instanceof Array ? type : [type], k = types.length; if (k) while (k --) { type = types[k]; if (obj.addEventListener) { obj.addEventListener(type, handler, false); } else { if(!handler._d) handler._d ={}; var key = type+handler.toString(); if(!handler._d[key]){ handler._d[key] = function(evt) { return handler.call(evt.srcElement, evt || window.event); }; obj.attachEvent('on' + type,handler._d[key]); } } } obj = null; }, /** * 解除原生DOM事件绑定 * @param {Element|Window|Document} obj 元素 * @param {Array|String} type 事件类型 * @param {Function} handler 执行函数 */ un : function (obj, type, handler) { var types = type instanceof Array ? type : [type], k = types.length; if (k) while (k --) { type = types[k]; if (obj.removeEventListener) { obj.removeEventListener(type, handler, false); } else { var key = type+handler.toString(); obj.detachEvent('on' + type, handler._d ? handler._d[key] : handler); if(handler._d && handler._d[key]){ delete handler._d[key]; } } } }, /** * 比较两个节点是否tagName相同且有相同的属性和属性值 * @param {Element} nodeA 节点A * @param {Element} nodeB 节点B * @return {Boolean} 返回两个节点的标签,属性和属性值是否相同 * @example * &lt;span style="font-size:12px"&gt;ssss&lt;/span&gt;和&lt;span style="font-size:12px"&gt;bbbbb&lt;/span&gt; 相等 * &lt;span style="font-size:13px"&gt;ssss&lt;/span&gt;和&lt;span style="font-size:12px"&gt;bbbbb&lt;/span&gt; 不相等 */ isSameElement : function(nodeA, nodeB) { if (nodeA.tagName != nodeB.tagName) return 0; var thisAttribs = nodeA.attributes, otherAttribs = nodeB.attributes; if (!ie && thisAttribs.length != otherAttribs.length) return 0; var attrA,attrB,al = 0,bl=0; for(var i= 0;attrA=thisAttribs[i++];){ if(attrA.nodeName == 'style' ){ if(attrA.specified)al++; if(domUtils.isSameStyle(nodeA,nodeB)){ continue }else{ return 0; } } if(ie){ if(attrA.specified){ al++; attrB = otherAttribs.getNamedItem(attrA.nodeName); }else{ continue; } }else{ attrB = nodeB.attributes[attrA.nodeName]; } if(!attrB.specified)return 0; if(attrA.nodeValue != attrB.nodeValue) return 0; } // 有可能attrB的属性包含了attrA的属性之外还有自己的属性 if(ie){ for(i=0;attrB = otherAttribs[i++];){ if(attrB.specified){ bl++; } } if(al!=bl) return 0; } return 1; }, /** * 判断两个元素的style属性是不是一致 * @param {Element} elementA 元素A * @param {Element} elementB 元素B * @return {boolean} 返回判断结果,true为一致 */ isSameStyle : function (elementA, elementB) { var styleA = elementA.style.cssText.replace(/( ?; ?)/g,';').replace(/( ?: ?)/g,':'), styleB = elementB.style.cssText.replace(/( ?; ?)/g,';').replace(/( ?: ?)/g,':'); if(!styleA || !styleB){ return styleA == styleB ? 1: 0; } styleA = styleA.split(';'); styleB = styleB.split(';'); if(styleA.length != styleB.length) return 0; for(var i = 0,ci;ci=styleA[i++];){ if(utils.indexOf(styleB,ci) == -1) return 0 } return 1; }, /** * 检查是否为块元素 * @function * @param {Element} node 元素 * @param {String} customNodeNames 自定义的块元素的tagName * @return {Boolean} 是否为块元素 */ isBlockElm : function (node) { return node.nodeType == 1 && (dtd.$block[node.tagName]||styleBlock[domUtils.getComputedStyle(node,'display')])&& !dtd.$nonChild[node.tagName]; }, /** * 判断是否body * @param {Node} 节点 * @return {Boolean} 是否是body节点 */ isBody : function(node) { return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body'; }, /** * 以node节点为中心,将该节点的父节点拆分成2块 * @param {Element} node 节点 * @param {Element} parent 要被拆分的父节点 * @example <div>xxxx<b>xxx</b>xxx</div> ==> <div>xxx</div><b>xx</b><div>xxx</div> */ breakParent : function(node, parent) { var tmpNode, parentClone = node, clone = node, leftNodes, rightNodes; do { parentClone = parentClone.parentNode; if (leftNodes) { tmpNode = parentClone.cloneNode(false); tmpNode.appendChild(leftNodes); leftNodes = tmpNode; tmpNode = parentClone.cloneNode(false); tmpNode.appendChild(rightNodes); rightNodes = tmpNode; } else { leftNodes = parentClone.cloneNode(false); rightNodes = leftNodes.cloneNode(false); } while (tmpNode = clone.previousSibling) { leftNodes.insertBefore(tmpNode, leftNodes.firstChild); } while (tmpNode = clone.nextSibling) { rightNodes.appendChild(tmpNode); } clone = parentClone; } while (parent !== parentClone); tmpNode = parent.parentNode; tmpNode.insertBefore(leftNodes, parent); tmpNode.insertBefore(rightNodes, parent); tmpNode.insertBefore(node, rightNodes); domUtils.remove(parent); return node; }, /** * 检查是否是空inline节点 * @param {Node} node 节点 * @return {Boolean} 返回1为是,0为否 * @example * &lt;b&gt;&lt;i&gt;&lt;/i&gt;&lt;/b&gt; //true * <b><i></i><u></u></b> true * &lt;b&gt;&lt;/b&gt; true &lt;b&gt;xx&lt;i&gt;&lt;/i&gt;&lt;/b&gt; //false */ isEmptyInlineElement : function(node) { if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) return 0; node = node.firstChild; while (node) { //如果是创建的bookmark就跳过 if (domUtils.isBookmarkNode(node)) return 0; if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) || node.nodeType == 3 && !domUtils.isWhitespace(node) ) { return 0; } node = node.nextSibling; } return 1; }, /** * 删除空白子节点 * @param {Element} node 需要删除空白子节点的元素 */ trimWhiteTextNode : function(node) { function remove(dir) { var child; while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) node.removeChild(child) } remove('firstChild'); remove('lastChild'); }, /** * 合并子节点 * @param {Node} node 节点 * @param {String} tagName 标签 * @param {String} attrs 属性 * @example &lt;span style="font-size:12px;"&gt;xx&lt;span style="font-size:12px;"&gt;aa&lt;/span&gt;xx&lt;/span 使用后 * &lt;span style="font-size:12px;"&gt;xxaaxx&lt;/span */ mergChild : function(node, tagName, attrs) { var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase()); for (var i = 0,ci; ci = list[i++];) { if (!ci.parentNode || domUtils.isBookmarkNode(ci)) continue; //span单独处理 if (ci.tagName.toLowerCase() == 'span') { if (node === ci.parentNode) { domUtils.trimWhiteTextNode(node); if (node.childNodes.length == 1) { node.style.cssText = ci.style.cssText + ";" + node.style.cssText; domUtils.remove(ci, true); continue; } } ci.style.cssText = node.style.cssText + ';' + ci.style.cssText; if (attrs) { var style = attrs.style; if (style) { style = style.split(';'); for (var j = 0,s; s = style[j++];) { ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1]; } } } if (domUtils.isSameStyle(ci, node)) { domUtils.remove(ci, true) } continue; } if (domUtils.isSameElement(node, ci)) { domUtils.remove(ci, true); } } if (tagName == 'span') { var as = domUtils.getElementsByTagName(node, 'a'); for (var i = 0,ai; ai = as[i++];) { ai.style.cssText = ';' + node.style.cssText; ai.style.textDecoration = 'underline'; } } }, /** * 封装原生的getElemensByTagName * @param {Node} node 根节点 * @param {String} name 标签的tagName * @return {Array} 返回符合条件的元素数组 */ getElementsByTagName : function(node, name) { var list = node.getElementsByTagName(name),arr = []; for (var i = 0,ci; ci = list[i++];) { arr.push(ci) } return arr; }, /** * 将子节点合并到父节点上 * @param {Element} node 节点 * @example &lt;span style="color:#ff"&gt;&lt;span style="font-size:12px"&gt;xxx&lt;/span&gt;&lt;/span&gt; ==&gt; &lt;span style="color:#ff;font-size:12px"&gt;xxx&lt;/span&gt; */ mergToParent : function(node) { var parent = node.parentNode; while (parent && dtd.$removeEmpty[parent.tagName]) { if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理 domUtils.trimWhiteTextNode(parent); //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span> if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node) || (parent.tagName == 'A' && node.tagName == 'SPAN')) { if (parent.childNodes.length > 1 || parent !== node.parentNode) { node.style.cssText = parent.style.cssText + ";" + node.style.cssText; parent = parent.parentNode; continue; } else { parent.style.cssText += ";" + node.style.cssText; //trace:952 a标签要保持下划线 if (parent.tagName == 'A') { parent.style.textDecoration = 'underline'; } } } if(parent.tagName != 'A' ){ parent === node.parentNode && domUtils.remove(node, true); break; } } parent = parent.parentNode; } }, /** * 合并左右兄弟节点 * @function * @param {Node} node * @param {Boolean} ingoreNext 默认为false合并上一个兄弟节点。true为不合并上一个兄弟节点 * @param {Boolean} ingorePre 默认为false合并下一个兄弟节点。true为不合并下一个兄弟节点 * @example &lt;b&gt;xxxx&lt;/b&gt;&lt;b&gt;xxx&lt;/b&gt;&lt;b&gt;xxxx&lt;/b&gt; ==> &lt;b&gt;xxxxxxxxxxx&lt;/b&gt; */ mergSibling : function(node, ingorePre, ingoreNext) { function merg(rtl, start, node) { var next; if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) { while (next.firstChild) { if (start == 'firstChild') { node.insertBefore(next.lastChild, node.firstChild); } else { node.appendChild(next.firstChild) } } domUtils.remove(next); } } !ingorePre && merg('previousSibling', 'firstChild', node); !ingoreNext && merg('nextSibling', 'lastChild', node); }, /** * 使得元素及其子节点不能被选择 * @function * @param {Node} node 节点 */ unselectable : gecko ? function(node) { node.style.MozUserSelect = 'none'; } : webkit ? function(node) { node.style.KhtmlUserSelect = 'none'; } : function(node) { //for ie9 node.onselectstart = function () { return false; }; node.onclick = node.onkeyup = node.onkeydown = function(){return false}; node.unselectable = 'on'; node.setAttribute("unselectable","on"); for (var i = 0,ci; ci = node.all[i++];) { switch (ci.tagName.toLowerCase()) { case 'iframe' : case 'textarea' : case 'input' : case 'select' : break; default : ci.unselectable = 'on'; node.setAttribute("unselectable","on"); } } }, /** * 删除元素上的属性,可以删除多个 * @function * @param {Element} element 元素 * @param {Array} attrNames 要删除的属性数组 */ removeAttributes : function (elm, attrNames) { for(var i = 0,ci;ci=attrNames[i++];){ ci = attrFix[ci] || ci; switch (ci){ case 'className': elm[ci] = ''; break; case 'style': elm.style.cssText = ''; !browser.ie && elm.removeAttributeNode(elm.getAttributeNode('style')) } elm.removeAttribute(ci); } }, /** * 给节点添加属性 * @function * @param {Node} node 节点 * @param {Object} attrNames 要添加的属性名称,采用json对象存放 */ setAttributes : function(node, attrs) { for (var name in attrs) { var value = attrs[name]; switch (name) { case 'class': //ie下要这样赋值,setAttribute不起作用 node.className = value; break; case 'style' : node.style.cssText = node.style.cssText + ";" + value; break; case 'innerHTML': node[name] = value; break; case 'value': node.value = value; break; default: node.setAttribute(attrFix[name]||name, value); } } return node; }, /** * 获取元素的样式 * @function * @param {Element} element 元素 * @param {String} styleName 样式名称 * @return {String} 样式值 */ getComputedStyle : function (element, styleName) { function fixUnit(key, val) { if (key == 'font-size' && /pt$/.test(val)) { val = Math.round(parseFloat(val) / 0.75) + 'px'; } return val; } if(element.nodeType == 3){ element = element.parentNode; } //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize && !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) { var span = element.ownerDocument.createElement('span'); span.style.cssText = 'padding:0;border:0;font-family:simsun;'; span.innerHTML = '.'; element.appendChild(span); var result = span.offsetHeight; element.removeChild(span); span = null; return result + 'px'; } try { var value = domUtils.getStyle(element, styleName) || (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) : ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]); } catch(e) { return null; } return fixUnit(styleName, utils.fixColor(styleName, value)); }, /** * 删除cssClass,可以支持删除多个class,需以空格分隔 * @param {Element} element 元素 * @param {Array} classNames 删除的className */ removeClasses : function (element, classNames) { element.className = (' ' + element.className + ' ').replace( new RegExp('(?:\\s+(?:' + classNames.join('|') + '))+\\s+', 'g'), ' '); }, /** * 删除元素的样式 * @param {Element} element元素 * @param {String} name 删除的样式名称 */ removeStyle : function(node, name) { node.style[utils.cssStyleToDomStyle(name)] = ''; if(!node.style.cssText) domUtils.removeAttributes(node,['style']) }, /** * 判断元素属性中是否包含某一个classname * @param {Element} element 元素 * @param {String} className 样式名 * @returns {Boolean} 是否包含该classname */ hasClass : function (element, className) { return ( ' ' + element.className + ' ' ).indexOf(' ' + className + ' ') > -1; }, /** * 阻止事件默认行为 * @param {Event} evt 需要组织的事件对象 */ preventDefault : function (evt) { evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); }, /** * 获得元素样式 * @param {Element} element 元素 * @param {String} name 样式名称 * @return {String} 返回元素样式值 */ getStyle : function(element, name) { var value = element.style[ utils.cssStyleToDomStyle(name) ]; return utils.fixColor(name, value); }, setStyle: function (element, name, value) { element.style[utils.cssStyleToDomStyle(name)] = value; }, setStyles: function (element, styles) { for (var name in styles) { if (styles.hasOwnProperty(name)) { domUtils.setStyle(element, name, styles[name]); } } }, /** * 删除_moz_dirty属性 * @function * @param {Node} node 节点 */ removeDirtyAttr : function(node) { for (var i = 0,ci,nodes = node.getElementsByTagName('*'); ci = nodes[i++];) { ci.removeAttribute('_moz_dirty') } node.removeAttribute('_moz_dirty') }, /** * 返回子节点的数量 * @function * @param {Node} node 父节点 * @param {Function} fn 过滤子节点的规则,若为空,则得到所有子节点的数量 * @return {Number} 符合条件子节点的数量 */ getChildCount : function (node, fn) { var count = 0,first = node.firstChild; fn = fn || function() { return 1 }; while (first) { if (fn(first)) count++; first = first.nextSibling; } return count; }, /** * 判断是否为空节点 * @function * @param {Node} node 节点 * @return {Boolean} 是否为空节点 */ isEmptyNode : function(node) { return !node.firstChild || domUtils.getChildCount(node, function(node) { return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node) }) == 0 }, /** * 清空节点所有的className * @function * @param {Array} nodes 节点数组 */ clearSelectedArr : function(nodes) { var node; while(node = nodes.pop()){ domUtils.removeAttributes(node,['class']); } }, /** * 将显示区域滚动到显示节点的位置 * @function * @param {Node} node 节点 * @param {window} win window对象 * @param {Number} offsetTop 距离上方的偏移量 */ scrollToView : function(node, win, offsetTop) { var getViewPaneSize = function() { var doc = win.document, mode = doc.compatMode == 'CSS1Compat'; return { width : ( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0, height : ( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0 }; }, getScrollPosition = function(win) { if ('pageXOffset' in win) { return { x : win.pageXOffset || 0, y : win.pageYOffset || 0 }; } else { var doc = win.document; return { x : doc.documentElement.scrollLeft || doc.body.scrollLeft || 0, y : doc.documentElement.scrollTop || doc.body.scrollTop || 0 }; } }; var winHeight = getViewPaneSize().height,offset = winHeight * -1 + offsetTop; offset += (node.offsetHeight || 0); var elementPosition = domUtils.getXY(node); offset += elementPosition.y; var currentScroll = getScrollPosition(win).y; // offset += 50; if (offset > currentScroll || offset < currentScroll - winHeight) win.scrollTo(0, offset + (offset < 0 ? -20 : 20)); }, /** * 判断节点是否为br * @function * @param {Node} node 节点 */ isBr : function(node) { return node.nodeType == 1 && node.tagName == 'BR'; }, isFillChar : function(node){ return node.nodeType == 3 && !node.nodeValue.replace(new RegExp( domUtils.fillChar ),'').length }, isStartInblock : function(range){ var tmpRange = range.cloneRange(), flag = 0, start = tmpRange.startContainer, tmp; while(start && domUtils.isFillChar(start)){ tmp = start; start = start.previousSibling } if(tmp){ tmpRange.setStartBefore(tmp); start = tmpRange.startContainer; } if(start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1){ tmpRange.setStart(start,0).collapse(true); } while(!tmpRange.startOffset){ start = tmpRange.startContainer; if(domUtils.isBlockElm(start)||domUtils.isBody(start)){ flag = 1; break; } var pre = tmpRange.startContainer.previousSibling, tmpNode; if(!pre){ tmpRange.setStartBefore(tmpRange.startContainer); }else{ while(pre && domUtils.isFillChar(pre)){ tmpNode = pre; pre = pre.previousSibling; } if(tmpNode){ tmpRange.setStartBefore(tmpNode); }else tmpRange.setStartBefore(tmpRange.startContainer); } } return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0; }, isEmptyBlock : function(node){ var reg = new RegExp( '[ \t\r\n' + domUtils.fillChar+']', 'g' ); if(node[browser.ie?'innerText':'textContent'].replace(reg,'').length >0) return 0; for(var n in dtd.$isNotEmpty){ if(node.getElementsByTagName(n).length) return 0; } return 1; }, setViewportOffset: function (element, offset){ var left = parseInt(element.style.left) | 0; var top = parseInt(element.style.top) | 0; var rect = element.getBoundingClientRect(); var offsetLeft = offset.left - rect.left; var offsetTop = offset.top - rect.top; if (offsetLeft) { element.style.left = left + offsetLeft + 'px'; } if (offsetTop) { element.style.top = top + offsetTop + 'px'; } }, fillNode : function(doc,node){ var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br'); node.innerHTML = ''; node.appendChild(tmpNode); }, moveChild : function(src,tag,dir){ while(src.firstChild){ if(dir && tag.firstChild){ tag.insertBefore(src.lastChild,tag.firstChild); }else{ tag.appendChild(src.firstChild) } } }, //判断是否有额外属性 hasNoAttributes : function(node){ return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) :node.attributes.length == 0; } }; var fillCharReg = new RegExp( domUtils.fillChar, 'g' );///import editor.js ///import core/utils.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/dom/domUtils.js /** * @class baidu.editor.dom.Range Range类 */ /** * @description Range类实现 * @author zhanyi */ (function() { var guid = 0, fillChar = domUtils.fillChar, fillData; /** * 更新range的collapse状态 * @param {Range} range range对象 */ function updateCollapse( range ) { range.collapsed = range.startContainer && range.endContainer && range.startContainer === range.endContainer && range.startOffset == range.endOffset; } function setEndPoint( toStart, node, offset, range ) { //如果node是自闭合标签要处理 if ( node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) { offset = domUtils.getNodeIndex( node ) + (toStart ? 0 : 1); node = node.parentNode; } if ( toStart ) { range.startContainer = node; range.startOffset = offset; if ( !range.endContainer ) { range.collapse( true ); } } else { range.endContainer = node; range.endOffset = offset; if ( !range.startContainer ) { range.collapse( false ); } } updateCollapse( range ); return range; } function execContentsAction ( range, action ) { //调整边界 //range.includeBookmark(); var start = range.startContainer, end = range.endContainer, startOffset = range.startOffset, endOffset = range.endOffset, doc = range.document, frag = doc.createDocumentFragment(), tmpStart,tmpEnd; if ( start.nodeType == 1 ) { start = start.childNodes[startOffset] || (tmpStart = start.appendChild( doc.createTextNode( '' ) )); } if ( end.nodeType == 1 ) { end = end.childNodes[endOffset] || (tmpEnd = end.appendChild( doc.createTextNode( '' ) )); } if ( start === end && start.nodeType == 3 ) { frag.appendChild( doc.createTextNode( start.substringData( startOffset, endOffset - startOffset ) ) ); //is not clone if ( action ) { start.deleteData( startOffset, endOffset - startOffset ); range.collapse( true ); } return frag; } var current,currentLevel,clone = frag, startParents = domUtils.findParents( start, true ),endParents = domUtils.findParents( end, true ); for ( var i = 0; startParents[i] == endParents[i]; i++ ); for ( var j = i,si; si = startParents[j]; j++ ) { current = si.nextSibling; if ( si == start ) { if ( !tmpStart ) { if ( range.startContainer.nodeType == 3 ) { clone.appendChild( doc.createTextNode( start.nodeValue.slice( startOffset ) ) ); //is not clone if ( action ) { start.deleteData( startOffset, start.nodeValue.length - startOffset ); } } else { clone.appendChild( !action ? start.cloneNode( true ) : start ); } } } else { currentLevel = si.cloneNode( false ); clone.appendChild( currentLevel ); } while ( current ) { if ( current === end || current === endParents[j] )break; si = current.nextSibling; clone.appendChild( !action ? current.cloneNode( true ) : current ); current = si; } clone = currentLevel; } clone = frag; if ( !startParents[i] ) { clone.appendChild( startParents[i - 1].cloneNode( false ) ); clone = clone.firstChild; } for ( var j = i,ei; ei = endParents[j]; j++ ) { current = ei.previousSibling; if ( ei == end ) { if ( !tmpEnd && range.endContainer.nodeType == 3 ) { clone.appendChild( doc.createTextNode( end.substringData( 0, endOffset ) ) ); //is not clone if ( action ) { end.deleteData( 0, endOffset ); } } } else { currentLevel = ei.cloneNode( false ); clone.appendChild( currentLevel ); } //如果两端同级,右边第一次已经被开始做了 if ( j != i || !startParents[i] ) { while ( current ) { if ( current === start )break; ei = current.previousSibling; clone.insertBefore( !action ? current.cloneNode( true ) : current, clone.firstChild ); current = ei; } } clone = currentLevel; } if ( action ) { range.setStartBefore( !endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i] ).collapse( true ) } tmpStart && domUtils.remove( tmpStart ); tmpEnd && domUtils.remove( tmpEnd ); return frag; } /** * Range类 * @param {Document} document 编辑器页面document对象 */ var Range = dom.Range = function( document ) { var me = this; me.startContainer = me.startOffset = me.endContainer = me.endOffset = null; me.document = document; me.collapsed = true; }; function removeFillData(doc,excludeNode){ try{ if ( fillData && domUtils.inDoc(fillData,doc) ) { if(!fillData.nodeValue.replace( fillCharReg, '' ).length){ var tmpNode = fillData.parentNode; domUtils.remove(fillData); while(tmpNode && domUtils.isEmptyInlineElement(tmpNode) && !tmpNode.contains(excludeNode)){ fillData = tmpNode.parentNode; domUtils.remove(tmpNode); tmpNode = fillData } }else fillData.nodeValue = fillData.nodeValue.replace( fillCharReg, '' ) } }catch(e){} } function mergSibling(node,dir){ var tmpNode; node = node[dir]; while(node && domUtils.isFillChar(node)){ tmpNode = node[dir]; domUtils.remove(node); node = tmpNode; } } Range.prototype = { /** * 克隆选中的内容到一个fragment里 * @public * @function * @name baidu.editor.dom.Range.cloneContents * @return {Fragment} frag|null 返回选中内容的文本片段或者空 */ cloneContents : function() { return this.collapsed ? null : execContentsAction( this, 0 ); }, /** * 删除所选内容 * @public * @function * @name baidu.editor.dom.Range.deleteContents * @return {Range} 删除选中内容后的Range */ deleteContents : function() { if ( !this.collapsed ) execContentsAction( this, 1 ); if(browser.webkit){ var txt = this.startContainer; if(txt.nodeType == 3 && !txt.nodeValue.length){ this.setStartBefore(txt).collapse(true); domUtils.remove(txt) } } return this; }, /** * 取出内容 * @public * @function * @name baidu.editor.dom.Range.extractContents * @return {String} 获得Range选中的内容 */ extractContents : function() { return this.collapsed ? null : execContentsAction( this, 2 ); }, /** * 设置range的开始位置 * @public * @function * @name baidu.editor.dom.Range.setStart * @param {Node} node range开始节点 * @param {Number} offset 偏移量 * @return {Range} 返回Range */ setStart : function( node, offset ) { return setEndPoint( true, node, offset, this ); }, /** * 设置range结束点的位置 * @public * @function * @name baidu.editor.dom.Range.setEnd * @param {Node} node range结束节点 * @param {Number} offset 偏移量 * @return {Range} 返回Range */ setEnd : function( node, offset ) { return setEndPoint( false, node, offset, this ); }, /** * 将开始位置设置到node后 * @public * @function * @name baidu.editor.dom.Range.setStartAfter * @param {Node} node 节点 * @return {Range} 返回Range */ setStartAfter : function( node ) { return this.setStart( node.parentNode, domUtils.getNodeIndex( node ) + 1 ); }, /** * 将开始位置设置到node前 * @public * @function * @name baidu.editor.dom.Range.setStartBefore * @param {Node} node 节点 * @return {Range} 返回Range */ setStartBefore : function( node ) { return this.setStart( node.parentNode, domUtils.getNodeIndex( node ) ); }, /** * 将结束点位置设置到node后 * @public * @function * @name baidu.editor.dom.Range.setEndAfter * @param {Node} node 节点 * @return {Range} 返回Range */ setEndAfter : function( node ) { return this.setEnd( node.parentNode, domUtils.getNodeIndex( node ) + 1 ); }, /** * 将结束点位置设置到node前 * @public * @function * @name baidu.editor.dom.Range.setEndBefore * @param {Node} node 节点 * @return {Range} 返回Range */ setEndBefore : function( node ) { return this.setEnd( node.parentNode, domUtils.getNodeIndex( node ) ); }, /** * 选中指定节点 * @public * @function * @name baidu.editor.dom.Range.selectNode * @param {Node} node 节点 * @return {Range} 返回Range */ selectNode : function( node ) { return this.setStartBefore( node ).setEndAfter( node ); }, /** * 选中node下的所有节点 * @public * @function * @name baidu.editor.dom.Range.selectNodeContents * @param {Element} node 要设置的节点 * @return {Range} 返回Range */ selectNodeContents : function( node ) { return this.setStart( node, 0 ).setEnd( node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length ); }, /** * 克隆range * @public * @function * @name baidu.editor.dom.Range.cloneRange * @return {Range} 克隆的range对象 */ cloneRange : function() { var me = this,range = new Range( me.document ); return range.setStart( me.startContainer, me.startOffset ).setEnd( me.endContainer, me.endOffset ); }, /** * 让选区闭合 * @public * @function * @name baidu.editor.dom.Range.collapse * @param {Boolean} toStart 是否在选区开始位置闭合选区,true在开始位置闭合,false反之 * @return {Range} range对象 */ collapse : function( toStart ) { var me = this; if ( toStart ) { me.endContainer = me.startContainer; me.endOffset = me.startOffset; } else { me.startContainer = me.endContainer; me.startOffset = me.endOffset; } me.collapsed = true; return me; }, /** * 调整range的边界,“缩”到合适的位置 * @public * @function * @name baidu.editor.dom.Range.shrinkBoundary * @param {Boolean} ignoreEnd 是否考虑前面的元素 */ shrinkBoundary : function( ignoreEnd ) { var me = this,child, collapsed = me.collapsed; while ( me.startContainer.nodeType == 1 //是element && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element && child.nodeType == 1 && !domUtils.isBookmarkNode(child) && !dtd.$empty[child.tagName] && !dtd.$nonChild[child.tagName] ) { me.setStart( child, 0 ); } if ( collapsed ) return me.collapse( true ); if ( !ignoreEnd ) { while ( me.endContainer.nodeType == 1//是element && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错 && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element && child.nodeType == 1 && !domUtils.isBookmarkNode(child) && !dtd.$empty[child.tagName] && !dtd.$nonChild[child.tagName]) { me.setEnd( child, child.childNodes.length ); } } return me; }, /** * 找到startContainer和endContainer的公共祖先节点 * @public * @function * @name baidu.editor.dom.Range.getCommonAncestor * @param {Boolean} includeSelf 是否包含自身 * @param {Boolean} ignoreTextNode 是否忽略文本节点 * @return {Node} 祖先节点 */ getCommonAncestor : function( includeSelf, ignoreTextNode ) { var start = this.startContainer, end = this.endContainer; if ( start === end ) { if ( includeSelf && start.nodeType == 1 && this.startOffset == this.endOffset - 1 ) { return start.childNodes[this.startOffset]; } //只有在上来就相等的情况下才会出现是文本的情况 return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start; } return domUtils.getCommonAncestor( start, end ); }, /** * 切割文本节点,将边界扩大到element * @public * @function * @name baidu.editor.dom.Range.trimBoundary * @param {Boolean} ignoreEnd 为真就不处理结束边界 * @return {Range} range对象 * @example <b>|xxx</b> * startContainer = xxx; startOffset = 0 * 执行后 * startContainer = <b>; startOffset = 0 * @example <b>xx|x</b> * startContainer = xxx; startOffset = 2 * 执行后 * startContainer = <b>; startOffset = 1 因为将xxx切割成2个节点了 */ trimBoundary : function( ignoreEnd ) { this.txtToElmBoundary(); var start = this.startContainer, offset = this.startOffset, collapsed = this.collapsed, end = this.endContainer; if ( start.nodeType == 3 ) { if ( offset == 0 ) { this.setStartBefore( start ) } else { if ( offset >= start.nodeValue.length ) { this.setStartAfter( start ); } else { var textNode = domUtils.split( start, offset ); //跟新结束边界 if ( start === end ) this.setEnd( textNode, this.endOffset - offset ); else if ( start.parentNode === end ) this.endOffset += 1; this.setStartBefore( textNode ); } } if ( collapsed ) { return this.collapse( true ); } } if ( !ignoreEnd ) { offset = this.endOffset; end = this.endContainer; if ( end.nodeType == 3 ) { if ( offset == 0 ) { this.setEndBefore( end ); } else { if ( offset >= end.nodeValue.length ) { this.setEndAfter( end ); } else { domUtils.split( end, offset ); this.setEndAfter( end ); } } } } return this; }, /** * 如果选区在文本的边界上,就扩展选区到文本的父节点上 * @public * @function * @name baidu.editor.dom.Range.txtToElmBoundary * @return {Range} range对象 * @example <b> |xxx</b> * startContainer = xxx; startOffset = 0 * 执行后 * startContainer = <b>; startOffset = 0 * @example <b> xxx| </b> * startContainer = xxx; startOffset = 3 * 执行后 * startContainer = <b>; startOffset = 1 */ txtToElmBoundary : function() { function adjust( r, c ) { var container = r[c + 'Container'], offset = r[c + 'Offset']; if ( container.nodeType == 3 ) { if ( !offset ) { r['set' + c.replace( /(\w)/, function( a ) { return a.toUpperCase() } ) + 'Before']( container ) } else if ( offset >= container.nodeValue.length ) { r['set' + c.replace( /(\w)/, function( a ) { return a.toUpperCase() } ) + 'After' ]( container ) } } } if ( !this.collapsed ) { adjust( this, 'start' ); adjust( this, 'end' ); } return this; }, /** * 在当前选区的开始位置前插入一个节点或者fragment * @public * @function * @name baidu.editor.dom.Range.insertNode * @param {Node/DocumentFragment} node 要插入的节点或fragment * @return {Range} 返回range对象 */ insertNode : function( node ) { var first = node,length = 1; if ( node.nodeType == 11 ) { first = node.firstChild; length = node.childNodes.length; } this.trimBoundary( true ); var start = this.startContainer, offset = this.startOffset; var nextNode = start.childNodes[ offset ]; if ( nextNode ) { start.insertBefore( node, nextNode ); } else { start.appendChild( node ); } if ( first.parentNode === this.endContainer ) { this.endOffset = this.endOffset + length; } return this.setStartBefore( first ); }, /** * 设置光标位置 * @public * @function * @name baidu.editor.dom.Range.setCursor * @param {Boolean} toEnd true为闭合到选区的结束位置后,false为闭合到选区的开始位置前 * @return {Range} 返回range对象 */ setCursor : function( toEnd ,notFillData) { return this.collapse( toEnd ? false : true ).select(notFillData); }, /** * 创建书签 * @public * @function * @name baidu.editor.dom.Range.createBookmark * @param {Boolean} serialize true:为true则返回对象中用id来分别表示书签的开始和结束节点 * @param {Boolean} same true:是否采用唯一的id,false将会为每一个标签产生一个唯一的id * @returns {Object} bookmark对象 */ createBookmark : function( serialize, same ) { var endNode, startNode = this.document.createElement( 'span' ); startNode.style.cssText = 'display:none;line-height:0px;'; startNode.appendChild( this.document.createTextNode( '\uFEFF' ) ); startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++); if ( !this.collapsed ) { endNode = startNode.cloneNode( true ); endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++); } this.insertNode( startNode ); if ( endNode ) { this.collapse( false ).insertNode( endNode ); this.setEndBefore( endNode ) } this.setStartAfter( startNode ); return { start : serialize ? startNode.id : startNode, end : endNode ? serialize ? endNode.id : endNode : null, id : serialize } }, /** * 移动边界到书签,并删除书签 * @public * @function * @name baidu.editor.dom.Range.moveToBookmark * @params {Object} bookmark对象 * @returns {Range} Range对象 */ moveToBookmark : function( bookmark ) { var start = bookmark.id ? this.document.getElementById( bookmark.start ) : bookmark.start, end = bookmark.end && bookmark.id ? this.document.getElementById( bookmark.end ) : bookmark.end; this.setStartBefore( start ); domUtils.remove( start ); if ( end ) { this.setEndBefore( end ); domUtils.remove( end ) } else { this.collapse( true ); } return this; }, /** * 调整边界到一个block元素上,或者移动到最大的位置 * @public * @function * @name baidu.editor.dom.Range.enlarge * @params {Boolean} toBlock 扩展到block元素 * @params {Function} stopFn 停止函数,若返回true,则不再扩展 * @return {Range} Range对象 */ enlarge : function( toBlock, stopFn ) { var isBody = domUtils.isBody, pre,node,tmp = this.document.createTextNode( '' ); if ( toBlock ) { node = this.startContainer; if ( node.nodeType == 1 ) { if ( node.childNodes[this.startOffset] ) { pre = node = node.childNodes[this.startOffset] } else { node.appendChild( tmp ); pre = node = tmp; } } else { pre = node; } while ( 1 ) { if ( domUtils.isBlockElm( node ) ) { node = pre; while ( (pre = node.previousSibling) && !domUtils.isBlockElm( pre ) ) { node = pre; } this.setStartBefore( node ); break; } pre = node; node = node.parentNode; } node = this.endContainer; if ( node.nodeType == 1 ) { if(pre = node.childNodes[this.endOffset]) { node.insertBefore( tmp, pre ); }else{ node.appendChild(tmp) } pre = node = tmp; } else { pre = node; } while ( 1 ) { if ( domUtils.isBlockElm( node ) ) { node = pre; while ( (pre = node.nextSibling) && !domUtils.isBlockElm( pre ) ) { node = pre; } this.setEndAfter( node ); break; } pre = node; node = node.parentNode; } if ( tmp.parentNode === this.endContainer ) { this.endOffset--; } domUtils.remove( tmp ) } // 扩展边界到最大 if ( !this.collapsed ) { while ( this.startOffset == 0 ) { if ( stopFn && stopFn( this.startContainer ) ) break; if ( isBody( this.startContainer ) )break; this.setStartBefore( this.startContainer ); } while ( this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length) ) { if ( stopFn && stopFn( this.endContainer ) ) break; if ( isBody( this.endContainer ) )break; this.setEndAfter( this.endContainer ) } } return this; }, /** * 调整边界 * @public * @function * @name baidu.editor.dom.Range.adjustmentBoundary * @return {Range} Range对象 * @example * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx] * <b>[xx</b><i>]xxx</i> ==> <b>[xx</b>]<i>xxx</i> * */ adjustmentBoundary : function() { if(!this.collapsed){ while ( !domUtils.isBody( this.startContainer ) && this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length ) { this.setStartAfter( this.startContainer ); } while ( !domUtils.isBody( this.endContainer ) && !this.endOffset ) { this.setEndBefore( this.endContainer ); } } return this; }, /** * 给选区中的内容加上inline样式 * @public * @function * @name baidu.editor.dom.Range.applyInlineStyle * @param {String} tagName 标签名称 * @param {Object} attrObj 属性 * @return {Range} Range对象 */ applyInlineStyle : function( tagName, attrs ,list) { if(this.collapsed)return this; this.trimBoundary().enlarge( false, function( node ) { return node.nodeType == 1 && domUtils.isBlockElm( node ) } ).adjustmentBoundary(); var bookmark = this.createBookmark(), end = bookmark.end, filterFn = function( node ) { return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace( node ) }, current = domUtils.getNextDomNode( bookmark.start, false, filterFn ), node, pre, range = this.cloneRange(); while ( current && (domUtils.getPosition( current, end ) & domUtils.POSITION_PRECEDING) ) { if ( current.nodeType == 3 || dtd[tagName][current.tagName] ) { range.setStartBefore( current ); node = current; while ( node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end ) { pre = node; node = domUtils.getNextDomNode( node, node.nodeType == 1, null, function( parent ) { return dtd[tagName][parent.tagName] } ) } var frag = range.setEndAfter( pre ).extractContents(),elm; if(list && list.length > 0){ var level,top; top = level = list[0].cloneNode(false); for(var i=1,ci;ci=list[i++];){ level.appendChild(ci.cloneNode(false)); level = level.firstChild; } elm = level; }else{ elm = range.document.createElement( tagName ) } if ( attrs ) { domUtils.setAttributes( elm, attrs ) } elm.appendChild( frag ); range.insertNode( list ? top : elm ); //处理下滑线在a上的情况 var aNode; if(tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm,'a',true)) ){ domUtils.setAttributes(aNode,attrs); domUtils.remove(elm,true); elm = aNode; }else{ domUtils.mergSibling( elm ); domUtils.clearEmptySibling( elm ); } //去除子节点相同的 domUtils.mergChild( elm, tagName,attrs ); current = domUtils.getNextDomNode( elm, false, filterFn ); domUtils.mergToParent( elm ); if ( node === end )break; } else { current = domUtils.getNextDomNode( current, true, filterFn ) } } return this.moveToBookmark( bookmark ); }, /** * 去掉inline样式 * @public * @function * @name baidu.editor.dom.Range.removeInlineStyle * @param {String/Array} tagName 要去掉的标签名 * @return {Range} Range对象 */ removeInlineStyle : function( tagName ) { if(this.collapsed)return this; tagName = utils.isArray( tagName ) ? tagName : [tagName]; this.shrinkBoundary().adjustmentBoundary(); var start = this.startContainer,end = this.endContainer; while ( 1 ) { if ( start.nodeType == 1 ) { if ( utils.indexOf( tagName, start.tagName.toLowerCase() ) > -1 ) { break; } if ( start.tagName.toLowerCase() == 'body' ) { start = null; break; } } start = start.parentNode; } while ( 1 ) { if ( end.nodeType == 1 ) { if ( utils.indexOf( tagName, end.tagName.toLowerCase() ) > -1 ) { break; } if ( end.tagName.toLowerCase() == 'body' ) { end = null; break; } } end = end.parentNode; } var bookmark = this.createBookmark(), frag, tmpRange; if ( start ) { tmpRange = this.cloneRange().setEndBefore( bookmark.start ).setStartBefore( start ); frag = tmpRange.extractContents(); tmpRange.insertNode( frag ); domUtils.clearEmptySibling( start, true ); start.parentNode.insertBefore( bookmark.start, start ); } if ( end ) { tmpRange = this.cloneRange().setStartAfter( bookmark.end ).setEndAfter( end ); frag = tmpRange.extractContents(); tmpRange.insertNode( frag ); domUtils.clearEmptySibling( end, false, true ); end.parentNode.insertBefore( bookmark.end, end.nextSibling ); } var current = domUtils.getNextDomNode( bookmark.start, false, function( node ) { return node.nodeType == 1 } ),next; while ( current && current !== bookmark.end ) { next = domUtils.getNextDomNode( current, true, function( node ) { return node.nodeType == 1 } ); if ( utils.indexOf( tagName, current.tagName.toLowerCase() ) > -1 ) { domUtils.remove( current, true ); } current = next; } return this.moveToBookmark( bookmark ); }, /** * 得到一个自闭合的节点 * @public * @function * @name baidu.editor.dom.Range.getClosedNode * @return {Node} 闭合节点 * @example * <img />,<br /> */ getClosedNode : function() { var node; if ( !this.collapsed ) { var range = this.cloneRange().adjustmentBoundary().shrinkBoundary(); if ( range.startContainer.nodeType == 1 && range.startContainer === range.endContainer && range.endOffset - range.startOffset == 1 ) { var child = range.startContainer.childNodes[range.startOffset]; if ( child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) { node = child; } } } return node; }, /** * 根据range选中元素 * @public * @function * @name baidu.editor.dom.Range.select * @param {Boolean} notInsertFillData true为不加占位符 */ select : browser.ie ? function( notInsertFillData ,textRange) { var nativeRange; if ( !this.collapsed ) this.shrinkBoundary(); var node = this.getClosedNode(); if ( node && !textRange) { try { nativeRange = this.document.body.createControlRange(); nativeRange.addElement( node ); nativeRange.select(); } catch( e ) { } return this; } var bookmark = this.createBookmark(), start = bookmark.start, end; nativeRange = this.document.body.createTextRange(); nativeRange.moveToElementText( start ); nativeRange.moveStart( 'character', 1 ); if ( !this.collapsed ) { var nativeRangeEnd = this.document.body.createTextRange(); end = bookmark.end; nativeRangeEnd.moveToElementText( end ); nativeRange.setEndPoint( 'EndToEnd', nativeRangeEnd ); } else { if ( !notInsertFillData && this.startContainer.nodeType != 3 ) { //使用<span>|x<span>固定住光标 var tmpText = this.document.createTextNode( fillChar ), tmp = this.document.createElement( 'span' ); tmp.appendChild( this.document.createTextNode( fillChar) ); start.parentNode.insertBefore( tmp, start ); start.parentNode.insertBefore( tmpText, start ); //当点b,i,u时,不能清除i上边的b removeFillData(this.document,tmpText); fillData = tmpText; mergSibling(tmp,'previousSibling'); mergSibling(start,'nextSibling'); nativeRange.moveStart( 'character', -1 ); nativeRange.collapse( true ); } } this.moveToBookmark( bookmark ); tmp && domUtils.remove( tmp ); nativeRange.select(); return this; } : function( notInsertFillData ) { var win = domUtils.getWindow( this.document ), sel = win.getSelection(), txtNode; browser.gecko ? this.document.body.focus() : win.focus(); if ( sel ) { sel.removeAllRanges(); // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断 // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR' if ( this.collapsed && !notInsertFillData ){ txtNode = this.document.createTextNode( fillChar ); //跟着前边走 this.insertNode( txtNode ); removeFillData(this.document,txtNode); mergSibling(txtNode,'previousSibling'); mergSibling(txtNode,'nextSibling'); fillData = txtNode; this.setStart( txtNode, browser.webkit ? 1 : 0 ).collapse( true ); } var nativeRange = this.document.createRange(); nativeRange.setStart( this.startContainer, this.startOffset ); nativeRange.setEnd( this.endContainer, this.endOffset ); sel.addRange( nativeRange ); } return this; }, /** * 滚动到可视范围 * @public * @function * @name baidu.editor.dom.Range.scrollToView * @param {Boolean} win 操作的window对象,若为空,则使用当前的window对象 * @param {Number} offset 滚动的偏移量 * @return {Range} Range对象 */ scrollToView : function(win,offset){ win = win ? window : domUtils.getWindow(this.document); var span = this.document.createElement('span'); //trace:717 span.innerHTML = '&nbsp;'; var tmpRange = this.cloneRange(); tmpRange.insertNode(span); domUtils.scrollToView(span,win,offset); domUtils.remove(span); return this; } }; })();///import editor.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/dom/domUtils.js ///import core/dom/Range.js /** * @class baidu.editor.dom.Selection Selection类 */ (function () { function getBoundaryInformation( range, start ) { var getIndex = domUtils.getNodeIndex; range = range.duplicate(); range.collapse( start ); var parent = range.parentElement(); //如果节点里没有子节点,直接退出 if ( !parent.hasChildNodes() ) { return {container:parent,offset:0}; } var siblings = parent.children, child, testRange = range.duplicate(), startIndex = 0,endIndex = siblings.length - 1,index = -1, distance; while ( startIndex <= endIndex ) { index = Math.floor( (startIndex + endIndex) / 2 ); child = siblings[index]; testRange.moveToElementText( child ); var position = testRange.compareEndPoints( 'StartToStart', range ); if ( position > 0 ) { endIndex = index - 1; } else if ( position < 0 ) { startIndex = index + 1; } else { //trace:1043 return {container:parent,offset:getIndex( child )}; } } if ( index == -1 ) { testRange.moveToElementText( parent ); testRange.setEndPoint( 'StartToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; siblings = parent.childNodes; if ( !distance ) { child = siblings[siblings.length - 1]; return {container:child,offset:child.nodeValue.length}; } var i = siblings.length; while ( distance > 0 ) distance -= siblings[ --i ].nodeValue.length; return {container:siblings[i],offset:-distance} } testRange.collapse( position > 0 ); testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; if ( !distance ) { return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName]? {container : parent,offset:getIndex( child ) + (position > 0 ? 0 : 1)} : {container : child,offset: position > 0 ? 0 : child.childNodes.length} } while ( distance > 0 ) { try{ var pre = child; child = child[position > 0 ? 'previousSibling' : 'nextSibling']; distance -= child.nodeValue.length; }catch(e){ return {container:parent,offset:getIndex(pre)}; } } return {container:child,offset:position > 0 ? -distance : child.nodeValue.length + distance} } /** * 将ieRange转换为Range对象 * @param {Range} ieRange ieRange对象 * @param {Range} range Range对象 * @return {Range} range 返回转换后的Range对象 */ function transformIERangeToRange( ieRange, range ) { if ( ieRange.item ) { range.selectNode( ieRange.item( 0 ) ); } else { var bi = getBoundaryInformation( ieRange, true ); range.setStart( bi.container, bi.offset ); if ( ieRange.compareEndPoints( 'StartToEnd',ieRange ) != 0 ) { bi = getBoundaryInformation( ieRange, false ); range.setEnd( bi.container, bi.offset ); } } return range; } /** * 获得ieRange * @param {Selection} sel Selection对象 * @return {ieRange} 得到ieRange */ function _getIERange(sel){ var ieRange; //ie下有可能报错 try{ ieRange = sel.getNative().createRange(); }catch(e){ return null; } var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement(); if ( ( el.ownerDocument || el ) === sel.document ) { return ieRange; } return null; } var Selection = dom.Selection = function ( doc ) { var me = this, iframe; me.document = doc; if ( ie ) { iframe = domUtils.getWindow(doc).frameElement; domUtils.on( iframe, 'beforedeactivate', function () { me._bakIERange = me.getIERange(); } ); domUtils.on( iframe, 'activate', function () { try { if ( !_getIERange(me) && me._bakIERange ) { me._bakIERange.select(); } } catch ( ex ) { } me._bakIERange = null; } ); } iframe = doc = null; }; Selection.prototype = { /** * 获取原生seleciton对象 * @public * @function * @name baidu.editor.dom.Selection.getNative * @return {Selection} 获得selection对象 */ getNative : function () { var doc = this.document; return !doc ? null : ie ? doc.selection : domUtils.getWindow( doc ).getSelection(); }, /** * 获得ieRange * @public * @function * @name baidu.editor.dom.Selection.getIERange * @return {ieRange} 返回ie原生的Range */ getIERange : function () { var ieRange = _getIERange(this); if ( !ieRange ) { if ( this._bakIERange ) { return this._bakIERange; } } return ieRange; }, /** * 缓存当前选区的range和选区的开始节点 * @public * @function * @name baidu.editor.dom.Selection.cache */ cache : function () { this.clear(); this._cachedRange = this.getRange(); this._cachedStartElement = this.getStart(); this._cachedStartElementPath = this.getStartElementPath(); }, getStartElementPath : function(){ if(this._cachedStartElementPath){ return this._cachedStartElementPath; } var start = this.getStart(); if(start){ return domUtils.findParents(start,true,null,true) } return []; }, /** * 清空缓存 * @public * @function * @name baidu.editor.dom.Selection.clear */ clear : function () { this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null; }, /** * 编辑器是否得到了选区 */ isFocus : function(){ return browser.ie && _getIERange(this) || !browser.ie && this.getNative().rangeCount ? true : false; }, /** * 获取选区对应的Range * @public * @function * @name baidu.editor.dom.Selection.getRange * @returns {baidu.editor.dom.Range} 得到Range对象 */ getRange : function () { var me = this; function optimze(range){ var child = me.document.body.firstChild, collapsed = range.collapsed; while(child && child.firstChild){ range.setStart(child,0); child = child.firstChild; } if(!range.startContainer){ range.setStart(me.document.body,0) } if(collapsed){ range.collapse(true); } } if ( me._cachedRange != null ) { return this._cachedRange; } var range = new baidu.editor.dom.Range( me.document ); if ( ie ) { var nativeRange = me.getIERange(); if(nativeRange){ transformIERangeToRange( nativeRange, range ); }else{ optimze(range) } } else { var sel = me.getNative(); if ( sel && sel.rangeCount ) { var firstRange = sel.getRangeAt( 0 ) ; var lastRange = sel.getRangeAt( sel.rangeCount - 1 ); range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset ); if(range.collapsed && domUtils.isBody(range.startContainer) && !range.startOffset){ optimze(range) } } else { //trace:1734 有可能已经不在dom树上了,标识的节点 if(this._bakRange && domUtils.inDoc(this._bakRange.startContainer,this.document)) return this._bakRange; optimze(range) } } return this._bakRange = range; }, /** * 获取开始元素,用于状态反射 * @public * @function * @name baidu.editor.dom.Selection.getStart * @return {Element} 获得开始元素 */ getStart : function () { if ( this._cachedStartElement ) { return this._cachedStartElement; } var range = ie ? this.getIERange() : this.getRange(), tmpRange, start,tmp,parent; if (ie) { if(!range){ //todo 给第一个值可能会有问题 return this.document.body.firstChild; } //control元素 if (range.item) return range.item(0); tmpRange = range.duplicate(); //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx tmpRange.text.length > 0 && tmpRange.moveStart('character',1); tmpRange.collapse(1); start = tmpRange.parentElement(); parent = tmp = range.parentElement(); while (tmp = tmp.parentNode) { if (tmp == start) { start = parent; break; } } } else { range.shrinkBoundary(); start = range.startContainer; if (start.nodeType == 1 && start.hasChildNodes()) start = start.childNodes[Math.min(start.childNodes.length - 1, range.startOffset)]; if (start.nodeType == 3) return start.parentNode; } return start; }, /** * 得到选区中的文本 * @public * @function * @name baidu.editor.dom.Selection.getText * @return {String} 选区中包含的文本 */ getText : function(){ if(this.isFocus()){ var nativeSel = this.getNative(), nativeRange = browser.ie ? nativeSel.createRange() : nativeSel.getRangeAt(0); return nativeRange.text || nativeRange.toString(); } return ''; } }; })();///import editor.js ///import core/utils.js ///import core/EventBase.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/domUtils.js ///import core/dom/Selection.js ///import core/dom/dtd.js (function () { var uid = 0, _selectionChangeTimer; function replaceSrc(div){ var imgs = div.getElementsByTagName("img"), orgSrc; for(var i=0,img;img = imgs[i++];){ if(orgSrc = img.getAttribute("orgSrc")){ img.src = orgSrc; img.removeAttribute("orgSrc"); } } var as = div.getElementsByTagName("a"); for(var i=0,ai;ai=as[i++];i++){ if(ai.getAttribute('data_ue_src')){ ai.setAttribute('href',ai.getAttribute('data_ue_src')) } } } /** * 编辑器类 * @public * @class * @extends baidu.editor.EventBase * @name baidu.editor.Editor * @param {Object} options */ var Editor = UE.Editor = function( options ) { var me = this; me.uid = uid ++; EventBase.call( me ); me.commands = {}; me.options = utils.extend( options || {}, UEDITOR_CONFIG, true ); //初始化插件 for ( var pi in UE.plugins ) { UE.plugins[pi].call( me ) } }; Editor.prototype = /**@lends baidu.editor.Editor.prototype*/{ destroy : function(){ this.fireEvent('destroy'); this.container.innerHTML = ''; domUtils.remove(this.container); }, /** * 渲染编辑器的DOM到指定容器,必须且只能调用一次 * @public * @function * @param {Element|String} container */ render : function ( container ) { if (container.constructor === String) { container = document.getElementById(container); } if(container){ container.innerHTML = '<iframe id="' + 'baidu_editor_' + this.uid + '"' + 'width="100%" height="100%" frameborder="0"></iframe>'; container.style.overflow = 'hidden'; this._setup( container.firstChild.contentWindow.document ); } }, _setup: function ( doc ) { var options = this.options, me = this; //防止在chrome下连接后边带# 会跳动的问题 !browser.webkit && doc.open(); var useBodyAsViewport = ie && browser.version < 9; doc.write( ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') + '<html xmlns="http://www.w3.org/1999/xhtml"' + (!useBodyAsViewport ? ' class="view"' : '') + '><head>' + ( options.iframeCssUrl ? '<link rel="stylesheet" type="text/css" href="' + utils.unhtml( /^http/.test(options.iframeCssUrl) ? options.iframeCssUrl : (options.UEDITOR_HOME_URL + options.iframeCssUrl) ) + '"/>' : '' ) + '<style type="text/css">' + ( options.initialStyle ||' ' ) + '</style></head><body' + (useBodyAsViewport ? ' class="view"' : '') + '></body></html>' ); !browser.webkit && doc.close(); if ( ie ) { doc.body.disabled = true; doc.body.contentEditable = true; doc.body.disabled = false; } else { doc.body.contentEditable = true; doc.body.spellcheck = false; } this.document = doc; this.window = doc.defaultView || doc.parentWindow; this.iframe = this.window.frameElement; this.body = doc.body; if (this.options.minFrameHeight) { this.setHeight(this.options.minFrameHeight); this.body.style.height = this.options.minFrameHeight; } this.selection = new dom.Selection( doc ); //gecko初始化就能得到range,无法判断isFocus了 if(browser.gecko){ this.selection.getNative().removeAllRanges(); } this._initEvents(); if(me.options.initialContent){ if(me.options.autoClearinitialContent){ var oldExecCommand = me.execCommand; me.execCommand = function(){ me.fireEvent('firstBeforeExecCommand'); oldExecCommand.apply(me,arguments) }; this.setDefaultContent(this.options.initialContent); }else this.setContent(this.options.initialContent,true); } //为form提交提供一个隐藏的textarea for(var form = this.iframe.parentNode;!domUtils.isBody(form);form = form.parentNode){ if(form.tagName == 'FORM'){ domUtils.on(form,'submit',function(){ var textarea = document.getElementById('ueditor_textarea_' + me.options.textarea); if(!textarea){ textarea = document.createElement('textarea'); textarea.setAttribute('name',me.options.textarea); textarea.id = 'ueditor_textarea_' + me.options.textarea; textarea.style.display = 'none'; this.appendChild(textarea); } textarea.value = me.getContent(); }); break; } } //编辑器不能为空内容 if(domUtils.isEmptyNode(me.body)){ this.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>'; } //如果要求focus, 就把光标定位到内容开始 if(me.options.focus){ setTimeout(function(){ me.focus(); //如果自动清除开着,就不需要做selectionchange; !me.options.autoClearinitialContent && me._selectionChange() }); } if(!this.container){ this.container = this.iframe.parentNode; } if(me.options.fullscreen && me.ui){ me.ui.setFullScreen(true) } this.fireEvent( 'ready' ); if(!browser.ie){ domUtils.on(me.window,'blur',function(){ me._bakRange = me.selection.getRange(); me.selection.getNative().removeAllRanges(); }); } //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点 if(browser.gecko && browser.version <= 10902){ //修复ff3.6初始化进来,不能点击获得焦点 me.body.contentEditable = false; setTimeout(function(){ me.body.contentEditable = true; },100); setInterval(function(){ me.body.style.height = me.iframe.offsetHeight - 20 + 'px' },100) } }, /** * 创建textarea,同步编辑的内容到textarea,为后台获取内容做准备 * @param formId 制定在那个form下添加 * @public * @function */ sync : function(formId){ var me = this, form; function setValue(form){ var textarea = document.getElementById('ueditor_textarea_' + me.options.textarea); if(!textarea){ textarea = document.createElement('textarea'); textarea.setAttribute('name',me.options.textarea); textarea.id = 'ueditor_textarea_' + me.options.textarea; textarea.style.display = 'none'; form.appendChild(textarea); } textarea.value = me.getContent(); } if(formId){ form = document.getElementById(formId); form && setValue(form); }else{ for(form = me.iframe.parentNode;!domUtils.isBody(form);form = form.parentNode){ if(form.tagName == 'FORM'){ setValue(form); break; } } } }, /** * 设置编辑器高度 * @public * @function * @param {Number} height 高度 */ setHeight: function (height){ if (height !== parseInt(this.iframe.parentNode.style.height)){ this.iframe.parentNode.style.height = height + 'px'; } //ie9下body 高度100%失效,改为手动设置 if(browser.ie && browser.version == 9){ this.document.body.style.height = height - 20 + 'px' } }, /** * 获取编辑器内容 * @public * @function * @returns {String} */ getContent : function (cmd) { this.fireEvent( 'beforegetcontent',cmd ); var reg = new RegExp( domUtils.fillChar, 'g' ), //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除 html = this.document.body.innerHTML.replace(reg,'').replace(/>[\t\r\n]*?</g,'><'); this.fireEvent( 'aftergetcontent',cmd ); if (this.serialize) { var node = this.serialize.parseHTML(html); node = this.serialize.transformOutput(node); html = this.serialize.toHTML(node); } return html; }, /** * 获取编辑器中的文本内容 * @public * @function * @returns {String} */ getContentTxt : function(){ var reg = new RegExp( domUtils.fillChar,'g' ); return this.body[browser.ie ? 'innerText':'textContent'].replace(reg,'') }, /** * 设置编辑器内容 * @public * @function * @param {String} html */ setContent : function ( html,notFireSelectionchange) { var me = this, inline = utils.extend({a:1,A:1},dtd.$inline,true), lastTagName; html = html .replace(/^[ \t\r\n]*?</,'<') .replace(/>[ \t\r\n]*?$/,'>') .replace(/>[\t\r\n]*?</g,'><')//代码高量的\n不能去除 .replace(/[\s\/]?(\w+)?>[ \t\r\n]*?<\/?(\w+)/gi,function(a,b,c){ if(b){ lastTagName = c; }else{ b = lastTagName } return !inline[b] && !inline[c] ? a.replace(/>[ \t\r\n]*?</,'><') : a; }); me.fireEvent( 'beforesetcontent' ); var serialize = this.serialize; if (serialize) { var node = serialize.parseHTML(html); node = serialize.transformInput(node); node = serialize.filter(node); html = serialize.toHTML(node); } //html.replace(new RegExp('[\t\n\r' + domUtils.fillChar + ']*','g'),''); //去掉了\t\n\r 如果有插入的代码,在源码切换所见即所得模式时,换行都丢掉了 //\r在ie下的不可见字符,在源码切换时会变成多个&nbsp; //trace:1559 this.document.body.innerHTML = html.replace(new RegExp('[\r' + domUtils.fillChar + ']*','g'),''); //处理ie6下innerHTML自动将相对路径转化成绝对路径的问题 if(browser.ie && browser.version < 7 && me.options.relativePath){ replaceSrc(this.document.body); } //给文本或者inline节点套p标签 if(me.options.enterTag == 'p'){ var child = this.body.firstChild, p = me.document.createElement('p'), tmpNode; if(!child || child.nodeType == 1 && dtd.$cdata[child.tagName]){ this.body.innerHTML = '<p>'+(browser.ie ? '' :'<br/>')+'</p>' + this.body.innerHTML; }else{ while(child){ if(child.nodeType ==3 || child.nodeType == 1 && dtd.p[child.tagName]){ tmpNode = child.nextSibling; p.appendChild(child); child = tmpNode; if(!child){ me.body.appendChild(p); } }else{ if(p.firstChild){ me.body.insertBefore(p,child); p = me.document.createElement('p') } child = child.nextSibling } } } } me.adjustTable && me.adjustTable(me.body); me.fireEvent( 'aftersetcontent' ); me.fireEvent( 'contentchange' ); !notFireSelectionchange && me._selectionChange(); //清除保存的选区 me._bakRange = me._bakIERange = null; //trace:1742 setContent后gecko能得到焦点问题 if(browser.gecko){ me.selection.getNative().removeAllRanges(); } }, /** * 让编辑器获得焦点 * @public * @function */ focus : function () { this.selection.getRange().select(true); }, /** * 初始化事件,绑定selectionchange * @private * @function */ _initEvents : function () { var me = this, doc = me.document, win = me.window; me._proxyDomEvent = utils.bind( me._proxyDomEvent, me ); domUtils.on( doc, ['click', 'contextmenu','mousedown','keydown', 'keyup','keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent ); domUtils.on( win, ['focus', 'blur'], me._proxyDomEvent ); domUtils.on( doc, ['mouseup','keydown'], function(evt){ //特殊键不触发selectionchange if(evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)){ return; } if(evt.button == 2)return; me._selectionChange(250, evt ); }); //处理拖拽 //ie ff不能从外边拖入 //chrome只针对从外边拖入的内容过滤 var innerDrag = 0,source = browser.ie ? me.body : me.document,dragoverHandler; domUtils.on(source,'dragstart',function(){ innerDrag = 1; }); domUtils.on(source,browser.webkit ? 'dragover' : 'drop',function(){ return browser.webkit ? function(){ clearTimeout( dragoverHandler ); dragoverHandler = setTimeout( function(){ if(!innerDrag){ var sel = me.selection, range = sel.getRange(); if(range){ var common = range.getCommonAncestor(); if(common && me.serialize){ var f = me.serialize, node = f.filter( f.transformInput( f.parseHTML( f.word(common.innerHTML) ) ) ); common.innerHTML = f.toHTML(node) } } } innerDrag = 0; }, 200 ); } : function(e){ if(!innerDrag){ e.preventDefault ? e.preventDefault() :(e.returnValue = false) ; } innerDrag = 0; } }()); }, _proxyDomEvent: function ( evt ) { return this.fireEvent( evt.type.replace( /^on/, '' ), evt ); }, _selectionChange : function ( delay, evt ) { var me = this; //有光标才做selectionchange if(!me.selection.isFocus()) return; var hackForMouseUp = false; var mouseX, mouseY; if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') { var range = this.selection.getRange(); if (!range.collapsed) { hackForMouseUp = true; mouseX = evt.clientX; mouseY = evt.clientY; } } clearTimeout(_selectionChangeTimer); _selectionChangeTimer = setTimeout(function(){ if(!me.selection.getNative()){ return; } //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响 var ieRange; if (hackForMouseUp && me.selection.getNative().type == 'None' ) { ieRange = me.document.body.createTextRange(); try { ieRange.moveToPoint( mouseX, mouseY ); } catch(ex){ ieRange = null; } } var bakGetIERange; if (ieRange) { bakGetIERange = me.selection.getIERange; me.selection.getIERange = function (){ return ieRange; }; } me.selection.cache(); if (bakGetIERange) { me.selection.getIERange = bakGetIERange; } if ( me.selection._cachedRange && me.selection._cachedStartElement ) { me.fireEvent( 'beforeselectionchange' ); // 第二个参数causeByUi为true代表由用户交互造成的selectionchange. me.fireEvent( 'selectionchange', !!evt ); me.fireEvent('afterselectionchange'); me.selection.clear(); } }, delay || 50); }, _callCmdFn: function ( fnName, args ) { var cmdName = args[0].toLowerCase(), cmd, cmdFn; cmdFn = ( cmd = this.commands[cmdName] ) && cmd[fnName] || ( cmd = UE.commands[cmdName]) && cmd[fnName]; if ( cmd && !cmdFn && fnName == 'queryCommandState' ) { return false; } else if ( cmdFn ) { return cmdFn.apply( this, args ); } }, /** * 执行命令 * @public * @function * @param {String} cmdName 执行的命令名 * */ execCommand : function ( cmdName ) { cmdName = cmdName.toLowerCase(); var me = this, result, cmd = me.commands[cmdName] || UE.commands[cmdName]; if ( !cmd || !cmd.execCommand ) { return; } if ( !cmd.notNeedUndo && !me.__hasEnterExecCommand ) { me.__hasEnterExecCommand = true; if(me.queryCommandState(cmdName) !=-1){ me.fireEvent( 'beforeexeccommand', cmdName ); result = this._callCmdFn( 'execCommand', arguments ); me.fireEvent( 'afterexeccommand', cmdName ); } me.__hasEnterExecCommand = false; } else { result = this._callCmdFn( 'execCommand', arguments ); } me._selectionChange(); return result; }, /** * 查询命令的状态 * @public * @function * @param {String} cmdName 执行的命令名 * @returns {Number|*} -1 : disabled, false : normal, true : enabled. * */ queryCommandState : function ( cmdName ) { return this._callCmdFn( 'queryCommandState', arguments ); }, /** * 查询命令的值 * @public * @function * @param {String} cmdName 执行的命令名 * @returns {*} */ queryCommandValue : function ( cmdName ) { return this._callCmdFn( 'queryCommandValue', arguments ); }, /** * 检查编辑区域中是否有内容 * @public * @params{Array} 自定义的标签 * @function * @returns {Boolean} true 有,false 没有 */ hasContents : function(tags){ if(tags){ for(var i=0,ci;ci=tags[i++];){ if(this.document.getElementsByTagName(ci).length > 0) return true; } } if(!domUtils.isEmptyBlock(this.body)){ return true } return false; }, /** * 从新设置 * @public * @function */ reset : function(){ this.fireEvent('reset'); }, /** * 设置默认内容 * @function * @param {String} cont 要存入的内容 */ setDefaultContent : function(){ function clear(){ var me = this; if(me.document.getElementById('initContent')){ me.document.body.innerHTML = '<p>'+(ie ? '' : '<br/>')+'</p>'; var range = me.selection.getRange(); me.removeListener('firstBeforeExecCommand',clear); me.removeListener('focus',clear); setTimeout(function(){ range.setStart(me.document.body.firstChild,0).collapse(true).select(true); me._selectionChange(); }) } } return function (cont){ var me = this; me.document.body.innerHTML = '<p id="initContent">'+cont+'</p>'; if(browser.ie && browser.version < 7 && me.options.relativePath){ replaceSrc(me.document.body); } me.addListener('firstBeforeExecCommand',clear); me.addListener('focus',clear); } }() }; utils.inherits( Editor, EventBase ); })(); /** * Created by . * User: taoqili * Date: 11-8-18 * Time: 下午3:18 * To change this template use File | Settings | File Templates. */ /** * ajax工具类 */ UE.ajax = function() { return { /** * 向url发送ajax请求 * @param url * @param ajaxOptions */ request:function(url, ajaxOptions) { var ajaxRequest = creatAjaxRequest(), //是否超时 timeIsOut = false, //默认参数 defaultAjaxOptions = { method:"POST", timeout:5000, async:true, data:{},//需要传递对象的话只能覆盖 onsuccess:function() { }, onerror:function() { } }; if (typeof url === "object") { ajaxOptions = url; url = ajaxOptions.url; } if (!ajaxRequest || !url) return; var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions; var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing" //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串 if (!utils.isEmptyObject(ajaxOpts.data)){ submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data); } //超时检测 var timerID = setTimeout(function() { if (ajaxRequest.readyState != 4) { timeIsOut = true; ajaxRequest.abort(); clearTimeout(timerID); } }, ajaxOpts.timeout); var method = ajaxOpts.method.toUpperCase(); var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr) + "&noCache=" + +new Date; ajaxRequest.open(method, str, ajaxOpts.async); ajaxRequest.onreadystatechange = function() { if (ajaxRequest.readyState == 4) { if (!timeIsOut && ajaxRequest.status == 200) { ajaxOpts.onsuccess(ajaxRequest); } else { ajaxOpts.onerror(ajaxRequest); } } }; if (method == "POST") { ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajaxRequest.send(submitStr); } else { ajaxRequest.send(null); } } }; /** * 将json参数转化成适合ajax提交的参数列表 * @param json */ function json2str(json) { var strArr = []; for (var i in json) { //忽略默认的几个参数 if(i=="method" || i=="timeout" || i=="async") continue; //传递过来的对象和函数不在提交之列 if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) { strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) ); } } return strArr.join("&"); } /** * 创建一个ajaxRequest对象 */ function creatAjaxRequest() { var xmlHttp = null; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } return xmlHttp; } }(); /* * 处理特殊键的兼容性问题 */ UE.plugins['keystrokes'] = function() { var me = this, flag = 0, keys = domUtils.keys, trans = { 'B' : 'strong', 'I' : 'em', 'FONT' : 'span' }, sizeMap = [0, 10, 12, 16, 18, 24, 32, 48], listStyle = { 'OL':['decimal','lower-alpha','lower-roman','upper-alpha','upper-roman'], 'UL':[ 'circle','disc','square'] }; me.addListener('keydown', function(type, evt) { var keyCode = evt.keyCode || evt.which; if(this.selectAll){ this.selectAll = false; if((keyCode == 8 || keyCode == 46)){ me.undoManger && me.undoManger.save(); //trace:1633 me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>'; new dom.Range(me.document).setStart(me.body.firstChild,0).setCursor(false,true); me.undoManger && me.undoManger.save(); //todo 对性能会有影响 browser.ie && me._selectionChange(); domUtils.preventDefault(evt); return; } } //处理backspace/del if (keyCode == 8 ) {//|| keyCode == 46 var range = me.selection.getRange(), tmpRange, start,end; //当删除到body最开始的位置时,会删除到body,阻止这个动作 if(range.collapsed){ start = range.startContainer; //有可能是展位符号 if(domUtils.isWhitespace(start)){ start = start.parentNode; } if(domUtils.isEmptyNode(start) && start === me.body.firstChild){ if(start.tagName != 'P'){ p = me.document.createElement('p'); me.body.insertBefore(p,start); domUtils.fillNode(me.document,p); range.setStart(p,0).setCursor(false,true); //trace:1645 domUtils.remove(start); } domUtils.preventDefault(evt); return; } } if (range.collapsed && range.startContainer.nodeType == 3 && range.startContainer.nodeValue.replace(new RegExp(domUtils.fillChar, 'g'), '').length == 0) { range.setStartBefore(range.startContainer).collapse(true) } //解决选中control元素不能删除的问题 if (start = range.getClosedNode()) { me.undoManger && me.undoManger.save(); range.setStartBefore(start); domUtils.remove(start); range.setCursor(); me.undoManger && me.undoManger.save(); domUtils.preventDefault(evt); return; } //阻止在table上的删除 if (!browser.ie) { start = domUtils.findParentByTagName(range.startContainer, 'table', true); end = domUtils.findParentByTagName(range.endContainer, 'table', true); if (start && !end || !start && end || start !== end) { evt.preventDefault(); return; } if (browser.webkit && range.collapsed && start) { tmpRange = range.cloneRange().txtToElmBoundary(); start = tmpRange.startContainer; if (domUtils.isBlockElm(start) && start.nodeType == 1 && !dtd.$tableContent[start.tagName] && !domUtils.getChildCount(start, function(node) { return node.nodeType == 1 ? node.tagName !== 'BR' : 1; })) { tmpRange.setStartBefore(start).setCursor(); domUtils.remove(start, true); evt.preventDefault(); return; } } } if (me.undoManger) { if (!range.collapsed) { me.undoManger.save(); flag = 1; } } } //处理tab键的逻辑 if (keyCode == 9) { range = me.selection.getRange(); me.undoManger && me.undoManger.save(); for (var i = 0,txt = ''; i < me.options.tabSize; i++) { txt += me.options.tabNode; } var span = me.document.createElement('span'); span.innerHTML = txt; if (range.collapsed) { var li = domUtils.findParentByTagName(range.startContainer, 'li', true); if (li && domUtils.isStartInblock(range)) { bk = range.createBookmark(); var parentLi = li.parentNode, list = me.document.createElement(parentLi.tagName); var index = utils.indexOf(listStyle[list.tagName], domUtils.getComputedStyle(parentLi, 'list-style-type')); index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; domUtils.setStyle(list, 'list-style-type', listStyle[list.tagName][index]); parentLi.insertBefore(list, li); list.appendChild(li); range.moveToBookmark(bk).select() } else range.insertNode(span.cloneNode(true).firstChild).setCursor(true); } else { //处理table start = domUtils.findParentByTagName(range.startContainer, 'table', true); end = domUtils.findParentByTagName(range.endContainer, 'table', true); if (start || end) { evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); return } //处理列表 再一个list里处理 start = domUtils.findParentByTagName(range.startContainer, ['ol','ul'], true); end = domUtils.findParentByTagName(range.endContainer, ['ol','ul'], true); if (start && end && start === end) { var bk = range.createBookmark(); start = domUtils.findParentByTagName(range.startContainer, 'li', true); end = domUtils.findParentByTagName(range.endContainer, 'li', true); //在开始单独处理 if (start === start.parentNode.firstChild) { var parentList = me.document.createElement(start.parentNode.tagName); start.parentNode.parentNode.insertBefore(parentList, start.parentNode); parentList.appendChild(start.parentNode); } else { parentLi = start.parentNode, list = me.document.createElement(parentLi.tagName); index = utils.indexOf(listStyle[list.tagName], domUtils.getComputedStyle(parentLi, 'list-style-type')); index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; domUtils.setStyle(list, 'list-style-type', listStyle[list.tagName][index]); start.parentNode.insertBefore(list, start); var nextLi; while (start !== end) { nextLi = start.nextSibling; list.appendChild(start); start = nextLi; } list.appendChild(end); } range.moveToBookmark(bk).select(); } else { if (start || end) { evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); return } //普通的情况 start = domUtils.findParent(range.startContainer, filterFn); end = domUtils.findParent(range.endContainer, filterFn); if (start && end && start === end) { range.deleteContents(); range.insertNode(span.cloneNode(true).firstChild).setCursor(true); } else { var bookmark = range.createBookmark(), filterFn = function(node) { return domUtils.isBlockElm(node); }; range.enlarge(true); var bookmark2 = range.createBookmark(), current = domUtils.getNextDomNode(bookmark2.start, false, filterFn); while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) { current.insertBefore(span.cloneNode(true).firstChild, current.firstChild); current = domUtils.getNextDomNode(current, false, filterFn); } range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select(); } } } me.undoManger && me.undoManger.save(); evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); } //trace:1634 //ff的del键在容器空的时候,也会删除 if(browser.gecko && keyCode == 46){ range = me.selection.getRange(); if(range.collapsed){ start = range.startContainer; if(domUtils.isEmptyBlock(start)){ var parent = start.parentNode; while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){ start = parent; parent = parent.parentNode; } if(start === parent.lastChild) evt.preventDefault(); return; } } } }); me.addListener('keyup', function(type, evt) { var keyCode = evt.keyCode || evt.which; //修复ie/chrome <strong><em>x|</em></strong> 当点退格后在输入文字后会出现 <b><i>x</i></b> if (!browser.gecko && !keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) { range = me.selection.getRange(); if (range.collapsed) { var start = range.startContainer, isFixed = 0; while (!domUtils.isBlockElm(start)) { if (start.nodeType == 1 && utils.indexOf(['FONT','B','I'], start.tagName) != -1) { var tmpNode = me.document.createElement(trans[start.tagName]); if (start.tagName == 'FONT') { //chrome only remember color property tmpNode.style.cssText = (start.getAttribute('size') ? 'font-size:' + (sizeMap[start.getAttribute('size')] || 12) + 'px' : '') + ';' + (start.getAttribute('color') ? 'color:' + start.getAttribute('color') : '') + ';' + (start.getAttribute('face') ? 'font-family:' + start.getAttribute('face') : '') + ';' + start.style.cssText; } while (start.firstChild) { tmpNode.appendChild(start.firstChild) } start.parentNode.insertBefore(tmpNode, start); domUtils.remove(start); if (!isFixed) { range.setEnd(tmpNode, tmpNode.childNodes.length).collapse(true) } start = tmpNode; isFixed = 1; } start = start.parentNode; } isFixed && range.select() } } if (keyCode == 8 ) {//|| keyCode == 46 //针对ff下在列表首行退格,不能删除空格行的问题 if(browser.gecko){ for(var i=0,li,lis = domUtils.getElementsByTagName(this.body,'li');li=lis[i++];){ if(domUtils.isEmptyNode(li) && !li.previousSibling){ var liOfPn = li.parentNode; domUtils.remove(li); if(domUtils.isEmptyNode(liOfPn)){ domUtils.remove(liOfPn) } } } } var range,start,parent, tds = this.currentSelectedArr; if (tds && tds.length > 0) { for (var i = 0,ti; ti = tds[i++];) { ti.innerHTML = browser.ie ? ( browser.version < 9 ? '&#65279' : '' ) : '<br/>'; } range = new dom.Range(this.document); range.setStart(tds[0], 0).setCursor(); if (flag) { me.undoManger.save(); flag = 0; } //阻止chrome执行默认的动作 if (browser.webkit) { evt.preventDefault(); } return; } range = me.selection.getRange(); //ctrl+a 后全部删除做处理 // // if (domUtils.isEmptyBlock(me.body) && !range.startOffset) { // //trace:1633 // me.body.innerHTML = '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>'; // range.setStart(me.body.firstChild,0).setCursor(false,true); // me.undoManger && me.undoManger.save(); // //todo 对性能会有影响 // browser.ie && me._selectionChange(); // return; // } //处理删除不干净的问题 start = range.startContainer; if(domUtils.isWhitespace(start)){ start = start.parentNode } //标志位防止空的p无法删除 var removeFlag = 0; while (start.nodeType == 1 && domUtils.isEmptyNode(start) && dtd.$removeEmpty[start.tagName]) { removeFlag = 1; parent = start.parentNode; domUtils.remove(start); start = parent; } if ( removeFlag && start.nodeType == 1 && domUtils.isEmptyNode(start)) { //ie下的问题,虽然没有了相应的节点但一旦你输入文字还是会自动把删除的节点加上, if (browser.ie) { var span = range.document.createElement('span'); start.appendChild(span); range.setStart(start,0).setCursor(); //for ie li = domUtils.findParentByTagName(start,'li',true); if(li){ var next = li.nextSibling; while(next){ if(domUtils.isEmptyBlock(next)){ li = next; next = next.nextSibling; domUtils.remove(li); continue; } break; } } } else { start.innerHTML = '<br/>'; range.setStart(start, 0).setCursor(false,true); } setTimeout(function() { if (browser.ie) { domUtils.remove(span); } if (flag) { me.undoManger.save(); flag = 0; } }, 0) } else { if (flag) { me.undoManger.save(); flag = 0; } } } }) };///import core ///commands 修复chrome下图片不能点击的问题 ///commandsName FixImgClick ///commandsTitle 修复chrome下图片不能点击的问题 //修复chrome下图片不能点击的问题 //todo 可以改大小 UE.plugins['fiximgclick'] = function() { var me = this; if ( browser.webkit ) { me.addListener( 'click', function( type, e ) { if ( e.target.tagName == 'IMG' ) { var range = new dom.Range( me.document ); range.selectNode( e.target ).select(); } } ) } };///import core ///commands 删除 ///commandsName Delete ///commandsTitle 删除 /** * 删除 * @function * @name baidu.editor.execCommand * @param {String} cmdName delete删除 */ UE.commands['delete'] = { execCommand : function (){ var range = this.selection.getRange(), mStart = 0, mEnd = 0, me = this; if(this.selectAll ){ //trace:1633 me.body.innerHTML = '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>'; range.setStart(me.body.firstChild,0).setCursor(false,true); me.selectAll = false; return; } if(me.currentSelectedArr && me.currentSelectedArr.length > 0){ for(var i=0,ci;ci=me.currentSelectedArr[i++];){ if(ci.style.display != 'none'){ ci.innerHTML = browser.ie ? domUtils.fillChar : '<br/>' } } range.setStart(me.currentSelectedArr[0],0).setCursor(); return; } if(range.collapsed) return; range.txtToElmBoundary(); //&& !domUtils.isBlockElm(range.startContainer) while(!range.startOffset && !domUtils.isBody(range.startContainer) && !dtd.$tableContent[range.startContainer.tagName] ){ mStart = 1; range.setStartBefore(range.startContainer); } //&& !domUtils.isBlockElm(range.endContainer) while(!domUtils.isBody(range.endContainer)&& !dtd.$tableContent[range.endContainer.tagName] ){ var child,endContainer = range.endContainer,endOffset = range.endOffset; // if(endContainer.nodeType == 3 && endOffset == endContainer.nodeValue.length){ // range.setEndAfter(endContainer); // continue; // } child = endContainer.childNodes[endOffset]; if(!child || domUtils.isBr(child) && endContainer.lastChild === child){ range.setEndAfter(endContainer); continue; } break; } if(mStart){ var start = me.document.createElement('span'); start.innerHTML = 'start'; start.id = '_baidu_cut_start'; range.insertNode(start).setStartBefore(start) } if(mEnd){ var end = me.document.createElement('span'); end.innerHTML = 'end'; end.id = '_baidu_cut_end'; range.cloneRange().collapse(false).insertNode(end); range.setEndAfter(end) } range.deleteContents(); if(domUtils.isBody(range.startContainer) && domUtils.isEmptyBlock(me.body)){ me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>'; range.setStart(me.body.firstChild,0).collapse(true); }else if ( !browser.ie && domUtils.isEmptyBlock(range.startContainer)){ range.startContainer.innerHTML = '<br/>' } range.select(true) }, queryCommandState : function(){ if(this.currentSelectedArr && this.currentSelectedArr.length > 0){ return 0; } return this.highlight || this.selection.getRange().collapsed ? -1 : 0; } }; ///import core ///commands 快捷键 ///commandsName ShortCutKeys ///commandsTitle 快捷键 //配置快捷键 UE.plugins['shortcutkeys'] = function(){ var me = this, shortcutkeys = utils.extend({ "ctrl+66" : "Bold" //^B ,"ctrl+90" : "Undo" //undo ,"ctrl+89" : "Redo" //redo ,"ctrl+73" : "Italic" //^I ,"ctrl+85" : "Underline" //^U ,"ctrl+shift+67" : "removeformat" //清除格式 ,"ctrl+shift+76" : "justify:left" //居左 ,"ctrl+shift+82" : "justify:right" //居右 ,"ctrl+65" : "selectAll" // ,"9" : "indent" //tab },me.options.shortcutkeys); me.addListener('keydown',function(type,e){ var keyCode = e.keyCode || e.which,value; for ( var i in shortcutkeys ) { if ( /^(ctrl)(\+shift)?\+(\d+)$/.test( i.toLowerCase() ) || /^(\d+)$/.test( i ) ) { if ( ( (RegExp.$1 == 'ctrl' ? (e.ctrlKey||e.metaKey) : 0) && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1) && keyCode == RegExp.$3 ) || keyCode == RegExp.$1 ){ value = shortcutkeys[i].split(':'); me.execCommand( value[0],value[1]); domUtils.preventDefault(e) } } } }); };var baidu = baidu || {}; baidu.editor = baidu.editor || {}; baidu.editor.ui = {};(function (){ var browser = baidu.editor.browser, domUtils = baidu.editor.dom.domUtils; var magic = '$EDITORUI'; var root = window[magic] = {}; var uidMagic = 'ID' + magic; var uidCount = 0; var uiUtils = baidu.editor.ui.uiUtils = { uid: function (obj){ return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount); }, hook: function ( fn, callback ) { var dg; if (fn && fn._callbacks) { dg = fn; } else { dg = function (){ var q; if (fn) { q = fn.apply(this, arguments); } var callbacks = dg._callbacks; var k = callbacks.length; while (k --) { var r = callbacks[k].apply(this, arguments); if (q === undefined) { q = r; } } return q; }; dg._callbacks = []; } dg._callbacks.push(callback); return dg; }, createElementByHtml: function (html){ var el = document.createElement('div'); el.innerHTML = html; el = el.firstChild; el.parentNode.removeChild(el); return el; }, getViewportElement: function (){ return (browser.ie && browser.quirks) ? document.body : document.documentElement; }, getClientRect: function (element){ var bcr = element.getBoundingClientRect(); var rect = { left: Math.round(bcr.left), top: Math.round(bcr.top), height: Math.round(bcr.bottom - bcr.top), width: Math.round(bcr.right - bcr.left) }; var doc; while ((doc = element.ownerDocument) !== document && (element = domUtils.getWindow(doc).frameElement)) { bcr = element.getBoundingClientRect(); rect.left += bcr.left; rect.top += bcr.top; } rect.bottom = rect.top + rect.height; rect.right = rect.left + rect.width; return rect; }, getViewportRect: function (){ var viewportEl = uiUtils.getViewportElement(); var width = (window.innerWidth || viewportEl.clientWidth) | 0; var height = (window.innerHeight ||viewportEl.clientHeight) | 0; return { left: 0, top: 0, height: height, width: width, bottom: height, right: width }; }, setViewportOffset: function (element, offset){ var rect; var fixedLayer = uiUtils.getFixedLayer(); if (element.parentNode === fixedLayer) { element.style.left = offset.left + 'px'; element.style.top = offset.top + 'px'; } else { domUtils.setViewportOffset(element, offset); } }, getEventOffset: function (evt){ var el = evt.target || evt.srcElement; var rect = uiUtils.getClientRect(el); var offset = uiUtils.getViewportOffsetByEvent(evt); return { left: offset.left - rect.left, top: offset.top - rect.top }; }, getViewportOffsetByEvent: function (evt){ var el = evt.target || evt.srcElement; var frameEl = domUtils.getWindow(el).frameElement; var offset = { left: evt.clientX, top: evt.clientY }; if (frameEl && el.ownerDocument !== document) { var rect = uiUtils.getClientRect(frameEl); offset.left += rect.left; offset.top += rect.top; } return offset; }, setGlobal: function (id, obj){ root[id] = obj; return magic + '["' + id + '"]'; }, unsetGlobal: function (id){ delete root[id]; }, copyAttributes: function (tgt, src){ var attributes = src.attributes; var k = attributes.length; while (k --) { var attrNode = attributes[k]; if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) { tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue); } } if (src.className) { tgt.className += ' ' + src.className; } if (src.style.cssText) { tgt.style.cssText += ';' + src.style.cssText; } }, removeStyle: function (el, styleName){ if (el.style.removeProperty) { el.style.removeProperty(styleName); } else if (el.style.removeAttribute) { el.style.removeAttribute(styleName); } else throw ''; }, contains: function (elA, elB){ return elA && elB && (elA === elB ? false : ( elA.contains ? elA.contains(elB) : elA.compareDocumentPosition(elB) & 16 )); }, startDrag: function (evt, callbacks,doc){ var doc = doc || document; var startX = evt.clientX; var startY = evt.clientY; function handleMouseMove(evt){ var x = evt.clientX - startX; var y = evt.clientY - startY; callbacks.ondragmove(x, y); if (evt.stopPropagation) { evt.stopPropagation(); } else { evt.cancelBubble = true; } } if (doc.addEventListener) { function handleMouseUp(evt){ doc.removeEventListener('mousemove', handleMouseMove, true); doc.removeEventListener('mouseup', handleMouseMove, true); callbacks.ondragstop(); } doc.addEventListener('mousemove', handleMouseMove, true); doc.addEventListener('mouseup', handleMouseUp, true); evt.preventDefault(); } else { var elm = evt.srcElement; elm.setCapture(); function releaseCaptrue(){ elm.releaseCapture(); elm.detachEvent('onmousemove', handleMouseMove); elm.detachEvent('onmouseup', releaseCaptrue); elm.detachEvent('onlosecaptrue', releaseCaptrue); callbacks.ondragstop(); } elm.attachEvent('onmousemove', handleMouseMove); elm.attachEvent('onmouseup', releaseCaptrue); elm.attachEvent('onlosecaptrue', releaseCaptrue); evt.returnValue = false; } callbacks.ondragstart(); }, getFixedLayer: function (){ var layer = document.getElementById('edui_fixedlayer'); if (layer == null) { layer = document.createElement('div'); layer.id = 'edui_fixedlayer'; document.body.appendChild(layer); if (browser.ie && browser.version <= 8) { layer.style.position = 'absolute'; bindFixedLayer(); setTimeout(updateFixedOffset); } else { layer.style.position = 'fixed'; } layer.style.left = '0'; layer.style.top = '0'; layer.style.width = '0'; layer.style.height = '0'; } return layer; }, makeUnselectable: function (element){ if (browser.opera || (browser.ie && browser.version < 9)) { element.unselectable = 'on'; if (element.hasChildNodes()) { for (var i=0; i<element.childNodes.length; i++) { if (element.childNodes[i].nodeType == 1) { uiUtils.makeUnselectable(element.childNodes[i]); } } } } else { if (element.style.MozUserSelect !== undefined) { element.style.MozUserSelect = 'none'; } else if (element.style.WebkitUserSelect !== undefined) { element.style.WebkitUserSelect = 'none'; } else if (element.style.KhtmlUserSelect !== undefined) { element.style.KhtmlUserSelect = 'none'; } } } }; function updateFixedOffset(){ var layer = document.getElementById('edui_fixedlayer'); uiUtils.setViewportOffset(layer, { left: 0, top: 0 }); // layer.style.display = 'none'; // layer.style.display = 'block'; //#trace: 1354 // setTimeout(updateFixedOffset); } function bindFixedLayer(adjOffset){ domUtils.on(window, 'scroll', updateFixedOffset); domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true)); } })(); (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, EventBase = baidu.editor.EventBase, UIBase = baidu.editor.ui.UIBase = function (){}; UIBase.prototype = { className: '', uiName: '', initOptions: function (options){ var me = this; for (var k in options) { me[k] = options[k]; } this.id = this.id || 'edui' + uiUtils.uid(); }, initUIBase: function (){ this._globalKey = utils.unhtml( uiUtils.setGlobal(this.id, this) ); }, render: function (holder){ var html = this.renderHtml(); var el = uiUtils.createElementByHtml(html); var seatEl = this.getDom(); if (seatEl != null) { seatEl.parentNode.replaceChild(el, seatEl); uiUtils.copyAttributes(el, seatEl); } else { if (typeof holder == 'string') { holder = document.getElementById(holder); } holder = holder || uiUtils.getFixedLayer(); holder.appendChild(el); } this.postRender(); }, getDom: function (name){ if (!name) { return document.getElementById( this.id ); } else { return document.getElementById( this.id + '_' + name ); } }, postRender: function (){ this.fireEvent('postrender'); }, getHtmlTpl: function (){ return ''; }, formatHtml: function (tpl){ var prefix = 'edui-' + this.uiName; return (tpl .replace(/##/g, this.id) .replace(/%%-/g, this.uiName ? prefix + '-' : '') .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className) .replace(/\$\$/g, this._globalKey)); }, renderHtml: function (){ return this.formatHtml(this.getHtmlTpl()); }, dispose: function (){ var box = this.getDom(); if (box) baidu.editor.dom.domUtils.remove( box ); uiUtils.unsetGlobal(this.id); } }; utils.inherits(UIBase, EventBase); })(); (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Separator = baidu.editor.ui.Separator = function (options){ this.initOptions(options); this.initSeparator(); }; Separator.prototype = { uiName: 'separator', initSeparator: function (){ this.initUIBase(); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%"></div>'; } }; utils.inherits(Separator, UIBase); })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, uiUtils = baidu.editor.ui.uiUtils; var Mask = baidu.editor.ui.Mask = function (options){ this.initOptions(options); this.initUIBase(); }; Mask.prototype = { getHtmlTpl: function (){ return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>'; }, postRender: function (){ var me = this; domUtils.on(window, 'resize', function (){ setTimeout(function (){ if (!me.isHidden()) { me._fill(); } }); }); }, show: function (zIndex){ this._fill(); this.getDom().style.display = ''; this.getDom().style.zIndex = zIndex; }, hide: function (){ this.getDom().style.display = 'none'; this.getDom().style.zIndex = ''; }, isHidden: function (){ return this.getDom().style.display == 'none'; }, _onMouseDown: function (){ return false; }, _fill: function (){ var el = this.getDom(); var vpRect = uiUtils.getViewportRect(); el.style.width = vpRect.width + 'px'; el.style.height = vpRect.height + 'px'; } }; utils.inherits(Mask, UIBase); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, Popup = baidu.editor.ui.Popup = function (options){ this.initOptions(options); this.initPopup(); }; var allPopups = []; function closeAllPopup( el ){ var newAll = []; for ( var i = 0; i < allPopups.length; i++ ) { var pop = allPopups[i]; if (!pop.isHidden()) { if (pop.queryAutoHide(el) !== false) { pop.hide(); } } } } Popup.postHide = closeAllPopup; var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright', 'edui-anchor-bottomleft','edui-anchor-bottomright']; Popup.prototype = { SHADOW_RADIUS: 5, content: null, _hidden: false, autoRender: true, canSideLeft: true, canSideUp: true, initPopup: function (){ this.initUIBase(); allPopups.push( this ); }, getHtmlTpl: function (){ return '<div id="##" class="edui-popup %%">' + ' <div id="##_body" class="edui-popup-body">' + ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: white;" frameborder="0" width="100%" height="100%" src="javascript:"></iframe>' + ' <div class="edui-shadow"></div>' + ' <div id="##_content" class="edui-popup-content">' + this.getContentHtmlTpl() + ' </div>' + ' </div>' + '</div>'; }, getContentHtmlTpl: function (){ if (typeof this.content == 'string') { return this.content; } return this.content.renderHtml(); }, _UIBase_postRender: UIBase.prototype.postRender, postRender: function (){ if (this.content instanceof UIBase) { this.content.postRender(); } this.fireEvent('postRenderAfter'); this.hide(true); this._UIBase_postRender(); }, _doAutoRender: function (){ if (!this.getDom() && this.autoRender) { this.render(); } }, mesureSize: function (){ var box = this.getDom('content'); return uiUtils.getClientRect(box); }, fitSize: function (){ var popBodyEl = this.getDom('body'); popBodyEl.style.width = ''; popBodyEl.style.height = ''; var size = this.mesureSize(); popBodyEl.style.width = size.width + 'px'; popBodyEl.style.height = size.height + 'px'; return size; }, showAnchor: function ( element, hoz ){ this.showAnchorRect( uiUtils.getClientRect( element ), hoz ); }, showAnchorRect: function ( rect, hoz, adj ){ this._doAutoRender(); var vpRect = uiUtils.getViewportRect(); this._show(); var popSize = this.fitSize(); var sideLeft, sideUp, left, top; if (hoz) { sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width); sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height); left = (sideLeft ? rect.left - popSize.width : rect.right); top = (sideUp ? rect.bottom - popSize.height : rect.top); } else { sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width); sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height); left = (sideLeft ? rect.right - popSize.width : rect.left); top = (sideUp ? rect.top - popSize.height : rect.bottom); } var popEl = this.getDom(); uiUtils.setViewportOffset(popEl, { left: left, top: top }); domUtils.removeClasses(popEl, ANCHOR_CLASSES); popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)]; if(this.editor){ popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10; baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1; } }, showAt: function (offset) { var left = offset.left; var top = offset.top; var rect = { left: left, top: top, right: left, bottom: top, height: 0, width: 0 }; this.showAnchorRect(rect, false, true); }, _show: function (){ if (this._hidden) { var box = this.getDom(); box.style.display = ''; this._hidden = false; // if (box.setActive) { // box.setActive(); // } this.fireEvent('show'); } }, isHidden: function (){ return this._hidden; }, show: function (){ this._doAutoRender(); this._show(); }, hide: function (notNofity){ if (!this._hidden && this.getDom()) { // this.getDom().style.visibility = 'hidden'; this.getDom().style.display = 'none'; this._hidden = true; if (!notNofity) { this.fireEvent('hide'); } } }, queryAutoHide: function (el){ return !el || !uiUtils.contains(this.getDom(), el); } }; utils.inherits(Popup, UIBase); domUtils.on( document, 'mousedown', function ( evt ) { var el = evt.target || evt.srcElement; closeAllPopup( el ); } ); domUtils.on( window, 'scroll', function () { closeAllPopup(); } ); // var lastVpRect = uiUtils.getViewportRect(); // domUtils.on( window, 'resize', function () { // var vpRect = uiUtils.getViewportRect(); // if (vpRect.width != lastVpRect.width || vpRect.height != lastVpRect.height) { // closeAllPopup(); // } // } ); })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, ColorPicker = baidu.editor.ui.ColorPicker = function (options){ this.initOptions(options); this.noColorText = this.noColorText || '不设置颜色'; this.initUIBase(); }; ColorPicker.prototype = { getHtmlTpl: function (){ return genColorPicker( this.noColorText ); }, _onTableClick: function (evt){ var tgt = evt.target || evt.srcElement; var color = tgt.getAttribute('data-color'); if (color) { this.fireEvent('pickcolor', color); } }, _onTableOver: function (evt){ var tgt = evt.target || evt.srcElement; var color = tgt.getAttribute('data-color'); if (color) { this.getDom('preview').style.backgroundColor = color; } }, _onTableOut: function (){ this.getDom('preview').style.backgroundColor = ''; }, _onPickNoColor: function (){ this.fireEvent('picknocolor'); } }; utils.inherits(ColorPicker, UIBase); var COLORS = ( 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' + 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' + 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' + 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' + 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' + '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' + 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(','); function genColorPicker(noColorText){ var html = '<div id="##" class="edui-colorpicker %%">' + '<div class="edui-colorpicker-topbar edui-clearfix">' + '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' + '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' + '</div>' + '<table class="edui-box" style="border-collapse: collapse;" onmouseover="$$._onTableOver(event, this);" onmouseout="$$._onTableOut(event, this);" onclick="return $$._onTableClick(event, this);" cellspacing="0" cellpadding="0">' + '<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#366092;padding-top: 2px"><td colspan="10">主题颜色</td> </tr>'+ '<tr class="edui-colorpicker-tablefirstrow" >'; for (var i=0; i<COLORS.length; i++) { if (i && i%10 === 0) { html += '</tr>'+(i==60?'<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#366092;"><td colspan="10">标准颜色</td></tr>':'')+'<tr'+(i==60?' class="edui-colorpicker-tablefirstrow"':'')+'>'; } html += i<70 ? '<td style="padding: 0 2px;"><a hidefocus title="'+COLORS[i]+'" onclick="return false;" href="javascript:" unselectable="on" class="edui-box edui-colorpicker-colorcell"' + ' data-color="#'+ COLORS[i] +'"'+ ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+ (i<10 || i>=60?'border-width:1px;': i>=10&&i<20?'border-width:1px 1px 0 1px;': 'border-width:0 1px 0 1px;')+ '"' + '></a></td>':''; } html += '</tr></table></div>'; return html; } })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase; var TablePicker = baidu.editor.ui.TablePicker = function (options){ this.initOptions(options); this.initTablePicker(); }; TablePicker.prototype = { defaultNumRows: 10, defaultNumCols: 10, maxNumRows: 20, maxNumCols: 20, numRows: 10, numCols: 10, lengthOfCellSide: 22, initTablePicker: function (){ this.initUIBase(); }, getHtmlTpl: function (){ return '<div id="##" class="edui-tablepicker %%">' + '<div class="edui-tablepicker-body">' + '<div class="edui-infoarea">' + '<span id="##_label" class="edui-label"></span>' + '<span class="edui-clickable" onclick="$$._onMore();">更多</span>' + '</div>' + '<div class="edui-pickarea"' + ' onmousemove="$$._onMouseMove(event, this);"' + ' onmouseover="$$._onMouseOver(event, this);"' + ' onmouseout="$$._onMouseOut(event, this);"' + ' onclick="$$._onClick(event, this);"' + '>' + '<div id="##_overlay" class="edui-overlay"></div>' + '</div>' + '</div>' + '</div>'; }, _UIBase_render: UIBase.prototype.render, render: function (holder){ this._UIBase_render(holder); this.getDom('label').innerHTML = '0列 x 0行'; }, _track: function (numCols, numRows){ var style = this.getDom('overlay').style; var sideLen = this.lengthOfCellSide; style.width = numCols * sideLen + 'px'; style.height = numRows * sideLen + 'px'; var label = this.getDom('label'); label.innerHTML = numCols + '列 x ' + numRows + '行'; this.numCols = numCols; this.numRows = numRows; }, _onMouseOver: function (evt, el){ var rel = evt.relatedTarget || evt.fromElement; if (!uiUtils.contains(el, rel) && el !== rel) { this.getDom('label').innerHTML = '0列 x 0行'; this.getDom('overlay').style.visibility = ''; } }, _onMouseOut: function (evt, el){ var rel = evt.relatedTarget || evt.toElement; if (!uiUtils.contains(el, rel) && el !== rel) { this.getDom('label').innerHTML = '0列 x 0行'; this.getDom('overlay').style.visibility = 'hidden'; } }, _onMouseMove: function (evt, el){ var style = this.getDom('overlay').style; var offset = uiUtils.getEventOffset(evt); var sideLen = this.lengthOfCellSide; var numCols = Math.ceil(offset.left / sideLen); var numRows = Math.ceil(offset.top / sideLen); this._track(numCols, numRows); }, _onClick: function (){ this.fireEvent('picktable', this.numCols, this.numRows); }, _onMore: function (){ this.fireEvent('more'); } }; utils.inherits(TablePicker, UIBase); })(); (function (){ var browser = baidu.editor.browser, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils; var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' + ' onmouseup="$$.Stateful_onMouseUp(event, this);"' + ( browser.ie ? ( ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' + ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' ) : ( ' onmouseover="$$.Stateful_onMouseOver(event, this);"' + ' onmouseout="$$.Stateful_onMouseOut(event, this);"' )); baidu.editor.ui.Stateful = { alwalysHoverable: false, Stateful_init: function (){ this._Stateful_dGetHtmlTpl = this.getHtmlTpl; this.getHtmlTpl = this.Stateful_getHtmlTpl; }, Stateful_getHtmlTpl: function (){ var tpl = this._Stateful_dGetHtmlTpl(); // 使用function避免$转义 return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; }); }, Stateful_onMouseEnter: function (evt, el){ if (!this.isDisabled() || this.alwalysHoverable) { this.addState('hover'); this.fireEvent('over'); } }, Stateful_onMouseLeave: function (evt, el){ if (!this.isDisabled() || this.alwalysHoverable) { this.removeState('hover'); this.removeState('active'); this.fireEvent('out'); } }, Stateful_onMouseOver: function (evt, el){ var rel = evt.relatedTarget; if (!uiUtils.contains(el, rel) && el !== rel) { this.Stateful_onMouseEnter(evt, el); } }, Stateful_onMouseOut: function (evt, el){ var rel = evt.relatedTarget; if (!uiUtils.contains(el, rel) && el !== rel) { this.Stateful_onMouseLeave(evt, el); } }, Stateful_onMouseDown: function (evt, el){ if (!this.isDisabled()) { this.addState('active'); } }, Stateful_onMouseUp: function (evt, el){ if (!this.isDisabled()) { this.removeState('active'); } }, Stateful_postRender: function (){ if (this.disabled && !this.hasState('disabled')) { this.addState('disabled'); } }, hasState: function (state){ return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state); }, addState: function (state){ if (!this.hasState(state)) { this.getStateDom().className += ' edui-state-' + state; } }, removeState: function (state){ if (this.hasState(state)) { domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]); } }, getStateDom: function (){ return this.getDom('state'); }, isChecked: function (){ return this.hasState('checked'); }, setChecked: function (checked){ if (!this.isDisabled() && checked) { this.addState('checked'); } else { this.removeState('checked'); } }, isDisabled: function (){ return this.hasState('disabled'); }, setDisabled: function (disabled){ if (disabled) { this.removeState('hover'); this.removeState('checked'); this.removeState('active'); this.addState('disabled'); } else { this.removeState('disabled'); } } }; })(); ///import core ///import uicore ///import ui/stateful.js (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Stateful = baidu.editor.ui.Stateful, Button = baidu.editor.ui.Button = function (options){ this.initOptions(options); this.initButton(); }; Button.prototype = { uiName: 'button', label: '', title: '', showIcon: true, showText: true, initButton: function (){ this.initUIBase(); this.Stateful_init(); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%">' + '<div id="##_state" stateful>' + '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') + ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' + (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') + (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') + '</div>' + '</div>' + '</div></div>'; }, postRender: function (){ this.Stateful_postRender(); }, _onClick: function (){ if (!this.isDisabled()) { this.fireEvent('click'); } } }; utils.inherits(Button, UIBase); utils.extend(Button.prototype, Stateful); })(); ///import core ///import uicore ///import ui/stateful.js (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, Stateful = baidu.editor.ui.Stateful, SplitButton = baidu.editor.ui.SplitButton = function (options){ this.initOptions(options); this.initSplitButton(); }; SplitButton.prototype = { popup: null, uiName: 'splitbutton', title: '', initSplitButton: function (){ this.initUIBase(); this.Stateful_init(); var me = this; if (this.popup != null) { var popup = this.popup; this.popup = null; this.setPopup(popup); } }, _UIBase_postRender: UIBase.prototype.postRender, postRender: function (){ this.Stateful_postRender(); this._UIBase_postRender(); }, setPopup: function (popup){ if (this.popup === popup) return; if (this.popup != null) { this.popup.dispose(); } popup.addListener('show', utils.bind(this._onPopupShow, this)); popup.addListener('hide', utils.bind(this._onPopupHide, this)); popup.addListener('postrender', utils.bind(function (){ popup.getDom('body').appendChild( uiUtils.createElementByHtml('<div id="' + this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' + (uiUtils.getClientRect(this.getDom()).width - 2) + 'px"></div>') ); popup.getDom().className += ' ' + this.className; }, this)); this.popup = popup; }, _onPopupShow: function (){ this.addState('opened'); }, _onPopupHide: function (){ this.removeState('opened'); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%">' + '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' + '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' + '<div class="edui-box edui-icon"></div>' + '</div>' + '<div class="edui-box edui-splitborder"></div>' + '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' + '</div></div></div>'; }, showPopup: function (){ // 当popup往上弹出的时候,做特殊处理 var rect = uiUtils.getClientRect(this.getDom()); rect.top -= this.popup.SHADOW_RADIUS; rect.height += this.popup.SHADOW_RADIUS; this.popup.showAnchorRect(rect); }, _onArrowClick: function (event, el){ if (!this.isDisabled()) { this.showPopup(); } }, _onButtonClick: function (){ if (!this.isDisabled()) { this.fireEvent('buttonclick'); } } }; utils.inherits(SplitButton, UIBase); utils.extend(SplitButton.prototype, Stateful, true); })(); ///import core ///import uicore ///import ui/colorpicker.js ///import ui/popup.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, ColorPicker = baidu.editor.ui.ColorPicker, Popup = baidu.editor.ui.Popup, SplitButton = baidu.editor.ui.SplitButton, ColorButton = baidu.editor.ui.ColorButton = function (options){ this.initOptions(options); this.initColorButton(); }; ColorButton.prototype = { initColorButton: function (){ var me = this; this.popup = new Popup({ content: new ColorPicker({ noColorText: '清除颜色', onpickcolor: function (t, color){ me._onPickColor(color); }, onpicknocolor: function (t, color){ me._onPickNoColor(color); } }), editor:me.editor }); this.initSplitButton(); }, _SplitButton_postRender: SplitButton.prototype.postRender, postRender: function (){ this._SplitButton_postRender(); this.getDom('button_body').appendChild( uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>') ); this.getDom().className += ' edui-colorbutton'; }, setColor: function (color){ this.getDom('colorlump').style.backgroundColor = color; this.color = color; }, _onPickColor: function (color){ if (this.fireEvent('pickcolor', color) !== false) { this.setColor(color); this.popup.hide(); } }, _onPickNoColor: function (color){ if (this.fireEvent('picknocolor') !== false) { this.popup.hide(); } } }; utils.inherits(ColorButton, SplitButton); })(); ///import core ///import uicore ///import ui/popup.js ///import ui/tablepicker.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, TablePicker = baidu.editor.ui.TablePicker, SplitButton = baidu.editor.ui.SplitButton, TableButton = baidu.editor.ui.TableButton = function (options){ this.initOptions(options); this.initTableButton(); }; TableButton.prototype = { initTableButton: function (){ var me = this; this.popup = new Popup({ content: new TablePicker({ onpicktable: function (t, numCols, numRows){ me._onPickTable(numCols, numRows); }, onmore: function (){ me.popup.hide(); me.fireEvent('more'); } }), 'editor':me.editor }); this.initSplitButton(); }, _onPickTable: function (numCols, numRows){ if (this.fireEvent('picktable', numCols, numRows) !== false) { this.popup.hide(); } } }; utils.inherits(TableButton, SplitButton); })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase; var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options){ this.initOptions(options); this.initAutoTypeSetPicker(); }; AutoTypeSetPicker.prototype = { initAutoTypeSetPicker: function (){ this.initUIBase(); }, getHtmlTpl: function (){ var options = this.editor.options, opt = options.autotypeset; for(var i = 0,lineStr = [],li,lis = options.listMap.lineheight;li=lis[i++];){ lineStr.push('<option value="'+li+'" '+(opt["lineHeight"] == li ? 'checked' : '')+'>'+li+'</option>'); } return '<div id="##" class="edui-autotypesetpicker %%">' + '<div class="edui-autotypesetpicker-body">' + '<table >' + '<tr><td colspan="2"><input type="checkbox" name="mergeEmptyline" '+ (opt["mergeEmptyline"] ? "checked" : "" )+'>合并空行</td><td colspan="2"><input type="checkbox" name="removeEmptyline" '+ (opt["removeEmptyline"] ? "checked" : "" )+'>删除空行</td></tr>'+ '<tr><td colspan="2"><input type="checkbox" name="removeClass" '+ (opt["removeClass"] ? "checked" : "" )+'>清除样式</td><td colspan="2"><input type="checkbox" name="indent" '+ (opt["indent"] ? "checked" : "" )+'>首行缩进2字</td></tr>'+ '<tr><td colspan="2"><input type="checkbox" name="textAlign" '+ (opt["textAlign"] ? "checked" : "" )+'>对齐方式:</td><td colspan="2" id="textAlignValue"><input type="radio" name="textAlignValue" value="left" '+((opt["textAlign"]&&opt["textAlign"]=="left") ? "checked" : "")+'>左对齐<input type="radio" name="textAlignValue" value="center" '+((opt["textAlign"]&&opt["textAlign"]=="center") ? "checked" : "")+'>居中对齐<input type="radio" name="textAlignValue" value="right" '+((opt["textAlign"]&&opt["textAlign"]=="right") ? "checked" : "")+'>右对齐 </tr>'+ '<tr><td colspan="2"><input type="checkbox" name="imageBlockLine" '+ (opt["imageBlockLine"] ? "checked" : "" )+'>图片浮动</td>' + '<td colspan="2" id="imageBlockLineValue">' + '<input type="radio" name="imageBlockLineValue" value="none" '+((opt["imageBlockLine"]&&opt["imageBlockLine"]=="none") ? "checked" : "")+'>默认' + '<input type="radio" name="imageBlockLineValue" value="left" '+((opt["imageBlockLine"]&&opt["imageBlockLine"]=="left") ? "checked" : "")+'>左浮动' + '<input type="radio" name="imageBlockLineValue" value="center" '+((opt["imageBlockLine"]&&opt["imageBlockLine"]=="center") ? "checked" : "")+'>独占行居中' + '<input type="radio" name="imageBlockLineValue" value="right" '+((opt["imageBlockLine"]&&opt["imageBlockLine"]=="right") ? "checked" : "")+'>右浮动</tr>'+ '<tr><td colspan="2"><input type="checkbox" name="clearFontSize" '+ (opt["clearFontSize"] ? "checked" : "" )+'>清除字号</td><td colspan="2"><input type="checkbox" name="clearFontFamily" '+ (opt["clearFontFamily"] ? "checked" : "" )+'>清除字体</td></tr>'+ '<tr><td colspan="4"><input type="checkbox" name="removeEmptyNode" '+ (opt["removeEmptyNode"] ? "checked" : "" )+'>去掉冗余的html代码</td></tr>'+ '<tr><td colspan="4"><input type="checkbox" name="pasteFilter" '+ (opt["pasteFilter"] ? "checked" : "" )+'>粘贴过滤 (对每次粘贴的内容应用以上过滤规则)</td></tr>'+ '<tr><td colspan="4" align="right"><button >执行</button></td></tr>'+ '</table>'+ '</div>' + '</div>'; }, _UIBase_render: UIBase.prototype.render }; utils.inherits(AutoTypeSetPicker, UIBase); })(); ///import core ///import uicore ///import ui/popup.js ///import ui/autotypesetpicker.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker, SplitButton = baidu.editor.ui.SplitButton, AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){ this.initOptions(options); this.initAutoTypeSetButton(); }; function getPara(me){ var opt = me.editor.options.autotypeset, cont = me.getDom(), ipts = domUtils.getElementsByTagName(cont,"input"); for(var i=ipts.length-1,ipt;ipt=ipts[i--];){ if(ipt.getAttribute("type")=="checkbox"){ var attrName = ipt.getAttribute("name"); opt[attrName] && delete opt[attrName]; if(ipt.checked){ var attrValue = document.getElementById(attrName+"Value"); if(attrValue){ if(/input/ig.test(attrValue.tagName)){ opt[attrName] = attrValue.value; }else{ var iptChilds = attrValue.getElementsByTagName("input"); for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){ if(iptchild.checked){ opt[attrName] = iptchild.value; break; } } } }else{ opt[attrName] = true; } } } } var selects = domUtils.getElementsByTagName(cont,"select"); for(var i=0,si;si=selects[i++];){ var attr = si.getAttribute('name'); opt[attr] = opt[attr] ? si.value : ''; } me.editor.options.autotypeset = opt; } AutoTypeSetButton.prototype = { initAutoTypeSetButton: function (){ var me = this; this.popup = new Popup({ //传入配置参数 content: new AutoTypeSetPicker({editor:me.editor}), 'editor':me.editor, hide : function(){ if (!this._hidden && this.getDom()) { getPara(this); this.getDom().style.display = 'none'; this._hidden = true; this.fireEvent('hide'); } } }); var flag = 0; this.popup.addListener('postRenderAfter',function(){ var popupUI = this; if(flag)return; var cont = this.getDom(), btn = cont.getElementsByTagName('button')[0]; btn.onclick = function(){ getPara(popupUI); me.editor.execCommand('autotypeset') }; flag = 1; }); this.initSplitButton(); } }; utils.inherits(AutoTypeSetButton, SplitButton); })(); (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, Toolbar = baidu.editor.ui.Toolbar = function (options){ this.initOptions(options); this.initToolbar(); }; Toolbar.prototype = { items: null, initToolbar: function (){ this.items = this.items || []; this.initUIBase(); }, add: function (item){ this.items.push(item); }, getHtmlTpl: function (){ var buff = []; for (var i=0; i<this.items.length; i++) { buff[i] = this.items[i].renderHtml(); } return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' + buff.join('') + '</div>' }, postRender: function (){ var box = this.getDom(); for (var i=0; i<this.items.length; i++) { this.items[i].postRender(); } uiUtils.makeUnselectable(box); }, _onMouseDown: function (){ return false; } }; utils.inherits(Toolbar, UIBase); })(); ///import core ///import uicore ///import ui\popup.js ///import ui\stateful.js (function (){ var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, Popup = baidu.editor.ui.Popup, Stateful = baidu.editor.ui.Stateful, Menu = baidu.editor.ui.Menu = function (options){ this.initOptions(options); this.initMenu(); }; var menuSeparator = { renderHtml: function (){ return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>'; }, postRender: function (){}, queryAutoHide: function (){ return true; } }; Menu.prototype = { items: null, uiName: 'menu', initMenu: function (){ this.items = this.items || []; this.initPopup(); this.initItems(); }, initItems: function (){ for (var i=0; i<this.items.length; i++) { var item = this.items[i]; if (item == '-') { this.items[i] = this.getSeparator(); } else if (!(item instanceof MenuItem)) { this.items[i] = this.createItem(item); } } }, getSeparator: function (){ return menuSeparator; }, createItem: function (item){ return new MenuItem(item); }, _Popup_getContentHtmlTpl: Popup.prototype.getContentHtmlTpl, getContentHtmlTpl: function (){ if (this.items.length == 0) { return this._Popup_getContentHtmlTpl(); } var buff = []; for (var i=0; i<this.items.length; i++) { var item = this.items[i]; buff[i] = item.renderHtml(); } return ('<div class="%%-body">' + buff.join('') + '</div>'); }, _Popup_postRender: Popup.prototype.postRender, postRender: function (){ var me = this; for (var i=0; i<this.items.length; i++) { var item = this.items[i]; item.ownerMenu = this; item.postRender(); } domUtils.on(this.getDom(), 'mouseover', function (evt){ evt = evt || event; var rel = evt.relatedTarget || evt.fromElement; var el = me.getDom(); if (!uiUtils.contains(el, rel) && el !== rel) { me.fireEvent('over'); } }); this._Popup_postRender(); }, queryAutoHide: function (el){ if (el) { if (uiUtils.contains(this.getDom(), el)) { return false; } for (var i=0; i<this.items.length; i++) { var item = this.items[i]; if (item.queryAutoHide(el) === false) { return false; } } } }, clearItems: function (){ for (var i=0; i<this.items.length; i++) { var item = this.items[i]; clearTimeout(item._showingTimer); clearTimeout(item._closingTimer); if (item.subMenu) { item.subMenu.destroy(); } } this.items = []; }, destroy: function (){ if (this.getDom()) { domUtils.remove(this.getDom()); } this.clearItems(); }, dispose: function (){ this.destroy(); } }; utils.inherits(Menu, Popup); var MenuItem = baidu.editor.ui.MenuItem = function (options){ this.initOptions(options); this.initUIBase(); this.Stateful_init(); if (this.subMenu && !(this.subMenu instanceof Menu)) { this.subMenu = new Menu(this.subMenu); } }; MenuItem.prototype = { label: '', subMenu: null, ownerMenu: null, uiName: 'menuitem', alwalysHoverable: true, getHtmlTpl: function (){ return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' + '<div class="%%-body">' + this.renderLabelHtml() + '</div>' + '</div>'; }, postRender: function (){ var me = this; this.addListener('over', function (){ me.ownerMenu.fireEvent('submenuover', me); if (me.subMenu) { me.delayShowSubMenu(); } }); if (this.subMenu) { this.getDom().className += ' edui-hassubmenu'; this.subMenu.render(); this.addListener('out', function (){ me.delayHideSubMenu(); }); this.subMenu.addListener('over', function (){ clearTimeout(me._closingTimer); me._closingTimer = null; me.addState('opened'); }); this.ownerMenu.addListener('hide', function (){ me.hideSubMenu(); }); this.ownerMenu.addListener('submenuover', function (t, subMenu){ if (subMenu !== me) { me.delayHideSubMenu(); } }); this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide; this.subMenu.queryAutoHide = function (el){ if (el && uiUtils.contains(me.getDom(), el)) { return false; } return this._bakQueryAutoHide(el); }; } this.getDom().style.tabIndex = '-1'; uiUtils.makeUnselectable(this.getDom()); this.Stateful_postRender(); }, delayShowSubMenu: function (){ var me = this; if (!me.isDisabled()) { me.addState('opened'); clearTimeout(me._showingTimer); clearTimeout(me._closingTimer); me._closingTimer = null; me._showingTimer = setTimeout(function (){ me.showSubMenu(); }, 250); } }, delayHideSubMenu: function (){ var me = this; if (!me.isDisabled()) { me.removeState('opened'); clearTimeout(me._showingTimer); if (!me._closingTimer) { me._closingTimer = setTimeout(function (){ if (!me.hasState('opened')) { me.hideSubMenu(); } me._closingTimer = null; }, 400); } } }, renderLabelHtml: function (){ return '<div class="edui-arrow"></div>' + '<div class="edui-box edui-icon"></div>' + '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>'; }, getStateDom: function (){ return this.getDom(); }, queryAutoHide: function (el){ if (this.subMenu && this.hasState('opened')) { return this.subMenu.queryAutoHide(el); } }, _onClick: function (event, this_){ if (this.hasState('disabled')) return; if (this.fireEvent('click', event, this_) !== false) { if (this.subMenu) { this.showSubMenu(); } else { Popup.postHide(); } } }, showSubMenu: function (){ var rect = uiUtils.getClientRect(this.getDom()); rect.right -= 5; rect.left += 2; rect.width -= 7; rect.top -= 4; rect.bottom += 4; rect.height += 8; this.subMenu.showAnchorRect(rect, true, true); }, hideSubMenu: function (){ this.subMenu.hide(); } }; utils.inherits(MenuItem, UIBase); utils.extend(MenuItem.prototype, Stateful, true); })(); ///import core ///import uicore ///import ui/menu.js ///import ui/splitbutton.js (function (){ // todo: menu和item提成通用list var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, Menu = baidu.editor.ui.Menu, SplitButton = baidu.editor.ui.SplitButton, Combox = baidu.editor.ui.Combox = function (options){ this.initOptions(options); this.initCombox(); }; Combox.prototype = { uiName: 'combox', initCombox: function (){ var me = this; this.items = this.items || []; for (var i=0; i<this.items.length; i++) { var item = this.items[i]; item.uiName = 'listitem'; item.index = i; item.onclick = function (){ me.selectByIndex(this.index); }; } this.popup = new Menu({ items: this.items, uiName: 'list', editor:this.editor }); this.initSplitButton(); }, _SplitButton_postRender: SplitButton.prototype.postRender, postRender: function (){ this._SplitButton_postRender(); this.setLabel(this.label || ''); this.setValue(this.initValue || ''); }, showPopup: function (){ var rect = uiUtils.getClientRect(this.getDom()); rect.top += 1; rect.bottom -= 1; rect.height -= 2; this.popup.showAnchorRect(rect); }, getValue: function (){ return this.value; }, setValue: function (value){ var index = this.indexByValue(value); if (index != -1) { this.selectedIndex = index; this.setLabel(this.items[index].label); this.value = this.items[index].value; } else { this.selectedIndex = -1; this.setLabel(this.getLabelForUnknowValue(value)); this.value = value; } }, setLabel: function (label){ this.getDom('button_body').innerHTML = label; this.label = label; }, getLabelForUnknowValue: function (value){ return value; }, indexByValue: function (value){ for (var i=0; i<this.items.length; i++) { if (value == this.items[i].value) { return i; } } return -1; }, getItem: function (index){ return this.items[index]; }, selectByIndex: function (index){ if (index < this.items.length && this.fireEvent('select', index) !== false) { this.selectedIndex = index; this.value = this.items[index].value; this.setLabel(this.items[index].label); } } }; utils.inherits(Combox, SplitButton); })(); ///import core ///import uicore ///import ui/mask.js ///import ui/button.js (function (){ var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils, Mask = baidu.editor.ui.Mask, UIBase = baidu.editor.ui.UIBase, Button = baidu.editor.ui.Button, Dialog = baidu.editor.ui.Dialog = function (options){ this.initOptions(options); this.initDialog(); }; var modalMask; var dragMask; Dialog.prototype = { draggable: false, uiName: 'dialog', initDialog: function (){ var me = this; this.initUIBase(); this.modalMask = (modalMask || (modalMask = new Mask({ className: 'edui-dialog-modalmask' }))); this.dragMask = (dragMask || (dragMask = new Mask({ className: 'edui-dialog-dragmask' }))); this.closeButton = new Button({ className: 'edui-dialog-closebutton', title: '关闭对话框', onclick: function (){ me.close(false); } }); if (this.buttons) { for (var i=0; i<this.buttons.length; i++) { if (!(this.buttons[i] instanceof Button)) { this.buttons[i] = new Button(this.buttons[i]); } } } }, fitSize: function (){ var popBodyEl = this.getDom('body'); // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) { // uiUtils.removeStyle(popBodyEl, 'width'); // uiUtils.removeStyle(popBodyEl, 'height'); // } var size = this.mesureSize(); popBodyEl.style.width = size.width + 'px'; popBodyEl.style.height = size.height + 'px'; return size; }, safeSetOffset: function (offset){ var me = this; var el = me.getDom(); var vpRect = uiUtils.getViewportRect(); var rect = uiUtils.getClientRect(el); var left = offset.left; if (left + rect.width > vpRect.right) { left = vpRect.right - rect.width; } var top = offset.top; if (top + rect.height > vpRect.bottom) { top = vpRect.bottom - rect.height; } el.style.left = Math.max(left, 0) + 'px'; el.style.top = Math.max(top, 0) + 'px'; }, showAtCenter: function (){ this.getDom().style.display = ''; var vpRect = uiUtils.getViewportRect(); var popSize = this.fitSize(); var titleHeight = this.getDom('titlebar').offsetHeight | 0; var left = vpRect.width / 2 - popSize.width / 2; var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight; var popEl = this.getDom(); this.safeSetOffset({ left: Math.max(left | 0, 0), top: Math.max(top | 0, 0) }); if (!domUtils.hasClass(popEl, 'edui-state-centered')) { popEl.className += ' edui-state-centered'; } this._show(); }, getContentHtml: function (){ var contentHtml = ''; if (typeof this.content == 'string') { contentHtml = this.content; } else if (this.iframeUrl) { contentHtml = '<iframe id="'+ this.id + '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>'; } return contentHtml; }, getHtmlTpl: function (){ var footHtml = ''; if (this.buttons) { var buff = []; for (var i=0; i<this.buttons.length; i++) { buff[i] = this.buttons[i].renderHtml(); } footHtml = '<div class="%%-foot">' + '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' + '</div>'; } return '<div id="##" class="%%"><div class="%%-wrap"><div id="##_body" class="%%-body">' + '<div class="%%-shadow"></div>' + '<div id="##_titlebar" class="%%-titlebar">' + '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' + '<span class="%%-caption">' + (this.title || '') + '</span>' + '</div>' + this.closeButton.renderHtml() + '</div>' + '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' + footHtml + '</div></div></div>'; }, postRender: function (){ // todo: 保持居中/记住上次关闭位置选项 if (!this.modalMask.getDom()) { this.modalMask.render(); this.modalMask.hide(); } if (!this.dragMask.getDom()) { this.dragMask.render(); this.dragMask.hide(); } var me = this; this.addListener('show', function (){ me.modalMask.show(this.getDom().style.zIndex - 2); }); this.addListener('hide', function (){ me.modalMask.hide(); }); if (this.buttons) { for (var i=0; i<this.buttons.length; i++) { this.buttons[i].postRender(); } } domUtils.on(window, 'resize', function (){ setTimeout(function (){ if (!me.isHidden()) { me.safeSetOffset(uiUtils.getClientRect(me.getDom())); } }); }); this._hide(); }, mesureSize: function (){ var body = this.getDom('body'); var width = uiUtils.getClientRect(this.getDom('content')).width; var dialogBodyStyle = body.style; dialogBodyStyle.width = width; return uiUtils.getClientRect(body); }, _onTitlebarMouseDown: function (evt, el){ if (this.draggable) { var rect; var vpRect = uiUtils.getViewportRect(); var me = this; uiUtils.startDrag(evt, { ondragstart: function (){ rect = uiUtils.getClientRect(me.getDom()); me.dragMask.show(me.getDom().style.zIndex - 1); }, ondragmove: function (x, y){ var left = rect.left + x; var top = rect.top + y; me.safeSetOffset({ left: left, top: top }); }, ondragstop: function (){ domUtils.removeClasses(me.getDom(), ['edui-state-centered']); me.dragMask.hide(); } }); } }, reset: function (){ this.getDom('content').innerHTML = this.getContentHtml(); }, _show: function (){ if (this._hidden) { this.getDom().style.display = ''; //要高过编辑器的zindxe this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10); this._hidden = false; this.fireEvent('show'); baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4; } }, isHidden: function (){ return this._hidden; }, _hide: function (){ if (!this._hidden) { this.getDom().style.display = 'none'; this.getDom().style.zIndex = ''; this._hidden = true; this.fireEvent('hide'); } }, open: function (){ if (this.autoReset) { this.reset(); } this.showAtCenter(); if (this.iframeUrl) { try { this.getDom('iframe').focus(); } catch(ex){} } }, _onCloseButtonClick: function (evt, el){ this.close(false); }, close: function (ok){ if (this.fireEvent('close', ok) !== false) { this._hide(); } } }; utils.inherits(Dialog, UIBase); })(); ///import core ///import uicore ///import ui/menu.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Menu = baidu.editor.ui.Menu, SplitButton = baidu.editor.ui.SplitButton, MenuButton = baidu.editor.ui.MenuButton = function (options){ this.initOptions(options); this.initMenuButton(); }; MenuButton.prototype = { initMenuButton: function (){ var me = this; this.uiName = "menubutton"; this.popup = new Menu({ items: me.items, className: me.className, editor:me.editor }); this.popup.addListener('show', function (){ var list = this; for (var i=0; i<list.items.length; i++) { list.items[i].removeState('checked'); if (list.items[i].value == me._value) { list.items[i].addState('checked'); this.value = me._value; } } }); this.initSplitButton(); }, setValue : function(value){ this._value = value; } }; utils.inherits(MenuButton, SplitButton); })();(function (){ var isIE = baidu.editor.browser.ie; var utils = baidu.editor.utils; var editorui = baidu.editor.ui; var _Dialog = editorui.Dialog; editorui.Dialog = function (options){ var dialog = new _Dialog(options); dialog.addListener('hide', function (){ if (dialog.editor) { var editor = dialog.editor; try { editor.focus() } catch(ex){} } }); return dialog; }; var k, cmd; var btnCmds = ['Undo', 'Redo','FormatMatch', 'Bold', 'Italic', 'Underline', 'StrikeThrough', 'Subscript', 'Superscript','Source','Indent','Outdent', 'BlockQuote','PastePlain','PageBreak', 'SelectAll', 'Print', 'Preview', 'Horizontal', 'RemoveFormat','Time','Date','Unlink', 'InsertParagraphBeforeTable','InsertRow','InsertCol','MergeRight','MergeDown','DeleteRow', 'DeleteCol','SplittoRows','SplittoCols','SplittoCells','MergeCells','DeleteTable']; k = btnCmds.length; while (k --) { cmd = btnCmds[k]; editorui[cmd] = function (cmd){ return function (editor, title){ title = title || editor.options.labelMap[cmd.toLowerCase()] || ''; var ui = new editorui.Button({ className: 'edui-for-' + cmd.toLowerCase(), title: title, onclick: function (){ editor.execCommand(cmd); }, showText: false }); editor.addListener('selectionchange', function (type, causeByUi, uiReady){ var state = editor.queryCommandState(cmd.toLowerCase()); if (state == -1) { ui.setDisabled(true); ui.setChecked(false); } else { if(!uiReady){ ui.setDisabled(false); ui.setChecked(state); } } }); return ui; }; }(cmd); } editorui.SnapScreen = function(editor, title){ var cmd = "SnapScreen"; title = title || editor.options.labelMap[cmd.toLowerCase()] || ''; var ui = new editorui.Button({ className: 'edui-for-' + cmd.toLowerCase(), title: title, onclick: function (){ editor.execCommand(cmd); } }); if(isIE){ var iframeUrl = editor.options.iframeUrlMap['snapscreen']; iframeUrl = editor.ui.mapUrl(iframeUrl); title = title || editor.options.labelMap['snapscreen'] || ''; var dialog = new editorui.Dialog({ iframeUrl: iframeUrl, autoReset: true, draggable: true, editor: editor, className: 'edui-for-snapscreen', title: title, buttons: [{ className: 'edui-okbutton', label: '确认', onclick: function (){ dialog.close(true); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function (){ dialog.close(false); } }], onok: function (){}, oncancel: function (){}, onclose: function (t, ok){ if (ok) { return this.onok(); } else { return this.oncancel(); } } }); dialog.render(); editor.snapscreenInstall = dialog; } editor.addListener('selectionchange',function(){ var state = editor.queryCommandState('snapscreen'); ui.setDisabled(state == -1); }); return ui; }; editorui.ClearDoc = function(editor, title){ var cmd = "ClearDoc"; title = title || editor.options.labelMap[cmd.toLowerCase()] || ''; var ui = new editorui.Button({ className: 'edui-for-' + cmd.toLowerCase(), title: title, onclick: function (){ if(confirm('确定清空文档吗?')){ editor.execCommand('cleardoc'); } } }); editor.addListener('selectionchange',function(){ var state = editor.queryCommandState('cleardoc'); ui.setDisabled(state == -1); }); return ui; }; editorui.Justify = function (editor, side, title){ side = (side || 'left').toLowerCase(); title = title || editor.options.labelMap['justify'+side.toLowerCase()] || ''; var ui = new editorui.Button({ className: 'edui-for-justify' + side.toLowerCase(), title: title, onclick: function (){ editor.execCommand('Justify', side); } }); editor.addListener('selectionchange', function (type, causeByUi, uiReady){ var state = editor.queryCommandState('Justify'); ui.setDisabled(state == -1); var value = editor.queryCommandValue('Justify'); ui.setChecked(value == side && !uiReady); }); return ui; }; editorui.JustifyLeft = function (editor, title){ return editorui.Justify(editor, 'left', title); }; editorui.JustifyCenter = function (editor, title){ return editorui.Justify(editor, 'center', title); }; editorui.JustifyRight = function (editor, title){ return editorui.Justify(editor, 'right', title); }; editorui.JustifyJustify = function (editor, title){ return editorui.Justify(editor, 'justify', title); }; editorui.ImageFloat = function(editor,side,title){ side = (side || 'none').toLowerCase(); title = title || editor.options.labelMap['image'+side.toLowerCase()] || ''; var ui = new editorui.Button({ className: 'edui-for-image' + side.toLowerCase(), title: title, onclick: function (){ editor.execCommand('imagefloat', side); } }); editor.addListener('selectionchange', function (type){ var state = editor.queryCommandState('imagefloat'); ui.setDisabled(state == -1); var state = editor.queryCommandValue('imagefloat'); ui.setChecked(state == side); }); return ui; }; editorui.ImageNone = function(editor,title){ return editorui.ImageFloat(editor, title); }; editorui.ImageLeft = function(editor,title){ return editorui.ImageFloat(editor,"left", title); }; editorui.ImageRight = function(editor,title){ return editorui.ImageFloat(editor,"right", title); }; editorui.ImageCenter = function(editor,title){ return editorui.ImageFloat(editor,"center", title); }; editorui.Directionality = function (editor, side, title){ side = (side || 'left').toLowerCase(); title = title || editor.options.labelMap['directionality'+side.toLowerCase()] || ''; var ui = new editorui.Button({ className: 'edui-for-directionality' + side.toLowerCase(), title: title, onclick: function (){ editor.execCommand('directionality', side); }, type : side }); editor.addListener('selectionchange', function (type, causeByUi, uiReady){ var state = editor.queryCommandState('directionality'); ui.setDisabled(state == -1); var value = editor.queryCommandValue('directionality'); ui.setChecked(value == ui.type && !uiReady); }); return ui; }; editorui.DirectionalityLtr = function (editor, title){ return new editorui.Directionality(editor, 'ltr', title); }; editorui.DirectionalityRtl = function (editor, title){ return new editorui.Directionality(editor, 'rtl', title); }; var colorCmds = ['BackColor', 'ForeColor']; k = colorCmds.length; while (k --) { cmd = colorCmds[k]; editorui[cmd] = function (cmd){ return function (editor, title){ title = title || editor.options.labelMap[cmd.toLowerCase()] || ''; var ui = new editorui.ColorButton({ className: 'edui-for-' + cmd.toLowerCase(), color: 'default', title: title, editor:editor, onpickcolor: function (t, color){ editor.execCommand(cmd, color); }, onpicknocolor: function (){ editor.execCommand(cmd, 'default'); this.setColor('transparent'); this.color = 'default'; }, onbuttonclick: function (){ editor.execCommand(cmd, this.color); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState(cmd); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); } }); return ui; }; }(cmd); } //不需要确定取消按钮的dialog var dialogNoButton = ['SearchReplace','Help','Spechars']; k = dialogNoButton.length; while(k --){ cmd = dialogNoButton[k]; editorui[cmd] = function (cmd){ cmd = cmd.toLowerCase(); return function (editor, iframeUrl, title){ iframeUrl = iframeUrl || editor.options.iframeUrlMap[cmd.toLowerCase()] || 'about:blank'; iframeUrl = editor.ui.mapUrl(iframeUrl); title = title || editor.options.labelMap[cmd.toLowerCase()] || ''; var dialog = new editorui.Dialog({ iframeUrl: iframeUrl, autoReset: true, draggable: true, editor: editor, className: 'edui-for-' + cmd, title: title, onok: function (){}, oncancel: function (){}, onclose: function (t, ok){ if (ok) { return this.onok(); } else { return this.oncancel(); } } }); dialog.render(); var ui = new editorui.Button({ className: 'edui-for-' + cmd, title: title, onclick: function (){ dialog.open(); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState(cmd); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); } }); return ui; }; }(cmd); } var dialogCmds = ['Attachment','Anchor','Link', 'InsertImage', 'Map', 'GMap', 'InsertVideo','TableSuper','HighlightCode','InsertFrame','EditTd']; k = dialogCmds.length; while (k --) { cmd = dialogCmds[k]; editorui[cmd] = function (cmd){ cmd = cmd.toLowerCase(); return function (editor, iframeUrl, title){ iframeUrl = iframeUrl || editor.options.iframeUrlMap[cmd.toLowerCase()] || 'about:blank'; iframeUrl = editor.ui.mapUrl(iframeUrl); title = title || editor.options.labelMap[cmd.toLowerCase()] || ''; var dialog = new editorui.Dialog({ iframeUrl: iframeUrl, autoReset: true, draggable: true, editor: editor, className: 'edui-for-' + cmd, title: title, buttons: [{ className: 'edui-okbutton', label: '确认', onclick: function (){ dialog.close(true); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function (){ dialog.close(false); } }], onok: function (){}, oncancel: function (){}, onclose: function (t, ok){ if (ok) { return this.onok(); } else { return this.oncancel(); } } }); dialog.render(); var ui = new editorui.Button({ className: 'edui-for-' + cmd, title: title, onclick: function (){ dialog.open(); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState(cmd); if (state == -1) { ui.setDisabled(true); } else { ui.setChecked(state); ui.setDisabled(false); } }); return ui; }; }(cmd); } editorui.WordImage = function(editor){ var ui = new editorui.Button({ className: 'edui-for-wordimage', title: "图片转存", onclick: function (){ editor.execCommand("wordimage","word_img"); editor.ui._dialogs['wordImageDialog'].open(); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState("wordimage","word_img"); //if(console)console.log(state); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); ui.setChecked(state); } }); return ui; }; editorui.FontFamily = function (editor, list, title){ list = list || editor.options.listMap['fontfamily'] || []; title = title || editor.options.labelMap['fontfamily'] || ''; var items = []; for (var i=0; i<list.length; i++) { var font = list[i]; var fonts = editor.options.fontMap[font]; var value = '"' + font + '"'; var regex = new RegExp(font, 'i'); if (fonts) { value = '"' + fonts.join('","') + '"'; regex = new RegExp('(?:\\|)' + fonts.join('|') + '(?:\\|)', 'i'); } items.push({ label: font, value: value, regex: regex, renderLabelHtml: function (){ return '<div class="edui-label %%-label" style="font-family:' + utils.unhtml(this.value) + '">' + (this.label || '') + '</div>'; } }); } var ui = new editorui.Combox({ editor:editor, items: items, onselect: function (t,index){ editor.execCommand('FontFamily', this.items[index].value); }, onbuttonclick: function (){ this.showPopup(); }, title: title, initValue: editor.options.ComboxInitial.FONT_FAMILY, className: 'edui-for-fontfamily', indexByValue: function (value){ if(value){ value = '|' + value.replace(/,/g, '|').replace(/"/g, '') + '|'; value.replace(/\s*|\s*/g, '|'); for (var i=0; i<this.items.length; i++) { var item = this.items[i]; if (item.regex.test(value)) { return i; } } } return -1; } }); editor.addListener('selectionchange', function (type, causeByUi, uiReady){ if(!uiReady){ var state = editor.queryCommandState('FontFamily'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('FontFamily'); //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号 value && (value = value.replace(/['"]/g,'').split(',')[0]); ui.setValue( value); } } }); return ui; }; editorui.FontSize = function (editor, list, title){ list = list || editor.options.listMap['fontsize'] || []; title = title || editor.options.labelMap['fontsize'] || ''; var items = []; for (var i=0; i<list.length; i++) { var size = list[i] + 'px'; items.push({ label: size, value: size, renderLabelHtml: function (){ return '<div class="edui-label %%-label" style="font-size:' + this.value + '">' + (this.label || '') + '</div>'; } }); } var ui = new editorui.Combox({ editor:editor, items: items, title: title, initValue: editor.options.ComboxInitial.FONT_SIZE, onselect: function (t,index){ editor.execCommand('FontSize', this.items[index].value); }, onbuttonclick: function (){ this.showPopup(); }, className: 'edui-for-fontsize' }); editor.addListener('selectionchange', function (type, causeByUi, uiReady){ if(!uiReady){ var state = editor.queryCommandState('FontSize'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); ui.setValue(editor.queryCommandValue('FontSize')); } } }); return ui; }; // editorui.RowSpacing = function (editor, list, title){ // list = list || editor.options.listMap['rowspacing'] || []; // title = title || editor.options.labelMap['rowspacing'] || ''; // var items = []; // for (var i=0; i<list.length; i++) { // var tag = list[i] + 'px'; // var value = list[i]; // items.push({ // label: tag, // value: value, // renderLabelHtml: function (){ // return '<div class="edui-label %%-label" style="font-size:12px">' + (this.label || '') + '</div>'; // } // }); // } // var ui = new editorui.Combox({ // editor:editor, // items: items, // title: title, // initValue: editor.options.ComboxInitial.ROW_SPACING, // onselect: function (t,index){ // editor.execCommand('RowSpacing', this.items[index].value); // }, // onbuttonclick: function (){ // this.showPopup(); // }, // className: 'edui-for-rowspacing' // }); // editor.addListener('selectionchange', function (type, causeByUi, uiReady){ // if(!uiReady){ // var state = editor.queryCommandState('RowSpacing'); // if (state == -1) { // ui.setDisabled(true); // } else { // ui.setDisabled(false); // ui.setValue(editor.queryCommandValue('RowSpacing')); // } // } // // }); // return ui; // }; editorui.Paragraph = function (editor, list, title){ list = list || editor.options.listMap['paragraph'] || []; title = title || editor.options.labelMap['paragraph'] || ''; var items = []; for (var i=0; i<list.length; i++) { var item = list[i].split(':'); var tag = item[0]; var label = item[1]; items.push({ label: label, value: tag, renderLabelHtml: function (){ return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>'; } }); } var ui = new editorui.Combox({ editor:editor, items: items, title: title, initValue: editor.options.ComboxInitial.PARAGRAPH, className: 'edui-for-paragraph', onselect: function (t,index){ editor.execCommand('Paragraph', this.items[index].value); }, onbuttonclick: function (){ this.showPopup(); } }); editor.addListener('selectionchange', function (type, causeByUi, uiReady){ if(!uiReady){ var state = editor.queryCommandState('Paragraph'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('Paragraph'); var index = ui.indexByValue(value); if (index != -1) { ui.setValue(value); } else { ui.setValue(ui.initValue); } } } }); return ui; }; //自定义标题 editorui.CustomStyle = function(editor,list,title){ list = list || editor.options.listMap['customstyle'] || []; title = title || editor.options.labelMap['customstyle'] || ''; for(var i=0,items = [],t;t=list[i++];){ (function(ti){ items.push({ label: ti.label, value: ti, renderLabelHtml: function (){ return '<div class="edui-label %%-label">' +'<'+ ti.tag +' ' + (ti.className?' class="'+ti.className+'"':"") + (ti.style ? ' style="' + ti.style+'"':"") + '>' + ti.label+"<\/"+ti.tag+">" + '</div>'; } }); })(t) } var ui = new editorui.Combox({ editor:editor, items: items, title: title, initValue:editor.options.ComboxInitial.CUSTOMSTYLE, className: 'edui-for-customstyle', onselect: function (t,index){ editor.execCommand('customstyle', this.items[index].value); }, onbuttonclick: function (){ this.showPopup(); }, indexByValue: function (value){ for(var i=0,ti;ti=this.items[i++];){ if(ti.label == value){ return i-1 } } return -1; } }); editor.addListener('selectionchange', function (type, causeByUi, uiReady){ if(!uiReady){ var state = editor.queryCommandState('customstyle'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('customstyle'); var index = ui.indexByValue(value); if (index != -1) { ui.setValue(value); } else { ui.setValue(ui.initValue); } } } }); return ui; }; editorui.InsertTable = function (editor, iframeUrl, title){ iframeUrl = iframeUrl || editor.options.iframeUrlMap['inserttable'] || 'about:blank'; iframeUrl = editor.ui.mapUrl(iframeUrl); title = title || editor.options.labelMap['inserttable'] || ''; var dialog = new editorui.Dialog({ iframeUrl: iframeUrl, autoReset: true, draggable: true, editor: editor, className: 'edui-for-inserttable', title: title, buttons: [{ className: 'edui-okbutton', label: '确认', onclick: function (){ dialog.close(true); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function (){ dialog.close(false); } }], onok: function (){}, oncancel: function (){}, onclose: function (t,ok){ if (ok) { return this.onok(); } else { return this.oncancel(); } } }); dialog.render(); editor.tableDialog = dialog; var ui = new editorui.TableButton({ editor:editor, title: title, className: 'edui-for-inserttable', onpicktable: function (t,numCols, numRows){ editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols}); }, onmore: function (){ dialog.open(); }, onbuttonclick: function (){ dialog.open(); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('inserttable'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); } }); return ui; }; editorui.AutoTypeSet = function (editor, iframeUrl, title){ title = title || editor.options.labelMap['autotypeset'] || ''; var ui = new editorui.AutoTypeSetButton({ editor:editor, title: title, className: 'edui-for-autotypeset', onbuttonclick: function (){ editor.execCommand('autotypeset') } }); editor.addListener('selectionchange', function (){ ui.setDisabled(editor.queryCommandState('autotypeset') == -1); }); return ui; }; editorui.LineHeight = function (editor, title){ for(var i=0,ci,items=[];ci = editor.options.listMap.lineheight[i++];){ items.push({ //todo:写死了 label : ci == '1' ? '默认' : ci, value: ci, onclick:function(){ editor.execCommand("lineheight", this.value); } }) } var ui = new editorui.MenuButton({ editor:editor, className : 'edui-for-lineheight', title : title || editor.options.labelMap['lineheight'] || '', items :items, onbuttonclick: function (){ var value = editor.queryCommandValue('LineHeight') || this.value; editor.execCommand("LineHeight", value); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('LineHeight'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('LineHeight'); value && ui.setValue((value + '').replace(/cm/,'')); ui.setChecked(state) } }); return ui; }; editorui.RowSpacingTop = function (editor, title){ for(var i=0,ci,items=[];ci = editor.options.listMap.rowspacing[i++];){ items.push({ label : ci, value: ci, onclick:function(){ editor.execCommand("rowspacing", this.value,'top'); } }) } var ui = new editorui.MenuButton({ editor:editor, className : 'edui-for-rowspacingtop', title : title || editor.options.labelMap['rowspacingtop'] || '段前间距', items :items, onbuttonclick: function (){ var value = editor.queryCommandValue('rowspacing','top') || this.value; editor.execCommand("rowspacing", value,'top'); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('rowspacing','top'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('rowspacing','top'); value && ui.setValue((value + '').replace(/%/,'')); ui.setChecked(state) } }); return ui; }; editorui.RowSpacingBottom = function (editor, title){ for(var i=0,ci,items=[];ci = editor.options.listMap.rowspacing[i++];){ items.push({ label : ci, value: ci, onclick:function(){ editor.execCommand("rowspacing", this.value,'bottom'); } }) } var ui = new editorui.MenuButton({ editor:editor, className : 'edui-for-rowspacingbottom', title : title || editor.options.labelMap['rowspacingbottom'] || '段后间距', items :items, onbuttonclick: function (){ var value = editor.queryCommandValue('rowspacing','bottom') || this.value; editor.execCommand("rowspacing", value,'bottom'); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('rowspacing','bottom'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('rowspacing','bottom'); value && ui.setValue((value + '').replace(/%/,'')); ui.setChecked(state) } }); return ui; }; editorui.InsertOrderedList = function (editor, title){ title = title || editor.options.labelMap['insertorderedlist'] || ''; var _onMenuClick = function(){ editor.execCommand("InsertOrderedList", this.value); }; var ui = new editorui.MenuButton({ editor:editor, className : 'edui-for-insertorderedlist', title : title, items : [{ label: '1,2,3...', value: 'decimal', onclick : _onMenuClick },{ label: 'a,b,c ...', value: 'lower-alpha', onclick : _onMenuClick },{ label: 'i,ii,iii...', value: 'lower-roman', onclick : _onMenuClick },{ label: 'A,B,C', value: 'upper-alpha', onclick : _onMenuClick },{ label: 'I,II,III...', value: 'upper-roman', onclick : _onMenuClick }], onbuttonclick: function (){ var value = editor.queryCommandValue('InsertOrderedList') || this.value; editor.execCommand("InsertOrderedList", value); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('InsertOrderedList'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('InsertOrderedList'); ui.setValue(value); ui.setChecked(state) } }); return ui; }; editorui.InsertUnorderedList = function (editor, title){ title = title || editor.options.labelMap['insertunorderedlist'] || ''; var _onMenuClick = function(){ editor.execCommand("InsertUnorderedList", this.value); }; var ui = new editorui.MenuButton({ editor:editor, className : 'edui-for-insertunorderedlist', title: title, items: [{ label: '○ 小圆圈', value: 'circle', onclick : _onMenuClick },{ label: '● 小圆点', value: 'disc', onclick : _onMenuClick },{ label: '■ 小方块', value: 'square', onclick : _onMenuClick }], onbuttonclick: function (){ var value = editor.queryCommandValue('InsertUnorderedList') || this.value; editor.execCommand("InsertUnorderedList", value); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('InsertUnorderedList'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('InsertUnorderedList'); ui.setValue(value); ui.setChecked(state) } }); return ui; }; editorui.FullScreen = function (editor, title){ title = title || editor.options.labelMap['fullscreen'] || ''; var ui = new editorui.Button({ className: 'edui-for-fullscreen', title: title, onclick: function (){ if (editor.ui) { editor.ui.setFullScreen(!editor.ui.isFullScreen()); } this.setChecked(editor.ui.isFullScreen()); } }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('fullscreen'); ui.setDisabled(state == -1); ui.setChecked(editor.ui.isFullScreen()); }); return ui; }; editorui.Emotion = function(editor, iframeUrl, title){ title = title || editor.options.labelMap['emotion'] || ''; iframeUrl = iframeUrl || editor.options.iframeUrlMap['emotion'] || 'about:blank'; iframeUrl = editor.ui.mapUrl(iframeUrl); var ui = new editorui.MultiMenuPop({ title: title, editor: editor, className: 'edui-for-emotion', iframeUrl: iframeUrl }); editor.addListener('selectionchange', function (){ var state = editor.queryCommandState('emotion'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); } }); return ui; }; })(); ///import core ///commands 全屏 ///commandsName FullScreen ///commandsTitle 全屏 (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase; function EditorUI( options ) { this.initOptions( options ); this.initEditorUI(); } EditorUI.prototype = { uiName: 'editor', initEditorUI: function () { this.editor.ui = this; this._dialogs = {}; this.initUIBase(); this._initToolbars(); var editor = this.editor, iframeUrlMap = editor.options.iframeUrlMap; editor.addListener( 'ready', function () { baidu.editor.dom.domUtils.on( editor.window, 'scroll', function () { baidu.editor.ui.Popup.postHide(); } ); //display bottom-bar label based on config if ( editor.options.elementPathEnabled ) { editor.ui.getDom( 'elementpath' ).innerHTML = '<div class="edui-editor-breadcrumb">path:</div>'; } if ( editor.options.wordCount ) { editor.ui.getDom( 'wordcount' ).innerHTML = '字数统计'; } if(!editor.selection.isFocus())return; editor.fireEvent( 'selectionchange', false, true ); } ); editor.addListener( 'mousedown', function ( t, evt ) { var el = evt.target || evt.srcElement; baidu.editor.ui.Popup.postHide( el ); } ); editor.addListener( 'contextmenu', function ( t, evt ) { baidu.editor.ui.Popup.postHide(); } ); var me = this; editor.addListener( 'selectionchange', function () { if(!editor.selection.isFocus())return; me._updateElementPath(); //字数统计 me._wordCount(); } ); editor.addListener( 'sourcemodechanged', function ( t, mode ) { if ( editor.options.elementPathEnabled ) { if ( mode ) { me.disableElementPath(); } else { me.enableElementPath(); } } if ( editor.options.wordCount ) { if ( mode ) { me.disableWordCount(); } else { me.enableWordCount(); } } } ); // 超链接的编辑器浮层 var linkDialog = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap ? editor.ui.mapUrl(iframeUrlMap.link ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-link', title: '超链接', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { linkDialog.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { linkDialog.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); linkDialog.render(); // 图片的编辑器浮层 var imgDialog = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap?editor.ui.mapUrl(iframeUrlMap.insertimage ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-insertimage', title: '图片', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { imgDialog.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { imgDialog.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); imgDialog.render(); //锚点 var anchorDialog = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap?editor.ui.mapUrl( iframeUrlMap.anchor ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-anchor', title: '锚点', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { anchorDialog.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { anchorDialog.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); anchorDialog.render(); // video var videoDialog = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap?editor.ui.mapUrl( iframeUrlMap.insertvideo ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-insertvideo', title: '视频', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { videoDialog.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { videoDialog.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); videoDialog.render(); //本地word图片上传 var wordImageDialog = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap?editor.ui.mapUrl( iframeUrlMap.wordimage ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-wordimage', title: '图片转存', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { wordImageDialog.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { wordImageDialog.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); wordImageDialog.render(); //挂载dialog框到ui实例 me._dialogs['wordImageDialog'] = wordImageDialog; var tdDialog = new baidu.editor.ui.Dialog({ iframeUrl: iframeUrlMap?me.mapUrl(iframeUrlMap['edittd']):'about:blank', autoReset: true, draggable: true, editor:editor, className: 'edui-for-edittd', title: "单元格", buttons: [{ className: 'edui-okbutton', label: '确认', onclick: function (){ tdDialog.close(true); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function (){ tdDialog.close(false); } }], onok: function (){}, oncancel: function (){}, onclose: function (t,ok){ if (ok) { return this.onok(); } else { return this.oncancel(); } } }); tdDialog.render(); me._dialogs['tdDialog'] = tdDialog; // map var mapDialog = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap?editor.ui.mapUrl(iframeUrlMap.map ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-map', title: '地图', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { mapDialog.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { mapDialog.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); mapDialog.render(); // map var gmapDialog = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap?editor.ui.mapUrl( iframeUrlMap.gmap ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-gmap', title: 'Google地图', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { gmapDialog.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { gmapDialog.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); gmapDialog.render(); var popup = new baidu.editor.ui.Popup( { editor:editor, content: '', className: 'edui-bubble', _onEditButtonClick: function () { this.hide(); linkDialog.open(); }, _onImgEditButtonClick: function () { this.hide(); var nodeStart = editor.selection.getRange().getClosedNode(); var img = baidu.editor.dom.domUtils.findParentByTagName( nodeStart, "img", true ); if ( img && img.className.indexOf( "edui-faked-video" ) != -1 ) { videoDialog.open(); } else if ( img && img.src.indexOf( "http://api.map.baidu.com" ) != -1 ) { mapDialog.open(); } else if ( img && img.src.indexOf( "http://maps.google.com/maps/api/staticmap" ) != -1 ) { gmapDialog.open(); } else if ( img && img.getAttribute( "anchorname" ) ) { anchorDialog.open(); }else if(img && img.getAttribute("word_img")){ editor.word_img = [img.getAttribute("word_img")]; editor.ui._dialogs["wordImageDialog"].open(); } else { imgDialog.open(); } }, _getImg: function () { var img = editor.selection.getRange().getClosedNode(); if ( img && (img.nodeName == 'img' || img.nodeName == 'IMG') ) { return img; } return null; }, _onImgSetFloat: function( value ) { if ( this._getImg() ) { editor.execCommand( "imagefloat", value ); var img = this._getImg(); if ( img ) { this.showAnchor( img ); } } }, _setIframeAlign: function( value ) { var frame = popup.anchorEl; var newFrame = frame.cloneNode( true ); switch ( value ) { case -2: newFrame.setAttribute( "align", "" ); break; case -1: newFrame.setAttribute( "align", "left" ); break; case 1: newFrame.setAttribute( "align", "right" ); break; case 2: newFrame.setAttribute( "align", "middle" ); break; } frame.parentNode.insertBefore( newFrame, frame ); baidu.editor.dom.domUtils.remove( frame ); popup.anchorEl = newFrame; popup.showAnchor( popup.anchorEl ); }, _updateIframe: function() { editor._iframe = popup.anchorEl; insertframe.open(); popup.hide(); }, _onRemoveButtonClick: function () { var nodeStart = editor.selection.getRange().getClosedNode(); var img = baidu.editor.dom.domUtils.findParentByTagName( nodeStart, "img", true ); if ( img && img.getAttribute( "anchorname" ) ) { editor.execCommand( "anchor" ); } else { editor.execCommand( 'unlink' ); } this.hide(); }, queryAutoHide: function ( el ) { if ( el && el.ownerDocument == editor.document ) { if ( el.tagName.toLowerCase() == 'img' || baidu.editor.dom.domUtils.findParentByTagName( el, 'a', true ) ) { return el !== popup.anchorEl; } } return baidu.editor.ui.Popup.prototype.queryAutoHide.call( this, el ); } } ); popup.render(); //iframe var insertframe = new baidu.editor.ui.Dialog( { iframeUrl: iframeUrlMap?editor.ui.mapUrl( iframeUrlMap.insertframe ):"", autoReset: true, draggable: true, editor: editor, className: 'edui-for-insertframe', title: '插入iframe', buttons: [ { className: 'edui-okbutton', label: '确认', onclick: function () { insertframe.close( true ); } }, { className: 'edui-cancelbutton', label: '取消', onclick: function () { insertframe.close( false ); } } ], onok: function () { }, oncancel: function () { }, onclose: function ( t, ok ) { if ( ok ) { return this.onok(); } else { return this.oncancel(); } } } ); insertframe.render(); editor.addListener( 'mouseover', function( t, evt ) { evt = evt || window.event; var el = evt.target || evt.srcElement; if ( /iframe/ig.test( el.tagName ) && editor.options.imagePopup ) { var html = popup.formatHtml( '<nobr>属性: <span onclick=$$._setIframeAlign(-2) class="edui-clickable">默认</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(-1) class="edui-clickable">左对齐</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(1) class="edui-clickable">右对齐</span>&nbsp;&nbsp;' + '<span onclick=$$._setIframeAlign(2) class="edui-clickable">居中</span>' + ' <span onclick="$$._updateIframe( this);" class="edui-clickable">修改</span></nobr>' ); if ( html ) { popup.getDom( 'content' ).innerHTML = html; popup.anchorEl = el; popup.showAnchor( popup.anchorEl ); } else { popup.hide(); } } } ); editor.addListener( 'selectionchange', function ( t, causeByUi ) { if ( !causeByUi ) return; var html = ''; var img = editor.selection.getRange().getClosedNode(); if ( img != null && img.tagName.toLowerCase() == 'img' ) { if ( img.getAttribute( 'anchorname' ) ) { //锚点处理 html += popup.formatHtml( '<nobr>属性: <span onclick=$$._onImgEditButtonClick(event) class="edui-clickable">修改</span>&nbsp;&nbsp;<span onclick=$$._onRemoveButtonClick(event) class="edui-clickable">删除</span></nobr>' ); } else if ( editor.options.imagePopup ) { html += popup.formatHtml( '<nobr>属性: <span onclick=$$._onImgSetFloat("none") class="edui-clickable">默认</span>&nbsp;&nbsp;<span onclick=$$._onImgSetFloat("left") class="edui-clickable">居左</span>&nbsp;&nbsp;<span onclick=$$._onImgSetFloat("right") class="edui-clickable">居右</span>&nbsp;&nbsp;' + '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">居中</span>' + ' <span onclick="$$._onImgEditButtonClick(event, this);" class="edui-clickable">修改</span></nobr>' ); } } var link; if ( editor.selection.getRange().collapsed ) { link = editor.queryCommandValue( "link" ); } else { link = editor.selection.getStart(); } link = baidu.editor.dom.domUtils.findParentByTagName( link, "a", true ); var url; if ( link != null && (url = (link.getAttribute( 'data_ue_src' ) || link.getAttribute( 'href', 2 ))) != null ) { var txt = url; if ( url.length > 30 ) { txt = url.substring( 0, 20 ) + "..."; } if ( html ) { html += '<div style="height:5px;"></div>' } html += popup.formatHtml( '<nobr>链接: <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' + ' <span class="edui-clickable" onclick="$$._onEditButtonClick(event, this);">修改</span>' + ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(event, this);"> 清除</span></nobr>' ); popup.showAnchor( link ); } if ( html ) { popup.getDom( 'content' ).innerHTML = html; popup.anchorEl = img || link; popup.showAnchor( popup.anchorEl ); } else { popup.hide(); } } ); }, _initToolbars: function () { var editor = this.editor; var toolbars = this.toolbars || []; var toolbarUis = []; for ( var i = 0; i < toolbars.length; i++ ) { var toolbar = toolbars[i]; var toolbarUi = new baidu.editor.ui.Toolbar(); for ( var j = 0; j < toolbar.length; j++ ) { var toolbarItem = toolbar[j]; var toolbarItemUi = null; if ( typeof toolbarItem == 'string' ) { if ( toolbarItem == '|' ) { toolbarItem = 'Separator'; } if ( baidu.editor.ui[toolbarItem] ) { toolbarItemUi = new baidu.editor.ui[toolbarItem]( editor ); } //todo fullscreen这里单独处理一下,放到首行去 if ( toolbarItem == 'FullScreen' ) { if ( toolbarUis && toolbarUis[0] ) { toolbarUis[0].items.splice( 0, 0, toolbarItemUi ); } else { toolbarUi.items.splice( 0, 0, toolbarItemUi ); } continue; } } else { toolbarItemUi = toolbarItem; } if ( toolbarItemUi ) { toolbarUi.add( toolbarItemUi ); } } toolbarUis[i] = toolbarUi; } this.toolbars = toolbarUis; }, getHtmlTpl: function () { return '<div id="##" class="%%">' + '<div id="##_toolbarbox" class="%%-toolbarbox">' + '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' + this.renderToolbarBoxHtml() + '</div></div>' + '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' + '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">点此上传</div>' + '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' + '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' + '<div style="height:0;overflow:hidden;clear:both;"></div>' + '</div>' + '</div>' + '<div id="##_iframeholder" class="%%-iframeholder"></div>' + //modify wdcount by matao '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' + '<td id="##_elementpath" class="%%-bottombar"></td>' + '<td id="##_wordcount" class="%%-wordcount"></td>' + '</tr></table></div>' + '</div>'; }, showWordImageDialog:function() { this.editor.execCommand( "wordimage", "word_img" ); this._dialogs['wordImageDialog'].open(); }, renderToolbarBoxHtml: function () { var buff = []; for ( var i = 0; i < this.toolbars.length; i++ ) { buff.push( this.toolbars[i].renderHtml() ); } return buff.join( '' ); }, setFullScreen: function ( fullscreen ) { if ( this._fullscreen != fullscreen ) { this._fullscreen = fullscreen; this.editor.fireEvent( 'beforefullscreenchange', fullscreen ); var editor = this.editor; if ( baidu.editor.browser.gecko ) { var bk = editor.selection.getRange().createBookmark(); } if ( fullscreen ) { this._bakHtmlOverflow = document.documentElement.style.overflow; this._bakBodyOverflow = document.body.style.overflow; this._bakAutoHeight = this.editor.autoHeightEnabled; this._bakScrollTop = Math.max( document.documentElement.scrollTop, document.body.scrollTop ); if ( this._bakAutoHeight ) { //当全屏时不能执行自动长高 editor.autoHeightEnabled = false; this.editor.disableAutoHeight(); } document.documentElement.style.overflow = 'hidden'; document.body.style.overflow = 'hidden'; this._bakCssText = this.getDom().style.cssText; this._bakCssText1 = this.getDom( 'iframeholder' ).style.cssText; this._updateFullScreen(); } else { this.getDom().style.cssText = this._bakCssText; this.getDom( 'iframeholder' ).style.cssText = this._bakCssText1; if ( this._bakAutoHeight ) { editor.autoHeightEnabled = true; this.editor.enableAutoHeight(); } document.documentElement.style.overflow = this._bakHtmlOverflow; document.body.style.overflow = this._bakBodyOverflow; window.scrollTo( 0, this._bakScrollTop ); } if ( baidu.editor.browser.gecko ) { var input = document.createElement( 'input' ); document.body.appendChild( input ); editor.body.contentEditable = false; setTimeout( function() { input.focus(); setTimeout( function() { editor.body.contentEditable = true; editor.selection.getRange().moveToBookmark( bk ).select( true ); baidu.editor.dom.domUtils.remove( input ); fullscreen && window.scroll( 0, 0 ); } ) } ) } this.editor.fireEvent( 'fullscreenchanged', fullscreen ); this.triggerLayout(); } }, _wordCount:function() { var wdcount = this.getDom( 'wordcount' ); if ( !this.editor.options.wordCount ) { wdcount.style.display = "none"; return; } wdcount.innerHTML = this.editor.queryCommandValue( "wordcount" ); }, disableWordCount: function () { var w = this.getDom( 'wordcount' ); w.innerHTML = ''; w.style.display = 'none'; this.wordcount = false; }, enableWordCount: function () { var w = this.getDom( 'wordcount' ); w.style.display = ''; this.wordcount = true; this._wordCount(); }, _updateFullScreen: function () { if ( this._fullscreen ) { var vpRect = uiUtils.getViewportRect(); this.getDom().style.cssText = 'border:0;position:absolute;left:0;top:0;width:' + vpRect.width + 'px;height:' + vpRect.height + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 100); uiUtils.setViewportOffset( this.getDom(), { left: 0, top: 0 } ); this.editor.setHeight( vpRect.height - this.getDom( 'toolbarbox' ).offsetHeight - this.getDom( 'bottombar' ).offsetHeight ); } }, _updateElementPath: function () { var bottom = this.getDom( 'elementpath' ),list; if ( this.elementPathEnabled && (list = this.editor.queryCommandValue( 'elementpath' ))) { var buff = []; for ( var i = 0,ci; ci = list[i]; i++ ) { buff[i] = this.formatHtml( '<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>' ); } bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">path: ' + buff.join( ' &gt; ' ) + '</div>'; } else { bottom.style.display = 'none' } }, disableElementPath: function () { var bottom = this.getDom( 'elementpath' ); bottom.innerHTML = ''; bottom.style.display = 'none'; this.elementPathEnabled = false; }, enableElementPath: function () { var bottom = this.getDom( 'elementpath' ); bottom.style.display = ''; this.elementPathEnabled = true; this._updateElementPath(); }, isFullScreen: function () { return this._fullscreen; }, postRender: function () { UIBase.prototype.postRender.call( this ); for ( var i = 0; i < this.toolbars.length; i++ ) { this.toolbars[i].postRender(); } var me = this; var timerId, domUtils = baidu.editor.dom.domUtils, updateFullScreenTime = function() { clearTimeout( timerId ); timerId = setTimeout( function () { me._updateFullScreen(); } ); }; domUtils.on( window, 'resize', updateFullScreenTime ); me.addListener( 'destroy', function() { domUtils.un( window, 'resize', updateFullScreenTime ); clearTimeout( timerId ); } ) }, showToolbarMsg: function ( msg, flag ) { this.getDom( 'toolbarmsg_label' ).innerHTML = msg; this.getDom( 'toolbarmsg' ).style.display = ''; // if ( !flag ) { var w = this.getDom( 'upload_dialog' ); w.style.display = 'none'; } }, hideToolbarMsg: function () { this.getDom( 'toolbarmsg' ).style.display = 'none'; }, mapUrl: function ( url ) { return url.replace( '~/', this.editor.options.UEDITOR_HOME_URL || '' ); }, triggerLayout: function () { var dom = this.getDom(); if ( dom.style.zoom == '1' ) { dom.style.zoom = '100%'; } else { dom.style.zoom = '1'; } } }; utils.inherits( EditorUI, baidu.editor.ui.UIBase ); baidu.editor.ui.Editor = function ( options ) { var editor = new baidu.editor.Editor( options ); editor.options.editor = editor; new EditorUI( editor.options ); var oldRender = editor.render; editor.render = function ( holder ) { if ( holder ) { if ( holder.constructor === String ) { holder = document.getElementById( holder ); } holder && holder.getAttribute( 'name' ) && ( editor.options.textarea = holder.getAttribute( 'name' )); if ( holder && /script|textarea/ig.test( holder.tagName ) ) { var newDiv = document.createElement( 'div' ); holder.parentNode.insertBefore( newDiv, holder ); editor.options.initialContent = holder.value || holder.innerHTML; holder.id && (newDiv.id = holder.id); holder.className && (newDiv.className = holder.className); holder.style.cssText && (newDiv.style.cssText = holder.style.cssText); holder.parentNode.removeChild( holder ); holder = newDiv; holder.innerHTML = ''; } } editor.ui.render( holder ); var iframeholder = editor.ui.getDom( 'iframeholder' ); //给实例添加一个编辑器的容器引用 editor.container = editor.ui.getDom(); editor.container.style.zIndex = editor.options.zIndex; oldRender.call( editor, iframeholder ); }; return editor; }; })();///import core ///import uicore ///commands 表情 (function(){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, SplitButton = baidu.editor.ui.SplitButton, MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){ this.initOptions(options); this.initMultiMenu(); }; MultiMenuPop.prototype = { initMultiMenu: function (){ var me = this; this.popup = new Popup({ content: '', editor : me.editor, iframe_rendered: false, onshow: function (){ if (!this.iframe_rendered) { this.iframe_rendered = true; this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>'; me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1); } } // canSideUp:false, // canSideLeft:false }); this.onbuttonclick = function(){ this.showPopup(); }; this.initSplitButton(); } }; utils.inherits(MultiMenuPop, SplitButton); })(); ///import core ///commands 定制过滤规则 ///commandsName Serialize ///commandsTitle 定制过滤规则 UE.plugins['serialize'] = function () { var ie = browser.ie, version = browser.version; function ptToPx(value){ return /pt/.test(value) ? value.replace( /([\d.]+)pt/g, function( str ) { return Math.round(parseFloat(str) * 96 / 72) + "px"; } ) : value; } var me = this, EMPTY_TAG = dtd.$empty, parseHTML = function () { //干掉<a> 后便变得空格,保留</a> 这样的空格 var RE_PART = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g, RE_ATTR = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g, EMPTY_ATTR = {checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1,readonly:1,selected:1}, CDATA_TAG = {script:1,style: 1}, NEED_PARENT_TAG = { "li": { "$": 'ul', "ul": 1, "ol": 1 }, "dd": { "$": "dl", "dl": 1 }, "dt": { "$": "dl", "dl": 1 }, "option": { "$": "select", "select": 1 }, "td": { "$": "tr", "tr": 1 }, "th": { "$": "tr", "tr": 1 }, "tr": { "$": "tbody", "tbody": 1, "thead": 1, "tfoot": 1, "table": 1 }, "tbody": { "$": "table", 'table':1,"colgroup": 1 }, "thead": { "$": "table", "table": 1 }, "tfoot": { "$": "table", "table": 1 }, "col": { "$": "colgroup","colgroup":1 } }; var NEED_CHILD_TAG = { "table": "td", "tbody": "td", "thead": "td", "tfoot": "td", "tr": "td", "colgroup": "col", "ul": "li", "ol": "li", "dl": "dd", "select": "option" }; function parse( html, callbacks ) { var match, nextIndex = 0, tagName, cdata; RE_PART.exec( "" ); while ( (match = RE_PART.exec( html )) ) { var tagIndex = match.index; if ( tagIndex > nextIndex ) { var text = html.slice( nextIndex, tagIndex ); if ( cdata ) { cdata.push( text ); } else { callbacks.onText( text ); } } nextIndex = RE_PART.lastIndex; if ( (tagName = match[1]) ) { tagName = tagName.toLowerCase(); if ( cdata && tagName == cdata._tag_name ) { callbacks.onCDATA( cdata.join( '' ) ); cdata = null; } if ( !cdata ) { callbacks.onTagClose( tagName ); continue; } } if ( cdata ) { cdata.push( match[0] ); continue; } if ( (tagName = match[3]) ) { if ( /="/.test( tagName ) ) { continue; } tagName = tagName.toLowerCase(); var attrPart = match[4], attrMatch, attrMap = {}, selfClosing = attrPart && attrPart.slice( -1 ) == '/'; if ( attrPart ) { RE_ATTR.exec( "" ); while ( (attrMatch = RE_ATTR.exec( attrPart )) ) { var attrName = attrMatch[1].toLowerCase(), attrValue = attrMatch[2] || attrMatch[3] || attrMatch[4] || ''; if ( !attrValue && EMPTY_ATTR[attrName] ) { attrValue = attrName; } if ( attrName == 'style' ) { if ( ie && version <= 6 ) { attrValue = attrValue.replace( /(?!;)\s*([\w-]+):/g, function ( m, p1 ) { return p1.toLowerCase() + ':'; } ); } } //没有值的属性不添加 if ( attrValue ) { attrMap[attrName] = attrValue.replace( /:\s*/g, ':' ) } } } callbacks.onTagOpen( tagName, attrMap, selfClosing ); if ( !cdata && CDATA_TAG[tagName] ) { cdata = []; cdata._tag_name = tagName; } continue; } if ( (tagName = match[2]) ) { callbacks.onComment( tagName ); } } if ( html.length > nextIndex ) { callbacks.onText( html.slice( nextIndex, html.length ) ); } } return function ( html, forceDtd ) { var fragment = { type: 'fragment', parent: null, children: [] }; var currentNode = fragment; function addChild( node ) { node.parent = currentNode; currentNode.children.push( node ); } function addElement( element, open ) { var node = element; // 遇到结构化标签的时候 if ( NEED_PARENT_TAG[node.tag] ) { // 考虑这种情况的时候, 结束之前的标签 // e.g. <table><tr><td>12312`<tr>`4566 while ( NEED_PARENT_TAG[currentNode.tag] && NEED_PARENT_TAG[currentNode.tag][node.tag] ) { currentNode = currentNode.parent; } // 如果前一个标签和这个标签是同一级, 结束之前的标签 // e.g. <ul><li>123<li> if ( currentNode.tag == node.tag ) { currentNode = currentNode.parent; } // 向上补齐父标签 while ( NEED_PARENT_TAG[node.tag] ) { if ( NEED_PARENT_TAG[node.tag][currentNode.tag] ) break; node = node.parent = { type: 'element', tag: NEED_PARENT_TAG[node.tag]['$'], attributes: {}, children: [node] }; } } if ( forceDtd ) { // 如果遇到这个标签不能放在前一个标签内部,则结束前一个标签,span单独处理 while ( dtd[node.tag] && !(currentNode.tag == 'span' ? utils.extend( dtd['strong'], {'a':1,'A':1} ) : (dtd[currentNode.tag] || dtd['div']))[node.tag] ) { if ( tagEnd( currentNode ) ) continue; if ( !currentNode.parent ) break; currentNode = currentNode.parent; } } node.parent = currentNode; currentNode.children.push( node ); if ( open ) { currentNode = element; } if ( element.attributes.style ) { element.attributes.style = element.attributes.style.toLowerCase(); } return element; } // 结束一个标签的时候,需要判断一下它是否缺少子标签 // e.g. <table></table> function tagEnd( node ) { var needTag; if ( !node.children.length && (needTag = NEED_CHILD_TAG[node.tag]) ) { addElement( { type: 'element', tag: needTag, attributes: {}, children: [] }, true ); return true; } return false; } parse( html, { onText: function ( text ) { while ( !(dtd[currentNode.tag] || dtd['div'])['#'] ) { //节点之间的空白不能当作节点处理 // if(/^[ \t\r\n]+$/.test( text )){ // return; // } if ( tagEnd( currentNode ) ) continue; currentNode = currentNode.parent; } //if(/^[ \t\n\r]*/.test(text)) addChild( { type: 'text', data: text } ); }, onComment: function ( text ) { addChild( { type: 'comment', data: text } ); }, onCDATA: function ( text ) { while ( !(dtd[currentNode.tag] || dtd['div'])['#'] ) { if ( tagEnd( currentNode ) ) continue; currentNode = currentNode.parent; } addChild( { type: 'cdata', data: text } ); }, onTagOpen: function ( tag, attrs, closed ) { closed = closed || EMPTY_TAG[tag] ; addElement( { type: 'element', tag: tag, attributes: attrs, closed: closed, children: [] }, !closed ); }, onTagClose: function ( tag ) { var node = currentNode; // 向上找匹配的标签, 这里不考虑dtd的情况是因为tagOpen的时候已经处理过了, 这里不会遇到 while ( node && tag != node.tag ) { node = node.parent; } if ( node ) { // 关闭中间的标签 for ( var tnode = currentNode; tnode !== node.parent; tnode = tnode.parent ) { tagEnd( tnode ); } //去掉空白的inline节点 //分页,锚点保留 //|| dtd.$removeEmptyBlock[node.tag]) // if ( !node.children.length && dtd.$removeEmpty[node.tag] && !node.attributes.anchorname && node.attributes['class'] != 'pagebreak' && node.tag != 'a') { // // node.parent.children.pop(); // } currentNode = node.parent; } else { // 如果没有找到开始标签, 则创建新标签 // eg. </div> => <div></div> //针对视屏网站embed会给结束符,这里特殊处理一下 if ( !(dtd.$removeEmpty[tag] || dtd.$removeEmptyBlock[tag] || tag == 'embed') ) { node = { type: 'element', tag: tag, attributes: {}, children: [] }; addElement( node, true ); tagEnd( node ); currentNode = node.parent; } } } } ); // 处理这种情况, 只有开始标签没有结束标签的情况, 需要关闭开始标签 // eg. <table> while ( currentNode !== fragment ) { tagEnd( currentNode ); currentNode = currentNode.parent; } return fragment; }; }(); var unhtml1 = function () { var map = { '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; function rep( m ) { return map[m]; } return function ( str ) { str = str + ''; return str ? str.replace( /[<>"']/g, rep ) : ''; }; }(); var toHTML = function () { function printChildren( node, pasteplain ) { var children = node.children; var buff = []; for ( var i = 0,ci; ci = children[i]; i++ ) { buff.push( toHTML( ci, pasteplain ) ); } return buff.join( '' ); } function printAttrs( attrs ) { var buff = []; for ( var k in attrs ) { var value = attrs[k]; if(k == 'style'){ //pt==>px value = ptToPx(value); //color rgb ==> hex if(/rgba?\s*\([^)]*\)/.test(value)){ value = value.replace( /rgba?\s*\(([^)]*)\)/g, function( str ) { return utils.fixColor('color',str); } ) } attrs[k] = utils.optCss(value.replace(/windowtext/g,'#000')); } buff.push( k + '="' + unhtml1( attrs[k] ) + '"' ); } return buff.join( ' ' ) } function printData( node, notTrans ) { //trace:1399 输入html代码时空格转换成为&nbsp; //node.data.replace(/&nbsp;/g,' ') 针对pre中的空格和出现的&nbsp;把他们在得到的html代码中都转换成为空格,为了在源码模式下显示为空格而不是&nbsp; return notTrans ? node.data.replace(/&nbsp;/g,' ') : unhtml1( node.data ).replace(/ /g,'&nbsp;'); } //纯文本模式下标签转换 var transHtml = { 'div':'p', 'li':'p', 'tr':'p', 'br':'br', 'p':'p'//trace:1398 碰到p标签自己要加上p,否则transHtml[tag]是undefined }; function printElement( node, pasteplain ) { var tag = node.tag; if ( pasteplain && tag == 'td' ) { if ( !html ) html = ''; html += printChildren( node, pasteplain ) + '&nbsp;&nbsp;&nbsp;'; } else { var attrs = printAttrs( node.attributes ); var html = '<' + (pasteplain && transHtml[tag] ? transHtml[tag] : tag) + (attrs ? ' ' + attrs : '') + (EMPTY_TAG[tag] ? ' />' : '>'); if ( !EMPTY_TAG[tag] ) { //trace:1627 //p标签在ie下为空,将不占位这里占位符不起作用,用&nbsp; if(browser.ie && tag == 'p' && !node.children.length){ html += '&nbsp;'; } html += printChildren( node, pasteplain ); html += '</' + (pasteplain && transHtml[tag] ? transHtml[tag] : tag) + '>'; } } return html; } return function ( node, pasteplain ) { if ( node.type == 'fragment' ) { return printChildren( node, pasteplain ); } else if ( node.type == 'element' ) { return printElement( node, pasteplain ); } else if ( node.type == 'text' || node.type == 'cdata' ) { return printData( node, dtd.$notTransContent[node.parent.tag] ); } else if ( node.type == 'comment' ) { return '<!--' + node.data + '-->'; } return ''; }; }(); //过滤word var transformWordHtml = function () { function isWordDocument( strValue ) { var re = new RegExp( /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<v:)/ig ); return re.test( strValue ); } function ensureUnits( v ) { v = v.replace( /([\d.]+)([\w]+)?/g, function ( m, p1, p2 ) { return (Math.round( parseFloat( p1 ) ) || 1) + (p2 || 'px'); } ); return v; } function filterPasteWord( str ) { str = str.replace( /<!--\s*EndFragment\s*-->[\s\S]*$/, '' ) //remove link break .replace( /^(\r\n|\n|\r)|(\r\n|\n|\r)$/ig, "" ) //remove &nbsp; entities at the start of contents .replace( /^\s*(&nbsp;)+/ig, "" ) //remove &nbsp; entities at the end of contents .replace( /(&nbsp;|<br[^>]*>)+\s*$/ig, "" ) // Word comments like conditional comments etc .replace( /<!--[\s\S]*?-->/ig, "" ) //转换图片 .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){ var width = str.match(/width:([ \d.]*p[tx])/i)[1], height = str.match(/height:([ \d.]*p[tx])/i)[1], src = str.match(/src=\s*"([^"]*)"/i)[1]; return '<img width="'+ptToPx(width)+'" height="'+ptToPx(height)+'" src="' + src + '" />' }) //去掉多余的属性 .replace( /v:\w+=["']?[^'"]+["']?/g, '' ) // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" ) //convert word headers to strong .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" ) //remove lang attribute .replace( /(lang)\s*=\s*([\'\"]?)[\w-]+\2/ig, "" ) //清除多余的font不能匹配&nbsp;有可能是空格 .replace( /<font[^>]*>\s*<\/font>/gi, '' ) //清除多余的class .replace( /class\s*=\s*["']?(?:(?:MsoTableGrid)|(?:MsoNormal(Table)?))\s*["']?/gi, '' ); // Examine all styles: delete junk, transform some, and keep the rest //修复了原有的问题, 比如style='fontsize:"宋体"'原来的匹配失效了 str = str.replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) { var n = [], i = 0, s = style.replace( /^\s+|\s+$/, '' ).replace( /&quot;/gi, "'" ).split( /;\s*/g ); // Examine each style definition within the tag's style attribute for ( var i = 0; i < s.length; i++ ) { var v = s[i]; var name, value, parts = v.split( ":" ); if ( parts.length == 2 ) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); // Translate certain MS Office styles into their CSS equivalents switch ( name ) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": //trace:1819 ff下会解析出padding在table上 if(!/<table/.test(tag)) n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + ensureUnits( value ); continue; case "horiz-align": n[i] = "text-align:" + value; continue; case "vert-align": n[i] = "vertical-align:" + value; continue; case "font-color": case "mso-foreground": n[i] = "color:" + value; continue; case "mso-background": case "mso-highlight": n[i] = "background:" + value; continue; case "mso-default-height": n[i] = "min-height:" + ensureUnits( value ); continue; case "mso-default-width": n[i] = "min-width:" + ensureUnits( value ); continue; case "mso-padding-between-alt": n[i] = "border-collapse:separate;border-spacing:" + ensureUnits( value ); continue; case "text-line-through": if ( (value == "single") || (value == "double") ) { n[i] = "text-decoration:line-through"; } continue; //trace:1870 // //word里边的字体统一干掉 // case 'font-family': // continue; case "mso-zero-height": if ( value == "yes" ) { n[i] = "display:none"; } continue; case 'margin': if ( !/[1-9]/.test( parts[1] ) ) { continue; } } if ( /^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test( name ) ) { if ( !/mso\-list/.test( name ) ) continue; } n[i] = name + ":" + parts[1]; // Lower-case name, but keep value case } } // If style attribute contained any valid styles the re-write it; otherwise delete style attribute. if ( i > 0 ) { return tag + ' style="' + n.join( ';' ) + '"'; } else { return tag; } } ); str = str.replace( /([ ]+)<\/span>/ig, function ( m, p ) { return new Array( p.length + 1 ).join( '&nbsp;' ) + '</span>'; } ); return str; } return function ( html ) { //过了word,才能转p->li first = null; parentTag = '',liStyle = '',firstTag = ''; if ( isWordDocument( html ) ) { html = filterPasteWord( html ); } return html.replace( />[ \t\r\n]*</g, '><' ); }; }(); var NODE_NAME_MAP = { 'text': '#text', 'comment': '#comment', 'cdata': '#cdata-section', 'fragment': '#document-fragment' }; function _likeLi( node ) { var a; if ( node && node.tag == 'p' ) { //office 2011下有效 if ( node.attributes['class'] == 'MsoListParagraph' || /mso-list/.test( node.attributes.style ) ) { a = 1; } else { var firstChild = node.children[0]; if ( firstChild && firstChild.tag == 'span' && /Wingdings/i.test( firstChild.attributes.style ) ) { a = 1; } } } return a; } //为p==>li 做个标志 var first, orderStyle = { 'decimal' : /\d+/, 'lower-roman': /^m{0,4}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})$/, 'upper-roman': /^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/, 'lower-alpha' : /^\(?[a-z]+\)?$/, 'upper-alpha': /^\(?[A-Z]+\)?$/ }, unorderStyle = { 'disc' : /^[l\u00B7\u2002]/, 'circle' : /^[\u006F\u00D8]/,'square' : /^[\u006E\u25C6]/}, parentTag = '',liStyle = '',firstTag; //写入编辑器时,调用,进行转换操作 function transNode( node, word_img_flag ) { //dtd.$removeEmptyBlock[node.tag] if ( node.type == 'element' && !node.children.length && (dtd.$removeEmpty[node.tag]) && node.tag != 'a' ) {// 锚点保留 return { type : 'fragment', children:[] } } var sizeMap = [0, 10, 12, 16, 18, 24, 32, 48], attr, indexOf = utils.indexOf; switch ( node.tag ) { case 'img': //todo base64暂时去掉,后边做远程图片上传后,干掉这个 if(node.attributes.src && /^data:/.test(node.attributes.src)){ return { type : 'fragment', children:[] } } if ( node.attributes.src && /^(?:file)/.test( node.attributes.src ) ) { if ( !/(gif|bmp|png|jpg|jpeg)$/.test( node.attributes.src ) ) { return { type : 'fragment', children:[] } } node.attributes.word_img = node.attributes.src; node.attributes.src = me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif'; var flag = parseInt(node.attributes.width)<128||parseInt(node.attributes.height)<43; node.attributes.style="background:url(" + me.options.UEDITOR_HOME_URL +"themes/default/images/"+(flag?"word.gif":"localimage.png")+") no-repeat center center;border:1px solid #ddd"; //node.attributes.style = 'width:395px;height:173px;'; word_img_flag && (word_img_flag.flag = 1); } if(browser.ie && browser.version < 7 && me.options.relativePath) node.attributes.orgSrc = node.attributes.src; node.attributes.data_ue_src = node.attributes.data_ue_src || node.attributes.src; break; case 'li': var child = node.children[0]; if ( !child || child.type != 'element' || child.tag != 'p' && dtd.p[child.tag] ) { var tmpPNode = { type: 'element', tag: 'p', attributes: {}, parent : node }; tmpPNode.children = child ? node.children :[ browser.ie ? { type:'text', data:domUtils.fillChar, parent : tmpPNode }: { type : 'element', tag : 'br', attributes:{}, closed: true, children: [], parent : tmpPNode } ]; node.children = [tmpPNode]; } break; case 'table': case 'td': optStyle( node ); break; case 'a'://锚点,a==>img if ( node.attributes['anchorname'] ) { node.tag = 'img'; node.attributes = { 'class' : 'anchorclass', 'anchorname':node.attributes['name'] }; node.closed = 1; } node.attributes.href && (node.attributes.data_ue_src = node.attributes.href); break; case 'b': node.tag = node.name = 'strong'; break; case 'i': node.tag = node.name = 'em'; break; case 'u': node.tag = node.name = 'span'; node.attributes.style = (node.attributes.style || '') + ';text-decoration:underline;'; break; case 's': case 'del': node.tag = node.name = 'span'; node.attributes.style = (node.attributes.style || '') + ';text-decoration:line-through;'; if ( node.children.length == 1 ) { child = node.children[0]; if ( child.tag == node.tag ) { node.attributes.style += ";" + child.attributes.style; node.children = child.children; } } break; case 'span': if ( /mso-list/.test( node.attributes.style ) ) { //判断了两次就不在判断了 if ( firstTag != 'end' ) { var ci = node.children[0],p; while ( ci.type == 'element' ) { ci = ci.children[0]; } for ( p in unorderStyle ) { if ( unorderStyle[p].test( ci.data ) ) { // ci.data = ci.data.replace(unorderStyle[p],''); parentTag = 'ul'; liStyle = p; break; } } if ( !parentTag ) { for ( p in orderStyle ) { if ( orderStyle[p].test( ci.data.replace( /\.$/, '' ) ) ) { // ci.data = ci.data.replace(orderStyle[p],''); parentTag = 'ol'; liStyle = p; break; } } } if ( firstTag ) { if ( ci.data == firstTag ) { if ( parentTag != 'ul' ) { liStyle = ''; } parentTag = 'ul' } else { if ( parentTag != 'ol' ) { liStyle = ''; } parentTag = 'ol' } firstTag = 'end' } else { firstTag = ci.data } if ( parentTag ) { var tmpNode = node; while ( tmpNode && tmpNode.tag != 'ul' && tmpNode.tag != 'ol' ) { tmpNode = tmpNode.parent; } if(tmpNode ){ tmpNode.tag = parentTag; tmpNode.attributes.style = 'list-style-type:' + liStyle; } } } node = { type : 'fragment', children : [] }; break; } var style = node.attributes.style; if ( style ) { //trace:1493 //ff3.6出来的是background: none repeat scroll %0 %0 颜色 style = style.match( /(?:\b(?:color|font-size|background(-color)?|font-family|text-decoration)\b\s*:\s*(&[^;]+;|[^;])+(?=;)?)/gi ); if ( style ) { node.attributes.style = style.join( ';' ); if ( !node.attributes.style ) { delete node.attributes.style; } } } //针对ff3.6span的样式不能正确继承的修复 if(browser.gecko && browser.version <= 10902 && node.parent){ var parent = node.parent; if(parent.tag == 'span' && parent.attributes && parent.attributes.style){ node.attributes.style = parent.attributes.style + ';' + node.attributes.style; } } if ( utils.isEmptyObject( node.attributes ) ) { node.type = 'fragment' } break; case 'font': node.tag = node.name = 'span'; attr = node.attributes; node.attributes = { 'style': (attr.size ? 'font-size:' + (sizeMap[attr.size] || 12) + 'px' : '') + ';' + (attr.color ? 'color:'+ attr.color : '') + ';' + (attr.face ? 'font-family:'+ attr.face : '') + ';' + (attr.style||'') }; while(node.parent.tag == node.tag && node.parent.children.length == 1){ node.attributes.style && (node.parent.attributes.style ? (node.parent.attributes.style += ";" + node.attributes.style) : (node.parent.attributes.style = node.attributes.style)); node.parent.children = node.children; node = node.parent; } break; case 'p': if ( node.attributes.align ) { node.attributes.style = (node.attributes.style || '') + ';text-align:' + node.attributes.align + ';'; delete node.attributes.align; } if ( _likeLi( node ) ) { if ( !first ) { var ulNode = { type: 'element', tag: 'ul', attributes: {}, children: [] }, index = indexOf( node.parent.children, node ); node.parent.children[index] = ulNode; ulNode.parent = node.parent; ulNode.children[0] = node; node.parent = ulNode; while ( 1 ) { node = ulNode.parent.children[index + 1]; if ( _likeLi( node ) ) { ulNode.children[ulNode.children.length] = node; node.parent = ulNode; ulNode.parent.children.splice( index + 1, 1 ); } else { break; } } return ulNode; } node.tag = node.name = 'li'; //为chrome能找到标号做的处理 if ( browser.webkit ) { var span = node.children[0]; while ( span && span.type == 'element' ) { span = span.children[0] } span && (span.parent.attributes.style = (span.parent.attributes.style || '') + ';mso-list:10'); } delete node.attributes['class']; delete node.attributes.style; } } return node; } function optStyle( node ) { if ( ie && node.attributes.style ) { var style = node.attributes.style; node.attributes.style = style.replace(/;\s*/g,';'); node.attributes.style = node.attributes.style.replace( /^\s*|\s*$/, '' ) } } function transOutNode( node ) { switch ( node.tag ) { case 'table': !node.attributes.style && delete node.attributes.style; if ( ie && node.attributes.style ) { optStyle( node ); } break; case 'td': case 'th': if ( /display\s*:\s*none/i.test( node.attributes.style ) ) { return { type: 'fragment', children: [] }; } if ( ie && !node.children.length ) { var txtNode = { type: 'text', data:domUtils.fillChar, parent : node }; node.children[0] = txtNode; } if ( ie && node.attributes.style ) { optStyle( node ); } break; case 'img'://锚点,img==>a if ( node.attributes.anchorname ) { node.tag = 'a'; node.attributes = { name : node.attributes.anchorname, anchorname : 1 }; node.closed = null; }else{ if(node.attributes.data_ue_src){ node.attributes.src = node.attributes.data_ue_src; delete node.attributes.data_ue_src; } } break; case 'a': if(node.attributes.data_ue_src){ node.attributes.href = node.attributes.data_ue_src; delete node.attributes.data_ue_src; } } return node; } function childrenAccept( node, visit, ctx ) { if ( !node.children || !node.children.length ) { return node; } var children = node.children; for ( var i = 0; i < children.length; i++ ) { var newNode = visit( children[i], ctx ); if ( newNode.type == 'fragment' ) { var args = [i, 1]; args.push.apply( args, newNode.children ); children.splice.apply( children, args ); //节点为空的就干掉,不然后边的补全操作会添加多余的节点 if ( !children.length ) { node = { type: 'fragment', children: [] } } i --; } else { children[i] = newNode; } } return node; } function Serialize( rules ) { this.rules = rules; } Serialize.prototype = { // NOTE: selector目前只支持tagName rules: null, // NOTE: node必须是fragment filter: function ( node, rules, modify ) { rules = rules || this.rules; var whiteList = rules && rules.whiteList; var blackList = rules && rules.blackList; function visitNode( node, parent ) { node.name = node.type == 'element' ? node.tag : NODE_NAME_MAP[node.type]; if ( parent == null ) { return childrenAccept( node, visitNode, node ); } if ( blackList && blackList[node.name] ) { modify && (modify.flag = 1); return { type: 'fragment', children: [] }; } if ( whiteList ) { if ( node.type == 'element' ) { if ( parent.type == 'fragment' ? whiteList[node.name] : whiteList[node.name] && whiteList[parent.name][node.name] ) { var props; if ( (props = whiteList[node.name].$) ) { var oldAttrs = node.attributes; var newAttrs = {}; for ( var k in props ) { if ( oldAttrs[k] ) { newAttrs[k] = oldAttrs[k]; } } node.attributes = newAttrs; } } else { modify && (modify.flag = 1); node.type = 'fragment'; // NOTE: 这里算是一个hack node.name = parent.name; } } else { // NOTE: 文本默认允许 } } if ( blackList || whiteList ) { childrenAccept( node, visitNode, node ); } return node; } return visitNode( node, null ); }, transformInput: function ( node, word_img_flag ) { function visitNode( node ) { node = transNode( node, word_img_flag ); if ( node.tag == 'ol' || node.tag == 'ul' ) { first = 1; } node = childrenAccept( node, visitNode, node ); if ( node.tag == 'ol' || node.tag == 'ul' ) { first = 0; parentTag = '',liStyle = '',firstTag = ''; } if ( node.type == 'text' && node.data.replace( /\s/g, '' ) == me.options.pageBreakTag ) { node.type = 'element'; node.name = node.tag = 'hr'; delete node.data; node.attributes = { 'class' : 'pagebreak', noshade:"noshade", size:"5", 'unselectable' : 'on', 'style' : 'moz-user-select:none;-khtml-user-select: none;' }; node.children = []; } //去掉多余的空格和换行 if(node.type == 'text' && !dtd.$notTransContent[node.parent.tag]){ node.data = node.data.replace(/[\r\t\n]*/g,'')//.replace(/[ ]*$/g,'') } return node; } return visitNode( node ); }, transformOutput: function ( node ) { function visitNode( node ) { if ( node.tag == 'hr' && node.attributes['class'] == 'pagebreak' ) { delete node.tag; node.type = 'text'; node.data = me.options.pageBreakTag; delete node.children; } node = transOutNode( node ); if ( node.tag == 'ol' || node.tag == 'ul' ) { first = 1; } node = childrenAccept( node, visitNode, node ); if ( node.tag == 'ol' || node.tag == 'ul' ) { first = 0; } return node; } return visitNode( node ); }, toHTML: toHTML, parseHTML: parseHTML, word: transformWordHtml }; me.serialize = new Serialize( me.options.serialize ); UE.serialize = new Serialize( {} ); }; ///import core ///commands 撤销和重做 ///commandsName Undo,Redo ///commandsTitle 撤销,重做 /** * @description 回退 * @author zhanyi */ UE.plugins['undo'] = function() { var me = this, maxUndoCount = me.options.maxUndoCount, maxInputCount = me.options.maxInputCount, fillchar = new RegExp(domUtils.fillChar + '|<\/hr>','gi'),// ie会产生多余的</hr> //在比较时,需要过滤掉这些属性 specialAttr = /\b(?:href|src|name)="[^"]*?"/gi; function UndoManager() { this.list = []; this.index = 0; this.hasUndo = false; this.hasRedo = false; this.undo = function() { if ( this.hasUndo ) { var currentScene = this.getScene(), lastScene = this.list[this.index]; if ( lastScene.content.replace(specialAttr,'') != currentScene.content.replace(specialAttr,'') ) { this.save(); } if(!this.list[this.index - 1] && this.list.length == 1){ this.reset(); return; } while ( this.list[this.index].content == this.list[this.index - 1].content ) { this.index--; if ( this.index == 0 ) { return this.restore( 0 ) } } this.restore( --this.index ); } }; this.redo = function() { if ( this.hasRedo ) { while ( this.list[this.index].content == this.list[this.index + 1].content ) { this.index++; if ( this.index == this.list.length - 1 ) { return this.restore( this.index ) } } this.restore( ++this.index ); } }; this.restore = function() { var scene = this.list[this.index]; //trace:873 //去掉展位符 me.document.body.innerHTML = scene.bookcontent.replace(fillchar,''); //处理undo后空格不展位的问题 if(browser.ie){ for(var i=0,pi,ps = me.document.getElementsByTagName('p');pi = ps[i++];){ if(pi.innerHTML == ''){ domUtils.fillNode(me.document,pi); } } } var range = new dom.Range( me.document ); range.moveToBookmark( { start : '_baidu_bookmark_start_', end : '_baidu_bookmark_end_', id : true //去掉true 是为了<b>|</b>,回退后还能在b里 //todo safari里输入中文时,会因为改变了dom而导致丢字 } ); //trace:1278 ie9block元素为空,将出现光标定位的问题,必须填充内容 if(browser.ie && browser.version == 9 && range.collapsed && domUtils.isBlockElm(range.startContainer) && domUtils.isEmptyNode(range.startContainer)){ domUtils.fillNode(range.document,range.startContainer); } range.select(!browser.gecko); setTimeout(function(){ range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0); },200); this.update(); //table的单独处理 if(me.currentSelectedArr){ me.currentSelectedArr = []; var tds = me.document.getElementsByTagName('td'); for(var i=0,td;td=tds[i++];){ if(td.className == me.options.selectedTdClass){ me.currentSelectedArr.push(td); } } } this.clearKey(); //不能把自己reset了 me.fireEvent('reset',true); me.fireEvent('contentchange') }; this.getScene = function() { var range = me.selection.getRange(), cont = me.body.innerHTML.replace(fillchar,''); //有可能边界落到了<table>|<tbody>这样的位置,所以缩一下位置 range.shrinkBoundary(); browser.ie && (cont = cont.replace(/>&nbsp;</g,'><').replace(/\s*</g,'').replace(/>\s*/g,'>')); var bookmark = range.createBookmark( true, true ), bookCont = me.body.innerHTML.replace(fillchar,''); range.moveToBookmark( bookmark ).select( true ); return { bookcontent : bookCont, content : cont } }; this.save = function() { var currentScene = this.getScene(), lastScene = this.list[this.index]; //内容相同位置相同不存 if ( lastScene && lastScene.content == currentScene.content && lastScene.bookcontent == currentScene.bookcontent ) { return; } this.list = this.list.slice( 0, this.index + 1 ); this.list.push( currentScene ); //如果大于最大数量了,就把最前的剔除 if ( this.list.length > maxUndoCount ) { this.list.shift(); } this.index = this.list.length - 1; this.clearKey(); //跟新undo/redo状态 this.update(); me.fireEvent('contentchange') }; this.update = function() { this.hasRedo = this.list[this.index + 1] ? true : false; this.hasUndo = this.list[this.index - 1] || this.list.length == 1 ? true : false; }; this.reset = function() { this.list = []; this.index = 0; this.hasUndo = false; this.hasRedo = false; this.clearKey(); }; this.clearKey = function(){ keycont = 0; lastKeyCode = null; } } me.undoManger = new UndoManager(); function saveScene() { this.undoManger.save() } me.addListener( 'beforeexeccommand', saveScene ); me.addListener( 'afterexeccommand', saveScene ); me.addListener('reset',function(type,exclude){ if(!exclude) me.undoManger.reset(); }); me.commands['redo'] = me.commands['undo'] = { execCommand : function( cmdName ) { me.undoManger[cmdName](); }, queryCommandState : function( cmdName ) { return me.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1; }, notNeedUndo : 1 }; var keys = { // /*Backspace*/ 8:1, /*Delete*/ 46:1, /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1, 37:1, 38:1, 39:1, 40:1, 13:1 /*enter*/ }, keycont = 0, lastKeyCode; me.addListener( 'keydown', function( type, evt ) { var keyCode = evt.keyCode || evt.which; if ( !keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey ) { if ( me.undoManger.list.length == 0 || ((keyCode == 8 ||keyCode == 46) && lastKeyCode != keyCode) ) { me.undoManger.save(); lastKeyCode = keyCode; return } //trace:856 //修正第一次输入后,回退,再输入要到keycont>maxInputCount才能在回退的问题 if(me.undoManger.list.length == 2 && me.undoManger.index == 0 && keycont == 0){ me.undoManger.list.splice(1,1); me.undoManger.update(); } lastKeyCode = keyCode; keycont++; if ( keycont > maxInputCount ) { setTimeout( function() { me.undoManger.save(); }, 0 ); } } } ) }; ///import core ///import plugins/serialize.js ///import plugins/undo.js ///commands 查看源码 ///commandsName Source ///commandsTitle 查看源码 (function (){ function SourceFormater(config){ config = config || {}; this.indentChar = config.indentChar || ' '; this.breakChar = config.breakChar || '\n'; this.selfClosingEnd = config.selfClosingEnd || ' />'; } var unhtml1 = function (){ var map = { '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; function rep( m ){ return map[m]; } return function ( str ) { str = str + ''; return str ? str.replace( /[<>"']/g, rep ) : ''; }; }(); var inline = utils.extend({a:1,A:1},dtd.$inline,true); function printAttrs(attrs){ var buff = []; for (var k in attrs) { buff.push(k + '="' + unhtml1(attrs[k]) + '"'); } return buff.join(' '); } SourceFormater.prototype = { format: function (html){ var node = UE.serialize.parseHTML(html); this.buff = []; this.indents = ''; this.indenting = 1; this.visitNode(node); return this.buff.join(''); }, visitNode: function (node){ if (node.type == 'fragment') { this.visitChildren(node.children); } else if (node.type == 'element') { var selfClosing = dtd.$empty[node.tag]; this.visitTag(node.tag, node.attributes, selfClosing); this.visitChildren(node.children); if (!selfClosing) { this.visitEndTag(node.tag); } } else if (node.type == 'comment') { this.visitComment(node.data); } else { this.visitText(node.data,dtd.$notTransContent[node.parent.tag]); } }, visitChildren: function (children){ for (var i=0; i<children.length; i++) { this.visitNode(children[i]); } }, visitTag: function (tag, attrs, selfClosing){ if (this.indenting) { this.indent(); } else if (!inline[tag]) { // todo: 去掉a, 因为dtd的inline里面没有a this.newline(); this.indent(); } this.buff.push('<', tag); var attrPart = printAttrs(attrs); if (attrPart) { this.buff.push(' ', attrPart); } if (selfClosing) { this.buff.push(this.selfClosingEnd); if (tag == 'br') { this.newline(); } } else { this.buff.push('>'); this.indents += this.indentChar; } if (!inline[tag]) { this.newline(); } }, indent: function (){ this.buff.push(this.indents); this.indenting = 0; }, newline: function (){ this.buff.push(this.breakChar); this.indenting = 1; }, visitEndTag: function (tag){ this.indents = this.indents.slice(0, -this.indentChar.length); if (this.indenting) { this.indent(); } else if (!inline[tag]) { this.newline(); this.indent(); } this.buff.push('</', tag, '>'); }, visitText: function (text,notTrans){ if (this.indenting) { this.indent(); } // if(!notTrans){ // text = text.replace(/&nbsp;/g, ' ').replace(/[ ][ ]+/g, function (m){ // return new Array(m.length + 1).join('&nbsp;'); // }).replace(/(?:^ )|(?: $)/g, '&nbsp;'); // } text = text.replace(/&nbsp;/g, ' ') this.buff.push(text); }, visitComment: function (text){ if (this.indenting) { this.indent(); } this.buff.push('<!--', text, '-->'); } }; var sourceEditors = { textarea: function (editor, holder){ var textarea = holder.ownerDocument.createElement('textarea'); textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;'; // todo: IE下只有onresize属性可用... 很纠结 if (browser.ie && browser.version < 8) { textarea.style.width = holder.offsetWidth + 'px'; textarea.style.height = holder.offsetHeight + 'px'; holder.onresize = function (){ textarea.style.width = holder.offsetWidth + 'px'; textarea.style.height = holder.offsetHeight + 'px'; }; } holder.appendChild(textarea); return { setContent: function (content){ textarea.value = content; }, getContent: function (){ return textarea.value; }, select: function (){ var range; if (browser.ie) { range = textarea.createTextRange(); range.collapse(true); range.select(); } else { //todo: chrome下无法设置焦点 textarea.setSelectionRange(0, 0); textarea.focus(); } }, dispose: function (){ holder.removeChild(textarea); // todo holder.onresize = null; textarea = null; holder = null; } }; }, codemirror: function (editor, holder){ var options = { mode: "text/html", tabMode: "indent", lineNumbers: true, lineWrapping:true }; var codeEditor = window.CodeMirror(holder, options); var dom = codeEditor.getWrapperElement(); dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;'; codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;'; codeEditor.refresh(); return { setContent: function (content){ codeEditor.setValue(content); }, getContent: function (){ return codeEditor.getValue(); }, select: function (){ codeEditor.focus(); }, dispose: function (){ holder.removeChild(dom); dom = null; codeEditor = null; } }; } }; UE.plugins['source'] = function (){ var me = this; var opt = this.options; var formatter = new SourceFormater(opt.source); var sourceMode = false; var sourceEditor; function createSourceEditor(holder){ var useCodeMirror = opt.sourceEditor == 'codemirror' && window.CodeMirror; return sourceEditors[useCodeMirror ? 'codemirror' : 'textarea'](me, holder); } var bakCssText; me.commands['source'] = { execCommand: function (){ sourceMode = !sourceMode; if (sourceMode) { me.undoManger && me.undoManger.save(); this.currentSelectedArr && domUtils.clearSelectedArr(this.currentSelectedArr); if(browser.gecko) me.body.contentEditable = false; bakCssText = me.iframe.style.cssText; me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;'; var content = formatter.format(me.hasContents() ? me.getContent() : ''); sourceEditor = createSourceEditor(me.iframe.parentNode); sourceEditor.setContent(content); setTimeout(function (){ sourceEditor.select(); }); } else { me.iframe.style.cssText = bakCssText; var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>'; cont = cont.replace(/>[\n\r\t]+([ ]{4})+/g,'>').replace(/[\n\r\t]+([ ]{4})+</g,'<').replace(/>[\n\r\t]+</g,'><'); me.setContent(cont); sourceEditor.dispose(); sourceEditor = null; setTimeout(function(){ var first = me.body.firstChild; //trace:1106 都删除空了,下边会报错,所以补充一个p占位 if(!first){ me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>'; first = me.body.firstChild; } //要在ifm为显示时ff才能取到selection,否则报错 me.undoManger && me.undoManger.save(); while(first && first.firstChild){ first = first.firstChild; } var range = me.selection.getRange(); if(first.nodeType == 3 || dtd.$empty[first.tagName]){ range.setStartBefore(first) }else{ range.setStart(first,0); } if(browser.gecko){ var input = document.createElement('input'); input.style.cssText = 'position:absolute;left:0;top:-32768px'; document.body.appendChild(input); me.body.contentEditable = false; setTimeout(function(){ domUtils.setViewportOffset(input, { left: -32768, top: 0 }); input.focus(); setTimeout(function(){ me.body.contentEditable = true; range.setCursor(false,true); domUtils.remove(input) }) }) }else{ range.setCursor(false,true); } }) } this.fireEvent('sourcemodechanged', sourceMode); }, queryCommandState: function (){ return sourceMode|0; } }; var oldQueryCommandState = me.queryCommandState; me.queryCommandState = function (cmdName){ cmdName = cmdName.toLowerCase(); if (sourceMode) { return cmdName == 'source' ? 1 : -1; } return oldQueryCommandState.apply(this, arguments); }; //解决在源码模式下getContent不能得到最新的内容问题 var oldGetContent = me.getContent; me.getContent = function (){ if(sourceMode && sourceEditor ){ var html = sourceEditor.getContent(); if (this.serialize) { var node = this.serialize.parseHTML(html); node = this.serialize.filter(node); html = this.serialize.toHTML(node); } return html; }else{ return oldGetContent.apply(this, arguments) } }; me.addListener("ready",function(){ if(opt.sourceEditor == "codemirror"){ utils.loadFile(document,{ src : opt.codeMirrorJsUrl, tag : "script", type : "text/javascript", defer : "defer" }); utils.loadFile(document,{ tag : "link", rel : "stylesheet", type : "text/css", href : opt.codeMirrorCssUrl }); } }); }; })();///import core ///commands 段落格式,居左,居右,居中,两端对齐 ///commandsName JustifyLeft,JustifyCenter,JustifyRight,JustifyJustify ///commandsTitle 居左对齐,居中对齐,居右对齐,两端对齐 /** * @description 居左右中 * @name baidu.editor.execCommand * @param {String} cmdName justify执行对齐方式的命令 * @param {String} align 对齐方式:left居左,right居右,center居中,justify两端对齐 * @author zhanyi */ (function(){ var block = domUtils.isBlockElm, defaultValue = { left : 1, right : 1, center : 1, justify : 1 }, doJustify = function(range,style){ var bookmark = range.createBookmark(), filterFn = function( node ) { return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node ) }; range.enlarge(true); var bookmark2 = range.createBookmark(), current = domUtils.getNextDomNode(bookmark2.start,false,filterFn), tmpRange = range.cloneRange(), tmpNode; while(current && !(domUtils.getPosition(current,bookmark2.end)&domUtils.POSITION_FOLLOWING)){ if(current.nodeType == 3 || !block(current)){ tmpRange.setStartBefore(current); while(current && current!==bookmark2.end && !block(current)){ tmpNode = current; current = domUtils.getNextDomNode(current,false,null,function(node){ return !block(node) }); } tmpRange.setEndAfter(tmpNode); var common = tmpRange.getCommonAncestor(); if( !domUtils.isBody(common) && block(common)){ domUtils.setStyles(common,utils.isString(style) ? {'text-align':style} : style); current = common; }else{ var p = range.document.createElement('p'); domUtils.setStyles(p,utils.isString(style) ? {'text-align':style} : style); var frag = tmpRange.extractContents(); p.appendChild(frag); tmpRange.insertNode(p); current = p; } current = domUtils.getNextDomNode(current,false,filterFn); }else{ current = domUtils.getNextDomNode(current,true,filterFn); } } return range.moveToBookmark(bookmark2).moveToBookmark(bookmark) }; UE.commands['justify'] = { execCommand : function( cmdName,align ) { var range = this.selection.getRange(), txt; if(this.currentSelectedArr && this.currentSelectedArr.length > 0){ for(var i=0,ti;ti=this.currentSelectedArr[i++];){ if(domUtils.isEmptyNode(ti)){ txt = this.document.createTextNode('p'); range.setStart(ti,0).collapse(true).insertNode(txt).selectNode(txt); }else{ range.selectNodeContents(ti) } doJustify(range,align); txt && domUtils.remove(txt); } range.selectNode(this.currentSelectedArr[0]).select() }else{ //闭合时单独处理 if(range.collapsed){ txt = this.document.createTextNode('p'); range.insertNode(txt); } doJustify(range,align); if(txt){ range.setStartBefore(txt).collapse(true); domUtils.remove(txt); } range.select(); } return true; }, queryCommandValue : function() { var startNode = this.selection.getStart(), value = domUtils.getComputedStyle(startNode,'text-align'); return defaultValue[value] ? value : 'left'; }, queryCommandState : function(){ return this.highlight ? -1 : 0; } } })(); ///import core ///commands 加粗,斜体,上标,下标 ///commandsName Bold,Italic,Subscript,Superscript ///commandsTitle 加粗,加斜,下标,上标 /** * b u i等基础功能实现 * @function * @name baidu.editor.execCommands * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。 */ UE.plugins['basestyle'] = function(){ var basestyles = { 'bold':['strong','b'], 'italic':['em','i'], 'subscript':['sub'], 'superscript':['sup'] }, getObj = function(editor,tagNames){ //var start = editor.selection.getStart(); var path = editor.selection.getStartElementPath(); // return domUtils.findParentByTagName( start, tagNames, true ) return utils.findNode(path,tagNames); }, me = this; for ( var style in basestyles ) { (function( cmd, tagNames ) { me.commands[cmd] = { execCommand : function( cmdName ) { var range = new dom.Range(me.document),obj = ''; //table的处理 if(me.currentSelectedArr && me.currentSelectedArr.length > 0){ for(var i=0,ci;ci=me.currentSelectedArr[i++];){ if(ci.style.display != 'none'){ range.selectNodeContents(ci).select(); //trace:943 !obj && (obj = getObj(this,tagNames)); if(cmdName == 'superscript' || cmdName == 'subscript'){ if(!obj || obj.tagName.toLowerCase() != cmdName) range.removeInlineStyle(['sub','sup']) } obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] ) } } range.selectNodeContents(me.currentSelectedArr[0]).select(); }else{ range = me.selection.getRange(); obj = getObj(this,tagNames); if ( range.collapsed ) { if ( obj ) { var tmpText = me.document.createTextNode(''); range.insertNode( tmpText ).removeInlineStyle( tagNames ); range.setStartBefore(tmpText); domUtils.remove(tmpText); } else { var tmpNode = range.document.createElement( tagNames[0] ); if(cmdName == 'superscript' || cmdName == 'subscript'){ tmpText = me.document.createTextNode(''); range.insertNode(tmpText) .removeInlineStyle(['sub','sup']) .setStartBefore(tmpText) .collapse(true); } range.insertNode( tmpNode ).setStart( tmpNode, 0 ); } range.collapse( true ) } else { if(cmdName == 'superscript' || cmdName == 'subscript'){ if(!obj || obj.tagName.toLowerCase() != cmdName) range.removeInlineStyle(['sub','sup']) } obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] ) } range.select(); } return true; }, queryCommandState : function() { if(this.highlight){ return -1; } return getObj(this,tagNames) ? 1 : 0; } } })( style, basestyles[style] ); } }; ///import core ///commands 清除格式 ///commandsName RemoveFormat ///commandsTitle 清除格式 /** * @description 清除格式 * @name baidu.editor.execCommand * @param {String} cmdName removeformat清除格式命令 * @param {String} tags 以逗号隔开的标签。如:span,a * @param {String} style 样式 * @param {String} attrs 属性 * @param {String} notIncluedA 是否把a标签切开 * @author zhanyi */ UE.commands['removeformat'] = { execCommand : function( cmdName, tags, style, attrs,notIncludeA ) { var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) , removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ), range = new dom.Range( this.document ), bookmark,node,parent, filter = function( node ) { return node.nodeType == 1; }; function isRedundantSpan (node) { if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span') return 0; if (browser.ie) { //ie 下判断实效,所以只能简单用style来判断 //return node.style.cssText == '' ? 1 : 0; var attrs = node.attributes; if ( attrs.length ) { for ( var i = 0,l = attrs.length; i<l; i++ ) { if ( attrs[i].specified ) { return 0; } } return 1; } } return !node.attributes.length } function doRemove( range ) { var bookmark1 = range.createBookmark(); if ( range.collapsed ) { range.enlarge( true ); } //不能把a标签切了 if(!notIncludeA){ var aNode = domUtils.findParentByTagName(range.startContainer,'a',true); if(aNode){ range.setStartBefore(aNode) } aNode = domUtils.findParentByTagName(range.endContainer,'a',true); if(aNode){ range.setEndAfter(aNode) } } bookmark = range.createBookmark(); node = bookmark.start; //切开始 while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) { domUtils.breakParent( node, parent ); domUtils.clearEmptySibling( node ); } if ( bookmark.end ) { //切结束 node = bookmark.end; while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) { domUtils.breakParent( node, parent ); domUtils.clearEmptySibling( node ); } //开始去除样式 var current = domUtils.getNextDomNode( bookmark.start, false, filter ), next; while ( current ) { if ( current == bookmark.end ) { break; } next = domUtils.getNextDomNode( current, true, filter ); if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) { if ( tagReg.test( current.tagName ) ) { if ( style ) { domUtils.removeStyle( current, style ); if ( isRedundantSpan( current ) && style != 'text-decoration') domUtils.remove( current, true ); } else { domUtils.remove( current, true ) } } else { //trace:939 不能把list上的样式去掉 if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){ domUtils.removeAttributes( current, removeFormatAttributes ); if ( isRedundantSpan( current ) ) domUtils.remove( current, true ); } } } current = next; } } //trace:1035 //trace:1096 不能把td上的样式去掉,比如边框 var pN = bookmark.start.parentNode; if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){ domUtils.removeAttributes( pN,removeFormatAttributes ); } pN = bookmark.end.parentNode; if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){ domUtils.removeAttributes( pN,removeFormatAttributes ); } range.moveToBookmark( bookmark ).moveToBookmark(bookmark1); //清除冗余的代码 <b><bookmark></b> var node = range.startContainer, tmp, collapsed = range.collapsed; while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){ tmp = node.parentNode; range.setStartBefore(node); //trace:937 //更新结束边界 if(range.startContainer === range.endContainer){ range.endOffset--; } domUtils.remove(node); node = tmp; } if(!collapsed){ node = range.endContainer; while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){ tmp = node.parentNode; range.setEndBefore(node); domUtils.remove(node); node = tmp; } } } if ( this.currentSelectedArr && this.currentSelectedArr.length ) { for ( var i = 0,ci; ci = this.currentSelectedArr[i++]; ) { range.selectNodeContents( ci ); doRemove( range ); } range.selectNodeContents( this.currentSelectedArr[0] ).select(); } else { range = this.selection.getRange(); doRemove( range ); range.select(); } }, queryCommandState : function(){ return this.highlight ? -1 :0; } }; ///import core ///import plugins\removeformat.js ///commands 字体颜色,背景色,字号,字体,下划线,删除线 ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线 /** * @description 字体 * @name baidu.editor.execCommand * @param {String} cmdName 执行的功能名称 * @param {String} value 传入的值 */ (function() { var fonts = { 'forecolor':'color', 'backcolor':'background-color', 'fontsize':'font-size', 'fontfamily':'font-family', 'underline':'text-decoration', 'strikethrough':'text-decoration' }; for ( var p in fonts ) { (function( cmd, style ) { UE.commands[cmd] = { execCommand : function( cmdName, value ) { value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' : 'line-through'); var me = this, range = this.selection.getRange(), text; if ( value == 'default' ) { if(range.collapsed){ text = me.document.createTextNode('font'); range.insertNode(text).select() } me.execCommand( 'removeFormat', 'span,a', style); if(text){ range.setStartBefore(text).setCursor(); domUtils.remove(text) } } else { if(me.currentSelectedArr && me.currentSelectedArr.length > 0){ for(var i=0,ci;ci=me.currentSelectedArr[i++];){ range.selectNodeContents(ci); range.applyInlineStyle( 'span', {'style':style + ':' + value} ); } range.selectNodeContents(this.currentSelectedArr[0]).select(); }else{ if ( !range.collapsed ) { if((cmd == 'underline'||cmd=='strikethrough') && me.queryCommandValue(cmd)){ me.execCommand( 'removeFormat', 'span,a', style ); } range = me.selection.getRange(); range.applyInlineStyle( 'span', {'style':style + ':' + value} ).select(); } else { var span = domUtils.findParentByTagName(range.startContainer,'span',true); text = me.document.createTextNode('font'); if(span && !span.children.length && !span[browser.ie ? 'innerText':'textContent'].replace(fillCharReg,'').length){ //for ie hack when enter range.insertNode(text); if(cmd == 'underline'||cmd=='strikethrough'){ range.selectNode(text).select(); me.execCommand( 'removeFormat','span,a', style, null ); span = domUtils.findParentByTagName(text,'span',true); range.setStartBefore(text) } span.style.cssText = span.style.cssText + ';' + style + ':' + value; range.collapse(true).select(); }else{ range.insertNode(text); range.selectNode(text).select(); span = range.document.createElement( 'span' ); if(cmd == 'underline'||cmd=='strikethrough'){ //a标签内的不处理跳过 if(domUtils.findParentByTagName(text,'a',true)){ range.setStartBefore(text).setCursor(); domUtils.remove(text); return; } me.execCommand( 'removeFormat','span,a', style ); } span.style.cssText = style + ':' + value; text.parentNode.insertBefore(span,text); //修复,span套span 但样式不继承的问题 if(!browser.ie || browser.ie && browser.version == 9){ var spanParent = span.parentNode; while(!domUtils.isBlockElm(spanParent)){ if(spanParent.tagName == 'SPAN'){ span.style.cssText = spanParent.style.cssText + span.style.cssText; } spanParent = spanParent.parentNode; } } range.setStart(span,0).setCursor(); //trace:981 //domUtils.mergToParent(span) } domUtils.remove(text) } } } return true; }, queryCommandValue : function (cmdName) { var startNode = this.selection.getStart(); //trace:946 if(cmdName == 'underline'||cmdName=='strikethrough' ){ var tmpNode = startNode,value; while(tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)){ if(tmpNode.nodeType == 1){ value = domUtils.getComputedStyle( tmpNode, style ); if(value != 'none'){ return value; } } tmpNode = tmpNode.parentNode; } return 'none' } return domUtils.getComputedStyle( startNode, style ); }, queryCommandState : function(cmdName){ if(this.highlight){ return -1; } if(!(cmdName == 'underline'||cmdName=='strikethrough')) return 0; return this.queryCommandValue(cmdName) == (cmdName == 'underline' ? 'underline' : 'line-through') } } })( p, fonts[p] ); } })();///import core /** * @description 插入内容 * @name baidu.editor.execCommand * @param {String} cmdName inserthtml插入内容的命令 * @param {String} html 要插入的内容 * @author zhanyi */ UE.commands['inserthtml'] = { execCommand: function (command,html){ var me = this, range,deletedElms, i,ci, div, tds = me.currentSelectedArr; range = me.selection.getRange(); div = range.document.createElement( 'div' ); div.style.display = 'inline'; div.innerHTML = utils.trim( html ); try{ me.adjustTable && me.adjustTable(div); }catch(e){} if(tds && tds.length){ for(var i=0,ti;ti=tds[i++];){ ti.className = '' } tds[0].innerHTML = ''; range.setStart(tds[0],0).collapse(true); me.currentSelectedArr = []; } if ( !range.collapsed ) { range.deleteContents(); if(range.startContainer.nodeType == 1){ var child = range.startContainer.childNodes[range.startOffset],pre; if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){ range.setEnd(pre,pre.childNodes.length).collapse(); while(child.firstChild){ pre.appendChild(child.firstChild); } domUtils.remove(child); } } } var child,parent,pre,tmp,hadBreak = 0; while ( child = div.firstChild ) { range.insertNode( child ); if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){ parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } ); if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){ if(!dtd[parent.tagName][child.nodeName]){ pre = parent; }else{ tmp = child.parentNode; while (tmp !== parent){ pre = tmp; tmp = tmp.parentNode; } } domUtils.breakParent( child, pre || tmp ); //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p> var pre = child.previousSibling; domUtils.trimWhiteTextNode(pre); if(!pre.childNodes.length){ domUtils.remove(pre); } hadBreak = 1; } } var next = child.nextSibling; if(!div.firstChild && next && domUtils.isBlockElm(next)){ range.setStart(next,0).collapse(true); break; } range.setEndAfter( child ).collapse(); } // if(!range.startContainer.childNodes[range.startOffset] && domUtils.isBlockElm(range.startContainer)){ // next = editor.document.createElement('br'); // range.insertNode(next); // range.collapse(true); // } //block为空无法定位光标 child = range.startContainer; //用chrome可能有空白展位符 if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){ child.innerHTML = browser.ie ? '' : '<br/>' } //加上true因为在删除表情等时会删两次,第一次是删的fillData range.select(true); setTimeout(function(){ range = me.selection.getRange(); range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0); },200) } }; ///import core ///import plugins\inserthtml.js ///commands 特殊字符 ///commandsName Spechars ///commandsTitle 特殊字符 ///commandsDialog dialogs\spechars\spechars.html UE.commands['spechars'] = { queryCommandState : function(){ return this.highlight ? -1 :0; } }; ///import core ///commands 为非ie浏览器自动添加a标签 ///commandsName AutoLink ///commandsTitle 自动增加链接 /** * @description 为非ie浏览器自动添加a标签 * @author zhanyi */ UE.plugins['autolink'] = function() { var cont = 0; if (browser.ie) { return; } var me = this; me.addListener('reset',function(){ cont = 0; }); me.addListener('keydown', function(type, evt) { var keyCode = evt.keyCode || evt.which; if (keyCode == 32 || keyCode == 13) { var sel = me.selection.getNative(), range = sel.getRangeAt(0).cloneRange(), offset, charCode; var start = range.startContainer; while (start.nodeType == 1 && range.startOffset > 0) { start = range.startContainer.childNodes[range.startOffset - 1]; if (!start) break; range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length); range.collapse(true); start = range.startContainer; } do{ if (range.startOffset == 0) { start = range.startContainer.previousSibling; while (start && start.nodeType == 1) { start = start.lastChild; } if (!start || domUtils.isFillChar(start)) break; offset = start.nodeValue.length; } else { start = range.startContainer; offset = range.startOffset; } range.setStart(start, offset - 1); charCode = range.toString().charCodeAt(0); } while (charCode != 160 && charCode != 32); if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) { while(range.toString().length){ if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){ break; } try{ range.setStart(range.startContainer,range.startOffset+1) }catch(e){ range.setStart(range.startContainer.nextSibling,0) } } var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href; me.undoManger && me.undoManger.save(); a.appendChild(range.extractContents()); a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,''); href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),''); href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href; a.setAttribute('data_ue_src',href); a.href = href; range.insertNode(a); a.parentNode.insertBefore(text, a.nextSibling); range.setStart(text, 0); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); me.undoManger && me.undoManger.save(); } } }) }; ///import core ///commands 超链接,取消链接 ///commandsName Link,Unlink ///commandsTitle 超链接,取消链接 ///commandsDialog dialogs\link\link.html /** * 超链接 * @function * @name baidu.editor.execCommand * @param {String} cmdName link插入超链接 * @param {Object} options url地址,title标题,target是否打开新页 * @author zhanyi */ /** * 取消链接 * @function * @name baidu.editor.execCommand * @param {String} cmdName unlink取消链接 * @author zhanyi */ (function() { function optimize( range ) { var start = range.startContainer,end = range.endContainer; if ( start = domUtils.findParentByTagName( start, 'a', true ) ) { range.setStartBefore( start ) } if ( end = domUtils.findParentByTagName( end, 'a', true ) ) { range.setEndAfter( end ) } } UE.commands['unlink'] = { execCommand : function() { var as, range = new dom.Range(this.document), tds = this.currentSelectedArr, bookmark; if(tds && tds.length >0){ for(var i=0,ti;ti=tds[i++];){ as = domUtils.getElementsByTagName(ti,'a'); for(var j=0,aj;aj=as[j++];){ domUtils.remove(aj,true); } } if(domUtils.isEmptyNode(tds[0])){ range.setStart(tds[0],0).setCursor(); }else{ range.selectNodeContents(tds[0]).select() } }else{ range = this.selection.getRange(); if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){ return; } bookmark = range.createBookmark(); optimize( range ); range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select(); } }, queryCommandState : function(){ return !this.highlight && this.queryCommandValue('link') ? 0 : -1; } }; function doLink(range,opt){ optimize( range = range.adjustmentBoundary() ); var start = range.startContainer; if(start.nodeType == 1){ start = start.childNodes[range.startOffset]; if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){ start.innerHTML = opt.href; } } range.removeInlineStyle( 'a' ); if ( range.collapsed ) { var a = range.document.createElement( 'a' ); domUtils.setAttributes( a, opt ); a.innerHTML = opt.href; range.insertNode( a ).selectNode( a ); } else { range.applyInlineStyle( 'a', opt ) } } UE.commands['link'] = { queryCommandState : function(){ return this.highlight ? -1 :0; }, execCommand : function( cmdName, opt ) { var range = new dom.Range(this.document), tds = this.currentSelectedArr; if(tds && tds.length){ for(var i=0,ti;ti=tds[i++];){ if(domUtils.isEmptyNode(ti)){ ti.innerHTML = opt.href } doLink(range.selectNodeContents(ti),opt) } range.selectNodeContents(tds[0]).select() }else{ doLink(range=this.selection.getRange(),opt); range.collapse().select(browser.gecko ? true : false); } }, queryCommandValue : function() { var range = new dom.Range(this.document), tds = this.currentSelectedArr, as, node; if(tds && tds.length){ for(var i=0,ti;ti=tds[i++];){ as = ti.getElementsByTagName('a'); if(as[0]) return as[0] } }else{ range = this.selection.getRange(); if ( range.collapsed ) { node = this.selection.getStart(); if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) ) { return node; } } else { //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a range.shrinkBoundary(); var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset], end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1], common = range.getCommonAncestor(); node = domUtils.findParentByTagName( common, 'a', true ); if ( !node && common.nodeType == 1){ var as = common.getElementsByTagName( 'a' ), ps,pe; for ( var i = 0,ci; ci = as[i++]; ) { ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end); if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS) && (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS) ) { node = ci; break; } } } return node; } } } }; })(); ///import core ///commandsName catchRemoteImage /** * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片 * */ UE.plugins['catchremoteimage'] = function (){ if(!this.options.catchRemoteImageEnable)return; var ajax = UE.ajax, me = this, localDomain = me.options.localDomain, catcherUrl = me.options.catcherUrl, separater="ue_separate_ue"; function catchremoteimage(imgs,callbacks) { var submitStr = imgs.join(separater); ajax.request( catcherUrl, { content:submitStr, timeout:60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值 onsuccess:callbacks["success"], onerror:callbacks["error"] } ) } me.addListener("afterpaste",function(){ me.fireEvent("catchRemoteImage"); }); me.addListener( "catchRemoteImage", function () { var remoteImages=[]; var imgs = domUtils.getElementsByTagName(me.document,"img"); for(var i = 0,ci;ci=imgs[i++];){ if(ci.getAttribute("word_img"))continue; var src = ci.getAttribute("data_ue_src") || ci.src||""; if(/^(https?|ftp):/i.test(src) && src.indexOf(localDomain)==-1 ) { remoteImages.push(src); } } if(remoteImages.length){ catchremoteimage(remoteImages,{ //成功抓取 success:function (xhr){ try{ var info = eval("("+xhr.responseText+")"); }catch(e){ return; } var srcUrls = info.srcUrl.split(separater), urls = info.url.split(separater); for(var i=0,ci;ci=imgs[i++];){ var src = ci.getAttribute("data_ue_src")||ci.src||""; for(var j=0,cj;cj=srcUrls[j++];){ var url = urls[j-1]; if(src == cj && url!="error"){ //抓取失败时不做替换处理 //地址修正 var newSrc = me.options.UEDITOR_HOME_URL +"server/"+url; domUtils.setAttributes(ci,{ "src":newSrc, "data_ue_src":newSrc }); break; } } } }, //回调失败,本次请求超时 error:function(){ me.fireEvent("catchremoteerror"); } }) } } ) };///import core ///import plugins\inserthtml.js ///import plugins\catchremoteimage.js ///commands 插入图片,操作图片的对齐方式 ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter ///commandsTitle 图片,默认,居左,居右,居中 ///commandsDialog dialogs\image\image.html /** * Created by . * User: zhanyi * for image */ UE.commands['imagefloat'] = { execCommand : function (cmd, align){ var me = this, range = me.selection.getRange(); if(!range.collapsed ){ var img = range.getClosedNode(); if(img && img.tagName == 'IMG'){ switch (align){ case 'left': case 'right': case 'none': var pN = img.parentNode,tmpNode,pre,next; while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){ pN = pN.parentNode; } tmpNode = pN; if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){ if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){ pre = tmpNode.previousSibling; next = tmpNode.nextSibling; if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){ pre.appendChild(tmpNode.firstChild); while(next.firstChild){ pre.appendChild(next.firstChild) } domUtils.remove(tmpNode); domUtils.remove(next); }else{ domUtils.setStyle(tmpNode,'text-align','') } } range.selectNode(img).select() } domUtils.setStyle(img,'float',align); break; case 'center': if(me.queryCommandValue('imagefloat') != 'center'){ pN = img.parentNode; domUtils.setStyle(img,'float','none'); tmpNode = img; while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1 && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){ tmpNode = pN; pN = pN.parentNode; } range.setStartBefore(tmpNode).setCursor(false); pN = me.document.createElement('div'); pN.appendChild(tmpNode); domUtils.setStyle(tmpNode,'float',''); me.execCommand('insertHtml','<p id="_img_parent_tmp" style="text-align:center">'+pN.innerHTML+'</p>'); tmpNode = me.document.getElementById('_img_parent_tmp'); tmpNode.removeAttribute('id'); tmpNode = tmpNode.firstChild; range.selectNode(tmpNode).select(); //去掉后边多余的元素 next = tmpNode.parentNode.nextSibling; if(next && domUtils.isEmptyNode(next)){ domUtils.remove(next) } } break; } } } }, queryCommandValue : function() { var range = this.selection.getRange(), startNode,floatStyle; if(range.collapsed){ return 'none'; } startNode = range.getClosedNode(); if(startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG'){ floatStyle = domUtils.getComputedStyle(startNode,'float'); if(floatStyle == 'none'){ floatStyle = domUtils.getComputedStyle(startNode.parentNode,'text-align') == 'center' ? 'center' : floatStyle } return { left : 1, right : 1, center : 1 }[floatStyle] ? floatStyle : 'none' } return 'none' }, queryCommandState : function(){ if(this.highlight){ return -1; } var range = this.selection.getRange(), startNode; if(range.collapsed){ return -1; } startNode = range.getClosedNode(); if(startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG'){ return 0; } return -1; } }; UE.commands['insertimage'] = { execCommand : function (cmd, opt){ opt = utils.isArray(opt) ? opt : [opt]; if(!opt.length) return; var me = this, range = me.selection.getRange(), img = range.getClosedNode(); if(img && /img/i.test( img.tagName ) && img.className != "edui-faked-video" &&!img.getAttribute("word_img") ){ var first = opt.shift(); var floatStyle = first['floatStyle']; delete first['floatStyle']; //// img.style.border = (first.border||0) +"px solid #000"; //// img.style.margin = (first.margin||0) +"px"; // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000"; domUtils.setAttributes(img,first); me.execCommand('imagefloat',floatStyle); if(opt.length > 0){ range.setStartAfter(img).setCursor(false,true); me.execCommand('insertimage',opt); } }else{ var html = [],str = '',ci; ci = opt[0]; if(opt.length == 1){ str = '<img src="'+ci.src+'" '+ (ci.data_ue_src ? ' data_ue_src="' + ci.data_ue_src +'" ':'') + (ci.width ? 'width="'+ci.width+'" ':'') + (ci.height ? ' height="'+ci.height+'" ':'') + (ci['floatStyle']&&ci['floatStyle']!='center' ? ' style="float:'+ci['floatStyle']+';"':'') + (ci.title?' title="'+ci.title+'"':'') + ' border="'+ (ci.border||0) + '" hspace = "'+(ci.hspace||0)+'" vspace = "'+(ci.vspace||0)+'" />'; if(ci['floatStyle'] == 'center'){ str = '<p style="text-align: center">'+str+'</p>' } html.push(str) }else{ for(var i=0;ci=opt[i++];){ str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="'+ci.src+'" '+ (ci.width ? 'width="'+ci.width+'" ':'') + (ci.data_ue_src ? ' data_ue_src="' + ci.data_ue_src +'" ':'') + (ci.height ? ' height="'+ci.height+'" ':'') + ' style="' + (ci['floatStyle']&&ci['floatStyle']!='center' ? 'float:'+ci['floatStyle']+';':'') + (ci.border||'') + '" ' + (ci.title?' title="'+ci.title+'"':'') + ' /></p>'; // if(ci['floatStyle'] == 'center'){ // str = '<p style="text-align: center">'+str+'</p>' // } html.push(str) } } me.execCommand('insertHtml',html.join('')); } }, queryCommandState : function(){ return this.highlight ? -1 :0; } };///import core ///commands 预览 ///commandsName Preview ///commandsTitle 预览 /** * 预览 * @function * @name baidu.editor.execCommand * @param {String} cmdName preview预览编辑器内容 */ UE.commands['preview'] = { execCommand : function(){ var me = this, w = window.open('', '_blank', ""), d = w.document, css = me.document.getElementById("syntaxhighlighter_css"), js = document.getElementById("syntaxhighlighter_js"), style = "<style type='text/css'>" + me.options.initialStyle + "</style>", cont = me.getContent(); if(browser.ie){ cont = cont.replace(/<\s*br\s*\/?\s*>/gi,'<br/><br/>') } d.open(); d.write('<html><head>'+style+'<link rel="stylesheet" type="text/css" href="'+me.options.UEDITOR_HOME_URL+utils.unhtml( this.options.iframeCssUrl ) + '"/>'+ (css ? '<link rel="stylesheet" type="text/css" href="' + css.href + '"/>' : '') + (css ? ' <script type="text/javascript" charset="utf-8" src="'+js.src+'"></script>':'') +'<title></title></head><body >' + cont + (css ? '<script type="text/javascript">'+(baidu.editor.browser.ie ? 'window.onload = function(){SyntaxHighlighter.all()};' : 'SyntaxHighlighter.all();')+ 'setTimeout(function(){' + 'for(var i=0,di;di=SyntaxHighlighter.highlightContainers[i++];){' + 'var tds = di.getElementsByTagName("td");' + 'for(var j=0,li,ri;li=tds[0].childNodes[j];j++){' + 'ri = tds[1].firstChild.childNodes[j];' + 'ri.style.height = li.style.height = ri.offsetHeight + "px";' + '}' + '}},100)</script>':'') + '</body></html>'); d.close(); }, notNeedUndo : 1 }; ///import core ///commands 清空文档 ///commandsName ClearDoc ///commandsTitle 清空文档 /** * * 清空文档 * @function * @name baidu.editor.execCommand * @param {String} cmdName cleardoc清空文档 */ UE.commands['cleardoc'] = { execCommand : function( cmdName) { var me = this, enterTag = me.options.enterTag, range = me.selection.getRange(); if(enterTag == "br"){ me.body.innerHTML = "<br/>"; range.setStart(me.body,0).setCursor(); }else{ me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>"; range.setStart(me.body.firstChild,0).setCursor(false,true); } } }; ///import core ///import plugins/inserthtml.js ///import plugins/undo.js ///import plugins/serialize.js ///commands 粘贴 ///commandsName PastePlain ///commandsTitle 纯文本粘贴模式 /* ** @description 粘贴 * @author zhanyi */ (function() { function getClipboardData( callback ) { var doc = this.document; if ( doc.getElementById( 'baidu_pastebin' ) ) { return; } var range = this.selection.getRange(), bk = range.createBookmark(), //创建剪贴的容器div pastebin = doc.createElement( 'div' ); pastebin.id = 'baidu_pastebin'; // Safari 要求div必须有内容,才能粘贴内容进来 browser.webkit && pastebin.appendChild( doc.createTextNode( domUtils.fillChar + domUtils.fillChar ) ); doc.body.appendChild( pastebin ); //trace:717 隐藏的span不能得到top //bk.start.innerHTML = '&nbsp;'; bk.start.style.display = ''; pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" + //要在现在光标平行的位置加入,否则会出现跳动的问题 domUtils.getXY( bk.start ).y + 'px'; range.selectNodeContents( pastebin ).select( true ); setTimeout( function() { if (browser.webkit) { for(var i=0,pastebins = doc.querySelectorAll('#baidu_pastebin'),pi;pi=pastebins[i++];){ if(domUtils.isEmptyNode(pi)){ domUtils.remove(pi) }else{ pastebin = pi; break; } } } try{ pastebin.parentNode.removeChild(pastebin); }catch(e){} range.moveToBookmark( bk ).select(true); callback( pastebin ); }, 0 ); } UE.plugins['paste'] = function() { var me = this; var word_img_flag = {flag:""}; var pasteplain = me.options.pasteplain; var modify_num = {flag:""}; me.commands['pasteplain'] = { queryCommandState: function (){ return pasteplain; }, execCommand: function (){ pasteplain = !pasteplain|0; }, notNeedUndo : 1 }; function filter(div){ var html; if ( div.firstChild ) { //去掉cut中添加的边界值 var nodes = domUtils.getElementsByTagName(div,'span'); for(var i=0,ni;ni=nodes[i++];){ if(ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end'){ domUtils.remove(ni) } } if(browser.webkit){ var brs = div.querySelectorAll('div br'); for(var i=0,bi;bi=brs[i++];){ var pN = bi.parentNode; if(pN.tagName == 'DIV' && pN.childNodes.length ==1){ pN.innerHTML = '<p><br/></p>'; domUtils.remove(pN) } } var divs = div.querySelectorAll('#baidu_pastebin'); for(var i=0,di;di=divs[i++];){ var tmpP = me.document.createElement('p'); di.parentNode.insertBefore(tmpP,di); while(di.firstChild){ tmpP.appendChild(di.firstChild) } domUtils.remove(di) } var metas = div.querySelectorAll('meta'); for(var i=0,ci;ci=metas[i++];){ domUtils.remove(ci); } var brs = div.querySelectorAll('br'); for(i=0;ci=brs[i++];){ if(/^apple-/.test(ci)){ domUtils.remove(ci) } } } if(browser.gecko){ var dirtyNodes = div.querySelectorAll('[_moz_dirty]') for(i=0;ci=dirtyNodes[i++];){ ci.removeAttribute( '_moz_dirty' ) } } if(!browser.ie ){ var spans = div.querySelectorAll('span.apple-style-span'); for(var i=0,ci;ci=spans[i++];){ domUtils.remove(ci,true); } } html = div.innerHTML; var f = me.serialize; if(f){ //如果过滤出现问题,捕获它,直接插入内容,避免出现错误导致粘贴整个失败 try{ var node = f.transformInput( f.parseHTML( //todo: 暂时不走dtd的过滤 f.word(html)//, true ),word_img_flag ); //trace:924 //纯文本模式也要保留段落 node = f.filter(node,pasteplain ? { whiteList: { 'p': {'br':1,'BR':1}, 'br':{'$':{}}, 'div':{'br':1,'BR':1,'$':{}}, 'li':{'$':{}}, 'tr':{'td':1,'$':{}}, 'td':{'$':{}} }, blackList: { 'style':1, 'script':1, 'object':1 } } : null, !pasteplain ? modify_num : null); if(browser.webkit){ var length = node.children.length, child; while((child = node.children[length-1]) && child.tag == 'br'){ node.children.splice(length-1,1); length = node.children.length; } } html = f.toHTML(node,pasteplain) }catch(e){} } //自定义的处理 html = {'html':html}; me.fireEvent('beforepaste',html); me.execCommand( 'insertHtml',html.html); me.fireEvent("afterpaste"); } } me.addListener('ready',function(){ domUtils.on(me.body,'cut',function(){ var range = me.selection.getRange(); if(!range.collapsed && me.undoManger){ me.undoManger.save() } }); //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理 domUtils.on(me.body, browser.ie ? 'keydown' : 'paste',function(e){ if(browser.ie && (!e.ctrlKey || e.keyCode != '86')) return; getClipboardData.call( me, function( div ) { filter(div); function hideMsg(){ me.ui.hideToolbarMsg(); me.removeListener("selectionchange",hideMsg); } if ( modify_num.flag && me.ui){ me.ui.showToolbarMsg( me.options.messages.pasteMsg, word_img_flag.flag ); modify_num.flag = ""; //trance:为了解决fireevent (selectionchange)事件的延时 setTimeout(function(){ me.addListener("selectionchange",hideMsg); },100); } if ( word_img_flag.flag && !me.queryCommandState("pasteplain") && me.ui){ me.ui.showToolbarMsg( me.options.messages.pasteWordImgMsg,true); word_img_flag.flag = ''; //trance:为了解决fireevent (selectionchange)事件的延时 setTimeout(function(){ me.addListener("selectionchange",hideMsg); },100); } } ); }) }); } })(); ///import core ///commands 右键菜单 ///commandsName ContextMenu ///commandsTitle 右键菜单 /** * 右键菜单 * @function * @name baidu.editor.plugins.contextmenu * @author zhanyi */ UE.plugins['contextmenu'] = function () { var me = this, menu, items = me.options.contextMenu; if(!items || items.length==0) return; var uiUtils = UE.ui.uiUtils; me.addListener('contextmenu',function(type,evt){ var offset = uiUtils.getViewportOffsetByEvent(evt); me.fireEvent('beforeselectionchange'); if (menu) menu.destroy(); for (var i = 0,ti,contextItems = []; ti = items[i]; i++) { var last; (function(item) { if (item == '-') { if ((last = contextItems[contextItems.length - 1 ] ) && last !== '-') contextItems.push('-'); } else if (item.group) { for (var j = 0,cj,subMenu = []; cj = item.subMenu[j]; j++) { (function(subItem) { if (subItem == '-') { if ((last = subMenu[subMenu.length - 1 ] ) && last !== '-') subMenu.push('-'); } else { if (me.queryCommandState(subItem.cmdName) != -1) { subMenu.push({ 'label':subItem.label, className: 'edui-for-' + subItem.cmdName + (subItem.value || ''), onclick : subItem.exec ? function() { subItem.exec.call(me) } : function() { me.execCommand(subItem.cmdName, subItem.value) } }) } } })(cj) } if (subMenu.length) { contextItems.push({ 'label' : item.group, className: 'edui-for-' + item.icon, 'subMenu' : { items: subMenu, editor:me } }) } } else { if (me.queryCommandState(item.cmdName) != -1) { //highlight todo if(item.cmdName == 'highlightcode' && me.queryCommandState(item.cmdName) == 0) return; contextItems.push({ 'label':item.label, className: 'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')), onclick : item.exec ? function() { item.exec.call(me) } : function() { me.execCommand(item.cmdName, item.value) } }) } } })(ti) } if (contextItems[contextItems.length - 1] == '-') contextItems.pop(); menu = new UE.ui.Menu({ items: contextItems, editor:me }); menu.render(); menu.showAt(offset); domUtils.preventDefault(evt); if(browser.ie){ var ieRange; try{ ieRange = me.selection.getNative().createRange(); }catch(e){ return; } if(ieRange.item){ var range = new dom.Range(me.document); range.selectNode(ieRange.item(0)).select(true,true); } } }) }; ///import core ///commands 当输入内容超过编辑器高度时,编辑器自动增高 ///commandsName AutoHeight,autoHeightEnabled ///commandsTitle 自动增高 /** * @description 自动伸展 * @author zhanyi */ UE.plugins['autoheight'] = function () { var me = this; //提供开关,就算加载也可以关闭 me.autoHeightEnabled = me.options.autoHeightEnabled; if (!me.autoHeightEnabled)return; var bakOverflow, span, tmpNode, lastHeight = 0, currentHeight, timer; function adjustHeight() { clearTimeout(timer); timer = setTimeout(function () { if (me.queryCommandState('source') != 1) { if (!span) { span = me.document.createElement('span'); //trace:1764 span.style.cssText = 'display:block;width:0;margin:0;padding:0;border:0;clear:both;'; span.innerHTML = '.'; } tmpNode = span.cloneNode(true); me.body.appendChild(tmpNode); currentHeight = Math.max(domUtils.getXY(tmpNode).y + tmpNode.offsetHeight, me.options.minFrameHeight); if (currentHeight != lastHeight) { me.setHeight(currentHeight); lastHeight = currentHeight; } domUtils.remove(tmpNode); } }, 50) } me.addListener('destroy', function () { me.removeListener('contentchange', adjustHeight); me.removeListener('keyup', adjustHeight); me.removeListener('mouseup', adjustHeight); }); me.enableAutoHeight = function () { if(!me.autoHeightEnabled)return; var doc = me.document; me.autoHeightEnabled = true; bakOverflow = doc.body.style.overflowY; doc.body.style.overflowY = 'hidden'; me.addListener('contentchange', adjustHeight); me.addListener('keyup', adjustHeight); me.addListener('mouseup', adjustHeight); //ff不给事件算得不对 setTimeout(function () { adjustHeight(); }, browser.gecko ? 100 : 0); me.fireEvent('autoheightchanged', me.autoHeightEnabled); }; me.disableAutoHeight = function () { me.body.style.overflowY = bakOverflow || ''; me.removeListener('contentchange', adjustHeight); me.removeListener('keyup', adjustHeight); me.removeListener('mouseup', adjustHeight); me.autoHeightEnabled = false; me.fireEvent('autoheightchanged', me.autoHeightEnabled); }; me.addListener('ready', function () { me.enableAutoHeight(); //trace:1764 var timer; domUtils.on(browser.ie ? me.body : me.document,browser.webkit ? 'dragover' : 'drop',function(){ clearTimeout(timer); timer = setTimeout(function(){ adjustHeight() },100) }); }); }; ///import core ///commands 悬浮工具栏 ///commandsName AutoFloat,autoFloatEnabled ///commandsTitle 悬浮工具栏 /* * modified by chengchao01 * * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉! */ UE.plugins['autofloat'] = function() { var uiUtils, LteIE6 = browser.ie && browser.version <= 6, quirks = browser.quirks; function checkHasUI(editor){ if(!editor.ui){ alert('autofloat插件功能依赖于UEditor UI\nautofloat定义位置: _src/plugins/autofloat.js'); throw({ name: '未包含UI文件', message: 'autofloat功能依赖于UEditor UI。autofloat定义位置: _src/plugins/autofloat.js' }); } uiUtils = UE.ui.uiUtils; return 1; } function fixIE6FixedPos(){ var docStyle = document.body.style; docStyle.backgroundImage = 'url("about:blank")'; docStyle.backgroundAttachment = 'fixed'; } var optsAutoFloatEnabled = this.options.autoFloatEnabled; //如果不固定toolbar的位置,则直接退出 if(!optsAutoFloatEnabled){ return; } var me = this, bakCssText, placeHolder = document.createElement('div'), toolbarBox,orgTop, getPosition, flag =true; //ie7模式下需要偏移 function setFloating(){ var toobarBoxPos = domUtils.getXY(toolbarBox), origalFloat = domUtils.getComputedStyle(toolbarBox,'position'), origalLeft = domUtils.getComputedStyle(toolbarBox,'left'); toolbarBox.style.width = toolbarBox.offsetWidth + 'px'; toolbarBox.style.zIndex = me.options.zIndex * 1 + 1; toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox); if (LteIE6 || quirks) { if(toolbarBox.style.position != 'absolute'){ toolbarBox.style.position = 'absolute'; } toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + 'px'; } else { if (browser.ie7Compat && flag) { flag = false; toolbarBox.style.left = getPosition(toolbarBox).left - document.documentElement.getBoundingClientRect().left+2 + 'px'; } if(toolbarBox.style.position != 'fixed'){ toolbarBox.style.position = 'fixed'; toolbarBox.style.top = '0'; ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px'); } } } function unsetFloating(){ flag = true; if(placeHolder.parentNode) placeHolder.parentNode.removeChild(placeHolder); toolbarBox.style.cssText = bakCssText; } function updateFloating(){ var rect3 = getPosition(me.container); if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > 0) { setFloating(); }else{ unsetFloating(); } } var defer_updateFloating = utils.defer(function(){ updateFloating(); },browser.ie ? 200 : 100,true); me.addListener('destroy',function(){ domUtils.un(window, ['scroll','resize'], updateFloating); me.removeListener('keydown', defer_updateFloating); }); me.addListener('ready', function(){ if(checkHasUI(me)){ getPosition = uiUtils.getClientRect; toolbarBox = me.ui.getDom('toolbarbox'); orgTop = getPosition(toolbarBox).top; bakCssText = toolbarBox.style.cssText; placeHolder.style.height = toolbarBox.offsetHeight + 'px'; if(LteIE6){ fixIE6FixedPos(); } me.addListener('autoheightchanged', function (t, enabled){ if (enabled) { domUtils.on(window, ['scroll','resize'], updateFloating); me.addListener('keydown', defer_updateFloating); } else { domUtils.un(window, ['scroll','resize'], updateFloating); me.removeListener('keydown', defer_updateFloating); } }); me.addListener('beforefullscreenchange', function (t, enabled){ if (enabled) { unsetFloating(); } }); me.addListener('fullscreenchanged', function (t, enabled){ if (!enabled) { updateFloating(); } }); me.addListener('sourcemodechanged', function (t, enabled){ setTimeout(function (){ updateFloating(); }); }); } }) }; ///import core ///commands 选区路径 ///commandsName ElementPath,elementPathEnabled ///commandsTitle 选区路径 /** * 选区路径 * @function * @name baidu.editor.execCommand * @param {String} cmdName elementpath选区路径 */ UE.plugins['elementpath'] = function(){ var currentLevel, tagNames, me = this; me.commands['elementpath'] = { execCommand : function( cmdName, level ) { var start = tagNames[level], range = me.selection.getRange(); me.currentSelectedArr && domUtils.clearSelectedArr(me.currentSelectedArr); currentLevel = level*1; if(dtd.$tableContent[start.tagName]){ switch (start.tagName){ case 'TD':me.currentSelectedArr = [start]; start.className = me.options.selectedTdClass; break; case 'TR': var cells = start.cells; for(var i=0,ti;ti=cells[i++];){ me.currentSelectedArr.push(ti); ti.className = me.options.selectedTdClass; } break; case 'TABLE': case 'TBODY': var rows = start.rows; for(var i=0,ri;ri=rows[i++];){ cells = ri.cells; for(var j=0,tj;tj=cells[j++];){ me.currentSelectedArr.push(tj); tj.className = me.options.selectedTdClass; } } } start = me.currentSelectedArr[0]; if(domUtils.isEmptyNode(start)){ range.setStart(start,0).setCursor() }else{ range.selectNodeContents(start).select() } }else{ range.selectNode(start).select() } }, queryCommandValue : function() { //产生一个副本,不能修改原来的startElementPath; var parents = [].concat(this.selection.getStartElementPath()).reverse(), names = []; tagNames = parents; for(var i=0,ci;ci=parents[i];i++){ if(ci.nodeType == 3) continue; var name = ci.tagName.toLowerCase(); if(name == 'img' && ci.getAttribute('anchorname')){ name = 'anchor' } names[i] = name; if(currentLevel == i){ currentLevel = -1; break; } } return names; } } }; ///import core ///commands 字数统计 ///commandsName WordCount,wordCount ///commandsTitle 字数统计 /** * Created by JetBrains WebStorm. * User: taoqili * Date: 11-9-7 * Time: 下午8:18 * To change this template use File | Settings | File Templates. */ UE.commands["wordcount"]={ queryCommandValue:function(cmd,onlyCount){ var length,contentText,reg; if(onlyCount){ reg = new RegExp("[\r\t\n]","g"); contentText = this.getContentTxt().replace(reg,""); return contentText.length; } var open = this.options.wordCount, max= this.options.maximumWords, msg = this.options.messages.wordCountMsg, errMsg=this.options.messages.wordOverFlowMsg; if(!open) return ""; reg = new RegExp("[\r\t\n]","g"); contentText = this.getContentTxt().replace(reg,""); length = contentText.length; if(max-length<0){ return "<span style='color:red;direction: none'>"+errMsg+"</span> " } msg = msg.replace("{#leave}",max-length >= 0 ? max-length:0); msg = msg.replace("{#count}",length); return msg; } };})();
JavaScript
(function(){ var parent = window.parent; //dialog对象 dialog = parent.$EDITORUI[window.frameElement.id.replace(/_iframe$/, '')]; //当前打开dialog的编辑器实例 editor = dialog.editor; UE = parent.UE; domUtils = UE.dom.domUtils; utils = UE.utils; browser = UE.browser; ajax = UE.ajax; $G = function(id){return document.getElementById(id)}; //focus元素 $focus = function(node){ setTimeout(function(){ if(browser.ie){ var r = node.createTextRange(); r.collapse(false); r.select(); }else{ node.focus() } },0) } })();
JavaScript
// Copyright (c) 2009, Baidu Inc. All rights reserved. // // Licensed under the BSD License // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http:// tangram.baidu.com/license.html // // 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. /** * @namespace T Tangram七巧板 * @name T * @version 1.6.0 */ /** * 声明baidu包 * @author: allstar, erik, meizz, berg */ var T, baidu = T = baidu || {version: "1.5.0"}; baidu.guid = "$BAIDU$"; baidu.$$ = window[baidu.guid] = window[baidu.guid] || {global:{}}; /** * 使用flash资源封装的一些功能 * @namespace baidu.flash */ baidu.flash = baidu.flash || {}; /** * 操作dom的方法 * @namespace baidu.dom */ baidu.dom = baidu.dom || {}; /** * 从文档中获取指定的DOM元素 * @name baidu.dom.g * @function * @grammar baidu.dom.g(id) * @param {string|HTMLElement} id 元素的id或DOM元素. * @shortcut g,T.G * @meta standard * @see baidu.dom.q * * @return {HTMLElement|null} 获取的元素,查找不到时返回null,如果参数不合法,直接返回参数. */ baidu.dom.g = function(id) { if (!id) return null; if ('string' == typeof id || id instanceof String) { return document.getElementById(id); } else if (id.nodeName && (id.nodeType == 1 || id.nodeType == 9)) { return id; } return null; }; baidu.g = baidu.G = baidu.dom.g; /** * 操作数组的方法 * @namespace baidu.array */ baidu.array = baidu.array || {}; /** * 遍历数组中所有元素 * @name baidu.array.each * @function * @grammar baidu.array.each(source, iterator[, thisObject]) * @param {Array} source 需要遍历的数组 * @param {Function} iterator 对每个数组元素进行调用的函数,该函数有两个参数,第一个为数组元素,第二个为数组索引值,function (item, index)。 * @param {Object} [thisObject] 函数调用时的this指针,如果没有此参数,默认是当前遍历的数组 * @remark * each方法不支持对Object的遍历,对Object的遍历使用baidu.object.each 。 * @shortcut each * @meta standard * * @returns {Array} 遍历的数组 */ baidu.each = baidu.array.forEach = baidu.array.each = function (source, iterator, thisObject) { var returnValue, item, i, len = source.length; if ('function' == typeof iterator) { for (i = 0; i < len; i++) { item = source[i]; returnValue = iterator.call(thisObject || source, item, i); if (returnValue === false) { break; } } } return source; }; /** * 对语言层面的封装,包括类型判断、模块扩展、继承基类以及对象自定义事件的支持。 * @namespace baidu.lang */ baidu.lang = baidu.lang || {}; /** * 判断目标参数是否为function或Function实例 * @name baidu.lang.isFunction * @function * @grammar baidu.lang.isFunction(source) * @param {Any} source 目标参数 * @version 1.2 * @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate * @meta standard * @returns {boolean} 类型判断结果 */ baidu.lang.isFunction = function (source) { return '[object Function]' == Object.prototype.toString.call(source); }; /** * 判断目标参数是否string类型或String对象 * @name baidu.lang.isString * @function * @grammar baidu.lang.isString(source) * @param {Any} source 目标参数 * @shortcut isString * @meta standard * @see baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate * * @returns {boolean} 类型判断结果 */ baidu.lang.isString = function (source) { return '[object String]' == Object.prototype.toString.call(source); }; baidu.isString = baidu.lang.isString; /** * 判断浏览器类型和特性的属性 * @namespace baidu.browser */ baidu.browser = baidu.browser || {}; /** * 判断是否为opera浏览器 * @property opera opera版本号 * @grammar baidu.browser.opera * @meta standard * @see baidu.browser.ie,baidu.browser.firefox,baidu.browser.safari,baidu.browser.chrome * @returns {Number} opera版本号 */ /** * opera 从10开始不是用opera后面的字符串进行版本的判断 * 在Browser identification最后添加Version + 数字进行版本标识 * opera后面的数字保持在9.80不变 */ baidu.browser.opera = /opera(\/| )(\d+(\.\d+)?)(.+?(version\/(\d+(\.\d+)?)))?/i.test(navigator.userAgent) ? + ( RegExp["\x246"] || RegExp["\x242"] ) : undefined; /** * 在目标元素的指定位置插入HTML代码 * @name baidu.dom.insertHTML * @function * @grammar baidu.dom.insertHTML(element, position, html) * @param {HTMLElement|string} element 目标元素或目标元素的id * @param {string} position 插入html的位置信息,取值为beforeBegin,afterBegin,beforeEnd,afterEnd * @param {string} html 要插入的html * @remark * * 对于position参数,大小写不敏感<br> * 参数的意思:beforeBegin&lt;span&gt;afterBegin this is span! beforeEnd&lt;/span&gt; afterEnd <br /> * 此外,如果使用本函数插入带有script标签的HTML字符串,script标签对应的脚本将不会被执行。 * * @shortcut insertHTML * @meta standard * * @returns {HTMLElement} 目标元素 */ baidu.dom.insertHTML = function (element, position, html) { element = baidu.dom.g(element); var range,begin; if (element.insertAdjacentHTML && !baidu.browser.opera) { element.insertAdjacentHTML(position, html); } else { range = element.ownerDocument.createRange(); position = position.toUpperCase(); if (position == 'AFTERBEGIN' || position == 'BEFOREEND') { range.selectNodeContents(element); range.collapse(position == 'AFTERBEGIN'); } else { begin = position == 'BEFOREBEGIN'; range[begin ? 'setStartBefore' : 'setEndAfter'](element); range.collapse(begin); } range.insertNode(range.createContextualFragment(html)); } return element; }; baidu.insertHTML = baidu.dom.insertHTML; /** * 操作flash对象的方法,包括创建flash对象、获取flash对象以及判断flash插件的版本号 * @namespace baidu.swf */ baidu.swf = baidu.swf || {}; /** * 浏览器支持的flash插件版本 * @property version 浏览器支持的flash插件版本 * @grammar baidu.swf.version * @return {String} 版本号 * @meta standard */ baidu.swf.version = (function () { var n = navigator; if (n.plugins && n.mimeTypes.length) { var plugin = n.plugins["Shockwave Flash"]; if (plugin && plugin.description) { return plugin.description .replace(/([a-zA-Z]|\s)+/, "") .replace(/(\s)+r/, ".") + ".0"; } } else if (window.ActiveXObject && !window.opera) { for (var i = 12; i >= 2; i--) { try { var c = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.' + i); if (c) { var version = c.GetVariable("$version"); return version.replace(/WIN/g,'').replace(/,/g,'.'); } } catch(e) {} } } })(); /** * 操作字符串的方法 * @namespace baidu.string */ baidu.string = baidu.string || {}; /** * 对目标字符串进行html编码 * @name baidu.string.encodeHTML * @function * @grammar baidu.string.encodeHTML(source) * @param {string} source 目标字符串 * @remark * 编码字符有5个:&<>"' * @shortcut encodeHTML * @meta standard * @see baidu.string.decodeHTML * * @returns {string} html编码后的字符串 */ baidu.string.encodeHTML = function (source) { return String(source) .replace(/&/g,'&amp;') .replace(/</g,'&lt;') .replace(/>/g,'&gt;') .replace(/"/g, "&quot;") .replace(/'/g, "&#39;"); }; baidu.encodeHTML = baidu.string.encodeHTML; /** * 创建flash对象的html字符串 * @name baidu.swf.createHTML * @function * @grammar baidu.swf.createHTML(options) * * @param {Object} options 创建flash的选项参数 * @param {string} options.id 要创建的flash的标识 * @param {string} options.url flash文件的url * @param {String} options.errorMessage 未安装flash player或flash player版本号过低时的提示 * @param {string} options.ver 最低需要的flash player版本号 * @param {string} options.width flash的宽度 * @param {string} options.height flash的高度 * @param {string} options.align flash的对齐方式,允许值:middle/left/right/top/bottom * @param {string} options.base 设置用于解析swf文件中的所有相对路径语句的基本目录或URL * @param {string} options.bgcolor swf文件的背景色 * @param {string} options.salign 设置缩放的swf文件在由width和height设置定义的区域内的位置。允许值:l/r/t/b/tl/tr/bl/br * @param {boolean} options.menu 是否显示右键菜单,允许值:true/false * @param {boolean} options.loop 播放到最后一帧时是否重新播放,允许值: true/false * @param {boolean} options.play flash是否在浏览器加载时就开始播放。允许值:true/false * @param {string} options.quality 设置flash播放的画质,允许值:low/medium/high/autolow/autohigh/best * @param {string} options.scale 设置flash内容如何缩放来适应设置的宽高。允许值:showall/noborder/exactfit * @param {string} options.wmode 设置flash的显示模式。允许值:window/opaque/transparent * @param {string} options.allowscriptaccess 设置flash与页面的通信权限。允许值:always/never/sameDomain * @param {string} options.allownetworking 设置swf文件中允许使用的网络API。允许值:all/internal/none * @param {boolean} options.allowfullscreen 是否允许flash全屏。允许值:true/false * @param {boolean} options.seamlesstabbing 允许设置执行无缝跳格,从而使用户能跳出flash应用程序。该参数只能在安装Flash7及更高版本的Windows中使用。允许值:true/false * @param {boolean} options.devicefont 设置静态文本对象是否以设备字体呈现。允许值:true/false * @param {boolean} options.swliveconnect 第一次加载flash时浏览器是否应启动Java。允许值:true/false * @param {Object} options.vars 要传递给flash的参数,支持JSON或string类型。 * * @see baidu.swf.create * @meta standard * @returns {string} flash对象的html字符串 */ baidu.swf.createHTML = function (options) { options = options || {}; var version = baidu.swf.version, needVersion = options['ver'] || '6.0.0', vUnit1, vUnit2, i, k, len, item, tmpOpt = {}, encodeHTML = baidu.string.encodeHTML; for (k in options) { tmpOpt[k] = options[k]; } options = tmpOpt; if (version) { version = version.split('.'); needVersion = needVersion.split('.'); for (i = 0; i < 3; i++) { vUnit1 = parseInt(version[i], 10); vUnit2 = parseInt(needVersion[i], 10); if (vUnit2 < vUnit1) { break; } else if (vUnit2 > vUnit1) { return ''; } } } else { return ''; } var vars = options['vars'], objProperties = ['classid', 'codebase', 'id', 'width', 'height', 'align']; options['align'] = options['align'] || 'middle'; options['classid'] = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'; options['codebase'] = 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0'; options['movie'] = options['url'] || ''; delete options['vars']; delete options['url']; if ('string' == typeof vars) { options['flashvars'] = vars; } else { var fvars = []; for (k in vars) { item = vars[k]; fvars.push(k + "=" + encodeURIComponent(item)); } options['flashvars'] = fvars.join('&'); } var str = ['<object ']; for (i = 0, len = objProperties.length; i < len; i++) { item = objProperties[i]; str.push(' ', item, '="', encodeHTML(options[item]), '"'); } str.push('>'); var params = { 'wmode' : 1, 'scale' : 1, 'quality' : 1, 'play' : 1, 'loop' : 1, 'menu' : 1, 'salign' : 1, 'bgcolor' : 1, 'base' : 1, 'allowscriptaccess' : 1, 'allownetworking' : 1, 'allowfullscreen' : 1, 'seamlesstabbing' : 1, 'devicefont' : 1, 'swliveconnect' : 1, 'flashvars' : 1, 'movie' : 1 }; for (k in options) { item = options[k]; k = k.toLowerCase(); if (params[k] && (item || item === false || item === 0)) { str.push('<param name="' + k + '" value="' + encodeHTML(item) + '" />'); } } options['src'] = options['movie']; options['name'] = options['id']; delete options['id']; delete options['movie']; delete options['classid']; delete options['codebase']; options['type'] = 'application/x-shockwave-flash'; options['pluginspage'] = 'http://www.macromedia.com/go/getflashplayer'; str.push('<embed'); var salign; for (k in options) { item = options[k]; if (item || item === false || item === 0) { if ((new RegExp("^salign\x24", "i")).test(k)) { salign = item; continue; } str.push(' ', k, '="', encodeHTML(item), '"'); } } if (salign) { str.push(' salign="', encodeHTML(salign), '"'); } str.push('></embed></object>'); return str.join(''); }; /** * 在页面中创建一个flash对象 * @name baidu.swf.create * @function * @grammar baidu.swf.create(options[, container]) * * @param {Object} options 创建flash的选项参数 * @param {string} options.id 要创建的flash的标识 * @param {string} options.url flash文件的url * @param {String} options.errorMessage 未安装flash player或flash player版本号过低时的提示 * @param {string} options.ver 最低需要的flash player版本号 * @param {string} options.width flash的宽度 * @param {string} options.height flash的高度 * @param {string} options.align flash的对齐方式,允许值:middle/left/right/top/bottom * @param {string} options.base 设置用于解析swf文件中的所有相对路径语句的基本目录或URL * @param {string} options.bgcolor swf文件的背景色 * @param {string} options.salign 设置缩放的swf文件在由width和height设置定义的区域内的位置。允许值:l/r/t/b/tl/tr/bl/br * @param {boolean} options.menu 是否显示右键菜单,允许值:true/false * @param {boolean} options.loop 播放到最后一帧时是否重新播放,允许值: true/false * @param {boolean} options.play flash是否在浏览器加载时就开始播放。允许值:true/false * @param {string} options.quality 设置flash播放的画质,允许值:low/medium/high/autolow/autohigh/best * @param {string} options.scale 设置flash内容如何缩放来适应设置的宽高。允许值:showall/noborder/exactfit * @param {string} options.wmode 设置flash的显示模式。允许值:window/opaque/transparent * @param {string} options.allowscriptaccess 设置flash与页面的通信权限。允许值:always/never/sameDomain * @param {string} options.allownetworking 设置swf文件中允许使用的网络API。允许值:all/internal/none * @param {boolean} options.allowfullscreen 是否允许flash全屏。允许值:true/false * @param {boolean} options.seamlesstabbing 允许设置执行无缝跳格,从而使用户能跳出flash应用程序。该参数只能在安装Flash7及更高版本的Windows中使用。允许值:true/false * @param {boolean} options.devicefont 设置静态文本对象是否以设备字体呈现。允许值:true/false * @param {boolean} options.swliveconnect 第一次加载flash时浏览器是否应启动Java。允许值:true/false * @param {Object} options.vars 要传递给flash的参数,支持JSON或string类型。 * * @param {HTMLElement|string} [container] flash对象的父容器元素,不传递该参数时在当前代码位置创建flash对象。 * @meta standard * @see baidu.swf.createHTML,baidu.swf.getMovie */ baidu.swf.create = function (options, target) { options = options || {}; var html = baidu.swf.createHTML(options) || options['errorMessage'] || ''; if (target && 'string' == typeof target) { target = document.getElementById(target); } baidu.dom.insertHTML( target || document.body ,'beforeEnd',html ); }; /** * 判断是否为ie浏览器 * @name baidu.browser.ie * @field * @grammar baidu.browser.ie * @returns {Number} IE版本号 */ baidu.browser.ie = baidu.ie = /msie (\d+\.\d+)/i.test(navigator.userAgent) ? (document.documentMode || + RegExp['\x241']) : undefined; /** * 移除数组中的项 * @name baidu.array.remove * @function * @grammar baidu.array.remove(source, match) * @param {Array} source 需要移除项的数组 * @param {Any} match 要移除的项 * @meta standard * @see baidu.array.removeAt * * @returns {Array} 移除后的数组 */ baidu.array.remove = function (source, match) { var len = source.length; while (len--) { if (len in source && source[len] === match) { source.splice(len, 1); } } return source; }; /** * 判断目标参数是否Array对象 * @name baidu.lang.isArray * @function * @grammar baidu.lang.isArray(source) * @param {Any} source 目标参数 * @meta standard * @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate * * @returns {boolean} 类型判断结果 */ baidu.lang.isArray = function (source) { return '[object Array]' == Object.prototype.toString.call(source); }; /** * 将一个变量转换成array * @name baidu.lang.toArray * @function * @grammar baidu.lang.toArray(source) * @param {mix} source 需要转换成array的变量 * @version 1.3 * @meta standard * @returns {array} 转换后的array */ baidu.lang.toArray = function (source) { if (source === null || source === undefined) return []; if (baidu.lang.isArray(source)) return source; if (typeof source.length !== 'number' || typeof source === 'string' || baidu.lang.isFunction(source)) { return [source]; } if (source.item) { var l = source.length, array = new Array(l); while (l--) array[l] = source[l]; return array; } return [].slice.call(source); }; /** * 获得flash对象的实例 * @name baidu.swf.getMovie * @function * @grammar baidu.swf.getMovie(name) * @param {string} name flash对象的名称 * @see baidu.swf.create * @meta standard * @returns {HTMLElement} flash对象的实例 */ baidu.swf.getMovie = function (name) { var movie = document[name], ret; return baidu.browser.ie == 9 ? movie && movie.length ? (ret = baidu.array.remove(baidu.lang.toArray(movie),function(item){ return item.tagName.toLowerCase() != "embed"; })).length == 1 ? ret[0] : ret : movie : movie || window[name]; }; baidu.flash._Base = (function(){ var prefix = 'bd__flash__'; /** * 创建一个随机的字符串 * @private * @return {String} */ function _createString(){ return prefix + Math.floor(Math.random() * 2147483648).toString(36); }; /** * 检查flash状态 * @private * @param {Object} target flash对象 * @return {Boolean} */ function _checkReady(target){ if(typeof target !== 'undefined' && typeof target.flashInit !== 'undefined' && target.flashInit()){ return true; }else{ return false; } }; /** * 调用之前进行压栈的函数 * @private * @param {Array} callQueue 调用队列 * @param {Object} target flash对象 * @return {Null} */ function _callFn(callQueue, target){ var result = null; callQueue = callQueue.reverse(); baidu.each(callQueue, function(item){ result = target.call(item.fnName, item.params); item.callBack(result); }); }; /** * 为传入的匿名函数创建函数名 * @private * @param {String|Function} fun 传入的匿名函数或者函数名 * @return {String} */ function _createFunName(fun){ var name = ''; if(baidu.lang.isFunction(fun)){ name = _createString(); window[name] = function(){ fun.apply(window, arguments); }; return name; }else if(baidu.lang.isString){ return fun; } }; /** * 绘制flash * @private * @param {Object} options 创建参数 * @return {Object} */ function _render(options){ if(!options.id){ options.id = _createString(); } var container = options.container || ''; delete(options.container); baidu.swf.create(options, container); return baidu.swf.getMovie(options.id); }; return function(options, callBack){ var me = this, autoRender = (typeof options.autoRender !== 'undefined' ? options.autoRender : true), createOptions = options.createOptions || {}, target = null, isReady = false, callQueue = [], timeHandle = null, callBack = callBack || []; /** * 将flash文件绘制到页面上 * @public * @return {Null} */ me.render = function(){ target = _render(createOptions); if(callBack.length > 0){ baidu.each(callBack, function(funName, index){ callBack[index] = _createFunName(options[funName] || new Function()); }); } me.call('setJSFuncName', [callBack]); }; /** * 返回flash状态 * @return {Boolean} */ me.isReady = function(){ return isReady; }; /** * 调用flash接口的统一入口 * @param {String} fnName 调用的函数名 * @param {Array} params 传入的参数组成的数组,若不许要参数,需传入空数组 * @param {Function} [callBack] 异步调用后将返回值作为参数的调用回调函数,如无返回值,可以不传入此参数 * @return {Null} */ me.call = function(fnName, params, callBack){ if(!fnName) return null; callBack = callBack || new Function(); var result = null; if(isReady){ result = target.call(fnName, params); callBack(result); }else{ callQueue.push({ fnName: fnName, params: params, callBack: callBack }); (!timeHandle) && (timeHandle = setInterval(_check, 200)); } }; /** * 为传入的匿名函数创建函数名 * @public * @param {String|Function} fun 传入的匿名函数或者函数名 * @return {String} */ me.createFunName = function(fun){ return _createFunName(fun); }; /** * 检查flash是否ready, 并进行调用 * @private * @return {Null} */ function _check(){ if(_checkReady(target)){ clearInterval(timeHandle); timeHandle = null; _call(); isReady = true; } }; /** * 调用之前进行压栈的函数 * @private * @return {Null} */ function _call(){ _callFn(callQueue, target); callQueue = []; } autoRender && me.render(); }; })(); /** * 创建flash based imageUploader * @class * @grammar baidu.flash.imageUploader(options) * @param {Object} createOptions 创建flash时需要的参数,请参照baidu.swf.create文档 * @config {Object} vars 创建imageUploader时所需要的参数 * @config {Number} vars.gridWidth 每一个预览图片所占的宽度,应该为flash寛的整除 * @config {Number} vars.gridHeight 每一个预览图片所占的高度,应该为flash高的整除 * @config {Number} vars.picWidth 单张预览图片的宽度 * @config {Number} vars.picHeight 单张预览图片的高度 * @config {String} vars.uploadDataFieldName POST请求中图片数据的key,默认值'picdata' * @config {String} vars.picDescFieldName POST请求中图片描述的key,默认值'picDesc' * @config {Number} vars.maxSize 文件的最大体积,单位'MB' * @config {Number} vars.compressSize 上传前如果图片体积超过该值,会先压缩 * @config {Number} vars.maxNum:32 最大上传多少个文件 * @config {Number} vars.compressLength 能接受的最大边长,超过该值会等比压缩 * @config {String} vars.url 上传的url地址 * @config {Number} vars.mode mode == 0时,是使用滚动条,mode == 1时,拉伸flash, 默认值为0 * @see baidu.swf.createHTML * @param {String} backgroundUrl 背景图片路径 * @param {String} listBacgroundkUrl 布局控件背景 * @param {String} buttonUrl 按钮图片不背景 * @param {String|Function} selectFileCallback 选择文件的回调 * @param {String|Function} exceedFileCallback文件超出限制的最大体积时的回调 * @param {String|Function} deleteFileCallback 删除文件的回调 * @param {String|Function} startUploadCallback 开始上传某个文件时的回调 * @param {String|Function} uploadCompleteCallback 某个文件上传完成的回调 * @param {String|Function} uploadErrorCallback 某个文件上传失败的回调 * @param {String|Function} allCompleteCallback 全部上传完成时的回调 * @param {String|Function} changeFlashHeight 改变Flash的高度,mode==1的时候才有用 */ baidu.flash.imageUploader = baidu.flash.imageUploader || function(options){ var me = this, options = options || {}, _flash = new baidu.flash._Base(options, [ 'selectFileCallback', 'exceedFileCallback', 'deleteFileCallback', 'startUploadCallback', 'uploadCompleteCallback', 'uploadErrorCallback', 'allCompleteCallback', 'changeFlashHeight' ]); /** * 开始或回复上传图片 * @public * @return {Null} */ me.upload = function(){ _flash.call('upload'); }; /** * 暂停上传图片 * @public * @return {Null} */ me.pause = function(){ _flash.call('pause'); }; }; /** * 操作原生对象的方法 * @namespace baidu.object */ baidu.object = baidu.object || {}; /** * 将源对象的所有属性拷贝到目标对象中 * @author erik * @name baidu.object.extend * @function * @grammar baidu.object.extend(target, source) * @param {Object} target 目标对象 * @param {Object} source 源对象 * @see baidu.array.merge * @remark * 1.目标对象中,与源对象key相同的成员将会被覆盖。<br> 2.源对象的prototype成员不会拷贝。 * @shortcut extend * @meta standard * * @returns {Object} 目标对象 */ baidu.extend = baidu.object.extend = function (target, source) { for (var p in source) { if (source.hasOwnProperty(p)) { target[p] = source[p]; } } return target; }; /** * 创建flash based fileUploader * @class * @grammar baidu.flash.fileUploader(options) * @param {Object} options * @config {Object} createOptions 创建flash时需要的参数,请参照baidu.swf.create文档 * @config {String} createOptions.width * @config {String} createOptions.height * @config {Number} maxNum 最大可选文件数 * @config {Function|String} selectFile * @config {Function|String} exceedMaxSize * @config {Function|String} deleteFile * @config {Function|String} uploadStart * @config {Function|String} uploadComplete * @config {Function|String} uploadError * @config {Function|String} uploadProgress */ baidu.flash.fileUploader = baidu.flash.fileUploader || function(options){ var me = this, options = options || {}; options.createOptions = baidu.extend({ wmod: 'transparent' },options.createOptions || {}); var _flash = new baidu.flash._Base(options, [ 'selectFile', 'exceedMaxSize', 'deleteFile', 'uploadStart', 'uploadComplete', 'uploadError', 'uploadProgress' ]); _flash.call('setMaxNum', options.maxNum ? [options.maxNum] : [1]); /** * 设置当鼠标移动到flash上时,是否变成手型 * @public * @param {Boolean} isCursor * @return {Null} */ me.setHandCursor = function(isCursor){ _flash.call('setHandCursor', [isCursor || false]); }; /** * 设置鼠标相应函数名 * @param {String|Function} fun */ me.setMSFunName = function(fun){ _flash.call('setMSFunName',[_flash.createFunName(fun)]); }; /** * 执行上传操作 * @param {String} url 上传的url * @param {String} fieldName 上传的表单字段名 * @param {Object} postData 键值对,上传的POST数据 * @param {Number|Array|null|-1} [index]上传的文件序列 * Int值上传该文件 * Array一次串行上传该序列文件 * -1/null上传所有文件 * @return {Null} */ me.upload = function(url, fieldName, postData, index){ if(typeof url !== 'string' || typeof fieldName !== 'string') return null; if(typeof index === 'undefined') index = -1; _flash.call('upload', [url, fieldName, postData, index]); }; /** * 取消上传操作 * @public * @param {Number|-1} index */ me.cancel = function(index){ if(typeof index === 'undefined') index = -1; _flash.call('cancel', [index]); }; /** * 删除文件 * @public * @param {Number|Array} [index] 要删除的index,不传则全部删除 * @param {Function} callBack * @param * */ me.deleteFile = function(index, callBack){ var callBackAll = function(list){ callBack && callBack(list); }; if(typeof index === 'undefined'){ _flash.call('deleteFilesAll', [], callBackAll); return; }; if(typeof index === 'Number') index = [index]; index.sort(function(a,b){ return b-a; }); baidu.each(index, function(item){ _flash.call('deleteFileBy', item, callBackAll); }); }; /** * 添加文件类型,支持macType * @public * @param {Object|Array[Object]} type {description:String, extention:String} * @return {Null}; */ me.addFileType = function(type){ var type = type || [[]]; if(type instanceof Array) type = [type]; else type = [[type]]; _flash.call('addFileTypes', type); }; /** * 设置文件类型,支持macType * @public * @param {Object|Array[Object]} type {description:String, extention:String} * @return {Null}; */ me.setFileType = function(type){ var type = type || [[]]; if(type instanceof Array) type = [type]; else type = [[type]]; _flash.call('setFileTypes', type); }; /** * 设置可选文件的数量限制 * @public * @param {Number} num * @return {Null} */ me.setMaxNum = function(num){ _flash.call('setMaxNum', [num]); }; /** * 设置可选文件大小限制,以兆M为单位 * @public * @param {Number} num,0为无限制 * @return {Null} */ me.setMaxSize = function(num){ _flash.call('setMaxSize', [num]); }; /** * @public */ me.getFileAll = function(callBack){ _flash.call('getFileAll', [], callBack); }; /** * @public * @param {Number} index * @param {Function} [callBack] */ me.getFileByIndex = function(index, callBack){ _flash.call('getFileByIndex', [], callBack); }; /** * @public * @param {Number} index * @param {function} [callBack] */ me.getStatusByIndex = function(index, callBack){ _flash.call('getStatusByIndex', [], callBack); }; }; /** * 使用动态script标签请求服务器资源,包括由服务器端的回调和浏览器端的回调 * @namespace baidu.sio */ baidu.sio = baidu.sio || {}; /** * * @param {HTMLElement} src script节点 * @param {String} url script节点的地址 * @param {String} [charset] 编码 */ baidu.sio._createScriptTag = function(scr, url, charset){ scr.setAttribute('type', 'text/javascript'); charset && scr.setAttribute('charset', charset); scr.setAttribute('src', url); document.getElementsByTagName('head')[0].appendChild(scr); }; /** * 删除script的属性,再删除script标签,以解决修复内存泄漏的问题 * * @param {HTMLElement} src script节点 */ baidu.sio._removeScriptTag = function(scr){ if (scr.clearAttributes) { scr.clearAttributes(); } else { for (var attr in scr) { if (scr.hasOwnProperty(attr)) { delete scr[attr]; } } } if(scr && scr.parentNode){ scr.parentNode.removeChild(scr); } scr = null; }; /** * 通过script标签加载数据,加载完成由浏览器端触发回调 * @name baidu.sio.callByBrowser * @function * @grammar baidu.sio.callByBrowser(url, opt_callback, opt_options) * @param {string} url 加载数据的url * @param {Function|string} opt_callback 数据加载结束时调用的函数或函数名 * @param {Object} opt_options 其他可选项 * @config {String} [charset] script的字符集 * @config {Integer} [timeOut] 超时时间,超过这个时间将不再响应本请求,并触发onfailure函数 * @config {Function} [onfailure] timeOut设定后才生效,到达超时时间时触发本函数 * @remark * 1、与callByServer不同,callback参数只支持Function类型,不支持string。 * 2、如果请求了一个不存在的页面,callback函数在IE/opera下也会被调用,因此使用者需要在onsuccess函数中判断数据是否正确加载。 * @meta standard * @see baidu.sio.callByServer */ baidu.sio.callByBrowser = function (url, opt_callback, opt_options) { var scr = document.createElement("SCRIPT"), scriptLoaded = 0, options = opt_options || {}, charset = options['charset'], callback = opt_callback || function(){}, timeOut = options['timeOut'] || 0, timer; scr.onload = scr.onreadystatechange = function () { if (scriptLoaded) { return; } var readyState = scr.readyState; if ('undefined' == typeof readyState || readyState == "loaded" || readyState == "complete") { scriptLoaded = 1; try { callback(); clearTimeout(timer); } finally { scr.onload = scr.onreadystatechange = null; baidu.sio._removeScriptTag(scr); } } }; if( timeOut ){ timer = setTimeout(function(){ scr.onload = scr.onreadystatechange = null; baidu.sio._removeScriptTag(scr); options.onfailure && options.onfailure(); }, timeOut); } baidu.sio._createScriptTag(scr, url, charset); }; /** * 通过script标签加载数据,加载完成由服务器端触发回调 * @name baidu.sio.callByServer * @function * @grammar baidu.sio.callByServer(url, callback[, opt_options]) * @param {string} url 加载数据的url. * @param {Function|string} callback 服务器端调用的函数或函数名。如果没有指定本参数,将在URL中寻找options['queryField']做为callback的方法名. * @param {Object} opt_options 加载数据时的选项. * @config {string} [charset] script的字符集 * @config {string} [queryField] 服务器端callback请求字段名,默认为callback * @config {Integer} [timeOut] 超时时间(单位:ms),超过这个时间将不再响应本请求,并触发onfailure函数 * @config {Function} [onfailure] timeOut设定后才生效,到达超时时间时触发本函数 * @remark * 如果url中已经包含key为“options['queryField']”的query项,将会被替换成callback中参数传递或自动生成的函数名。 * @meta standard * @see baidu.sio.callByBrowser */ baidu.sio.callByServer = /**@function*/function(url, callback, opt_options) { var scr = document.createElement('SCRIPT'), prefix = 'bd__cbs__', callbackName, callbackImpl, options = opt_options || {}, charset = options['charset'], queryField = options['queryField'] || 'callback', timeOut = options['timeOut'] || 0, timer, reg = new RegExp('(\\?|&)' + queryField + '=([^&]*)'), matches; if (baidu.lang.isFunction(callback)) { callbackName = prefix + Math.floor(Math.random() * 2147483648).toString(36); window[callbackName] = getCallBack(0); } else if(baidu.lang.isString(callback)){ callbackName = callback; } else { if (matches = reg.exec(url)) { callbackName = matches[2]; } } if( timeOut ){ timer = setTimeout(getCallBack(1), timeOut); } url = url.replace(reg, '\x241' + queryField + '=' + callbackName); if (url.search(reg) < 0) { url += (url.indexOf('?') < 0 ? '?' : '&') + queryField + '=' + callbackName; } baidu.sio._createScriptTag(scr, url, charset); /* * 返回一个函数,用于立即(挂在window上)或者超时(挂在setTimeout中)时执行 */ function getCallBack(onTimeOut){ /*global callbackName, callback, scr, options;*/ return function(){ try { if( onTimeOut ){ options.onfailure && options.onfailure(); }else{ callback.apply(window, arguments); clearTimeout(timer); } window[callbackName] = null; delete window[callbackName]; } catch (exception) { } finally { baidu.sio._removeScriptTag(scr); } } } }; /** * 通过请求一个图片的方式令服务器存储一条日志 * @function * @grammar baidu.sio.log(url) * @param {string} url 要发送的地址. * @author: int08h,leeight */ baidu.sio.log = function(url) { var img = new Image(), key = 'tangram_sio_log_' + Math.floor(Math.random() * 2147483648).toString(36); window[key] = img; img.onload = img.onerror = img.onabort = function() { img.onload = img.onerror = img.onabort = null; window[key] = null; img = null; }; img.src = url; };
JavaScript
/*! * jQuery JavaScript Library v1.6.1 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu May 12 15:04:36 2011 -0400 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.6.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery._Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return (new Function( "return " + data ))(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing // (xml & tmp used internally) parseXML: function( data , xml , tmp ) { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } tmp = xml.documentElement; if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( indexOf ) { return indexOf.call( array, elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } // Expose jQuery to the global object return jQuery; })(); var // Promise methods promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { // make sure args are available (#8421) args = args || []; firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, always: function() { return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, pipe: function( fnDone, fnFail ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject ); } else { newDefer[ action ]( returned ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } }); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( firstParam ) { var args = arguments, i = 0, length = args.length, count = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { // Strange bug in FF4: // Values changed onto the arguments object sometimes end up as undefined values // outside the $.when method. Cloning the object into a fresh array solves the issue deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return deferred.promise(); } }); jQuery.support = (function() { var div = document.createElement( "div" ), documentElement = document.documentElement, all, a, select, opt, input, marginDiv, support, fragment, body, bodyStyle, tds, events, eventName, i, isSupported; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName( "tbody" ).length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName( "link" ).length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; div.detachEvent( "onclick", click ); }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains it's value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; div.innerHTML = ""; // Figure out if the W3C box model works as expected div.style.width = div.style.paddingLeft = "1px"; // We use our own, invisible, body body = document.createElement( "body" ); bodyStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, // Set background to avoid IE crashes when removing (#9028) background: "none" }; for ( i in bodyStyle ) { body.style[ i ] = bodyStyle[ i ]; } body.appendChild( div ); documentElement.insertBefore( body, documentElement.firstChild ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( document.defaultView && document.defaultView.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Remove the body element we added body.innerHTML = ""; documentElement.removeChild( body ); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 } ) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } return support; })(); // Keep track of boxModel jQuery.boxModel = jQuery.support.boxModel; var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([a-z])([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } return getByName ? thisCache[ jQuery.camelCase( name ) ] : thisCache; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; if ( thisCache ) { delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care if ( jQuery.support.deleteExpando || cache != window ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); if ( defer && ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.resolve(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = (type || "fx") + "mark"; jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); if ( count ) { jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { if ( elem ) { type = (type || "fx") + "queue"; var q = jQuery.data( elem, type, undefined, true ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data), true ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), defer; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { count++; tmp.done( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, rinvalidChar = /\:/, formHook, boolHook; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class") || "") ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attrFix: { // Always normalize to ensure hook usage tabindex: "tabIndex" }, attr: function( elem, name, value, pass ) { var nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( !("getAttribute" in elem) ) { return jQuery.prop( elem, name, value ); } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Normalize the name if needed name = notxml && jQuery.attrFix[ name ] || name; hooks = jQuery.attrHooks[ name ]; if ( !hooks ) { // Use boolHook for boolean attributes if ( rboolean.test( name ) && (typeof value === "boolean" || value === undefined || value.toLowerCase() === name.toLowerCase()) ) { hooks = boolHook; // Use formHook for forms and if the name contains certain characters } else if ( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { hooks = formHook; } } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return undefined; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml ) { return hooks.get( elem, name ); } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, name ) { var propName; if ( elem.nodeType === 1 ) { name = jQuery.attrFix[ name ] || name; if ( jQuery.support.getSetAttribute ) { // Use removeAttribute in browsers that support it elem.removeAttribute( name ); } else { jQuery.attr( elem, name, "" ); elem.removeAttributeNode( elem.getAttributeNode( name ) ); } // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { elem[ propName ] = false; } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabIndex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Try to normalize/fix the name name = notxml && jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return (elem[ name ] = value); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) { return ret; } else { return elem[ name ]; } } }, propHooks: {} }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties return elem[ jQuery.propFix[ name ] || name ] ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = value; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // Use the value property for back compat // Use the formHook for button elements in IE6/7 (#1954) jQuery.attrHooks.value = { get: function( elem, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.get( elem, name ); } return elem.value; }, set: function( elem, value, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !jQuery.support.getSetAttribute ) { // propFix is more comprehensive and contains all fixes jQuery.attrFix = jQuery.propFix; // Use this for any attribute on a form in IE6/7 formHook = jQuery.attrHooks.name = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); // Return undefined if nodeValue is empty string return ret && ret.nodeValue !== "" ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Check form objects in IE (multiple bugs related) // Only use nodeValue if the attribute node exists on the form var ret = elem.getAttributeNode( name ); if ( ret ) { ret.nodeValue = value; return value; } } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return (elem.style.cssText = "" + value); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }); } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); } } }); }); var hasOwn = Object.prototype.hasOwnProperty, rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspaces = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, true ); } } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Event object or event type var type = event.type || event, namespaces = [], exclusive; if ( type.indexOf("!") >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.exclusive = exclusive; event.namespace = namespaces.join("."); event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); // triggerHandler() and global events don't bubble or run the default action if ( onlyHandlers || !elem ) { event.preventDefault(); event.stopPropagation(); } // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); return; } // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // Clean up the event in case it is being reused event.result = undefined; event.target = elem; // Clone any incoming data and prepend the event, creating the handler arg list data = data ? jQuery.makeArray( data ) : []; data.unshift( event ); var cur = elem, // IE doesn't like method names with a colon (#3533, #8272) ontype = type.indexOf(":") < 0 ? "on" + type : ""; // Fire event on the current element, then bubble up the DOM tree do { var handle = jQuery._data( cur, "handle" ); event.currentTarget = cur; if ( handle ) { handle.apply( cur, data ); } // Trigger an inline bound script if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { event.result = false; event.preventDefault(); } // Bubble up to document, then to window cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; } while ( cur && !event.isPropagationStopped() ); // If nobody prevented the default action, do it now if ( !event.isDefaultPrevented() ) { var old, special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction)() check here because IE6/7 fails that test. // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. try { if ( ontype && elem[ type ] ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } jQuery.event.triggered = type; elem[ type ](); } } catch ( ieError ) {} if ( old ) { elem[ ontype ] = old; } jQuery.event.triggered = undefined; } } return event.result; }, handle: function( event ) { event = jQuery.event.fix( event || window.event ); // Snapshot the handlers list since a called handler may add/remove events. var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), run_all = !event.exclusive && !event.namespace, args = Array.prototype.slice.call( arguments, 0 ); // Use the fix-ed Event rather than the (read-only) native event args[0] = event; event.currentTarget = this; for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Triggered event must 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event. if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var eventDocument = event.target.ownerDocument || document, doc = eventDocument.documentElement, body = eventDocument.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // set the correct event type event.type = event.data; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Chrome does something similar, the parentNode property // can be accessed but is null. if ( parent && parent !== document && !parent.parentNode ) { return; } // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( !jQuery.nodeName( this, "form" ) ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( jQuery.nodeName( elem, "select" ) ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( donor ) { // Donor event is always a native one; fix it and switch its type. // Let focusin/out handler cancel the donor focus/blur event. var e = jQuery.event.fix( donor ); e.type = fix; e.originalEvent = {}; jQuery.event.trigger( e, null, e.target ); if ( e.isDefaultPrevented() ) { donor.preventDefault(); } } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { var handler; // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( arguments.length === 2 || data === false ) { fn = data; data = undefined; } if ( name === "one" ) { handler = function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }; handler.guid = fn.guid || jQuery.guid++; } else { handler = fn; } if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( name === "die" && !types && origSelector && origSelector.charAt(0) === "." ) { context.unbind( origSelector ); return this; } if ( data === false || jQuery.isFunction( data ) ) { fn = data || returnFalse; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( liveMap[ type ] ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; // Make sure not to accidentally match a child element with the same selector if ( related && jQuery.contains( elem, related ) ) { related = elem; } } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[ selector ] ) { matches[ selector ] = POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[ selector ]; if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( elem.getElementsByTagName ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName // instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^[+\-]=/, rrelNumFilter = /[^+\-\.\de]+/g, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": true, "widows": true, "orphans": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Make sure that NaN and null values aren't set. See: #7116 if ( type === "number" && isNaN( value ) || value == null ) { return; } // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && rrelNum.test( value ) ) { value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) ); } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat(value); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")", filter = currentStyle && currentStyle.filter || style.filter || ""; style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for(; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for(; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.bind( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function ( target, settings ) { if ( !settings ) { // Only one parameter, we extend ajaxSettings settings = target; target = jQuery.extend( true, jQuery.ajaxSettings, settings ); } else { // target was provided, we extend into it jQuery.extend( true, target, jQuery.ajaxSettings, settings ); } // Flatten fields we don't want deep extended for( var field in { context: 1, url: 1 } ) { if ( field in settings ) { target[ field ] = settings[ field ]; } else if( field in jQuery.ajaxSettings ) { target[ field ] = jQuery.ajaxSettings[ field ]; } } return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": "*/*" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, statusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status ? 4 : 0; var isSuccess, success, error, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = statusText; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.done; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( status < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow, requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { if ( this[i].style ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, display, e, parts, start, end, unit; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { display = defaultDisplay( this.nodeName ); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ](); } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { if ( clearQueue ) { this.queue([]); } this.each(function() { var timers = jQuery.timers, i = timers.length; // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } while ( i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( opt.queue !== false ) { jQuery.dequeue( this ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx, raf; this.startTime = fxNow || createFxNow(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { // Use requestAnimationFrame instead of setInterval if available if ( requestAnimationFrame ) { timerId = 1; raf = function() { // When timerId gets set to null at any point, this stops if ( timerId ) { requestAnimationFrame( raf ); fx.tick(); } }; requestAnimationFrame( raf ); } else { timerId = setInterval( fx.tick, fx.interval ); } } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options, i, n; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( i in options.animatedProperties ) { if ( options.animatedProperties[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery(elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( var p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[p] ); } } // Execute the complete function options.complete.call( elem ); } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ((this.end - this.start) * this.pos); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery( "<" + nodeName + ">" ).appendTo( "body" ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } document.body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake html // document to it, Webkit & Firefox won't allow reusing the iframe document if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( "<!doctype><html><body></body></html>" ); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ]; return elem.document.compatMode === "CSS1Compat" && docElemProp || elem.document.body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); window.jQuery = window.$ = jQuery; })(window);
JavaScript
<!-- /* Screw - A jQuery plugin ================================================================== ©2010-2011 JasonLau.biz - Version 1.0.1 ================================================================== This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function($){ $.fn.extend({ screw: function(options) { var defaults = { loadingHTML : 'Loading ... ' } var option = $.extend(defaults, options); var obj = $(this); return this.each(function() { $(window).scroll(function() { screwIt($(this)); }); var screwIt = function(it){ var h = $(window).height(), st = it.scrollTop(), t = h+st; $(".screw-image").each(function(){ var pos = $(this).offset(), rand = Math.round(Math.random()*1000); if(t >= pos.top){ if(!$(this).hasClass('screw-loaded')){ $(this).html('<div id="screw-loading-' + rand + '">' + option.loadingHTML + '</div>'); // Stop cache var url = $(this).attr('rel'), patt = /&/g; if(patt.test(url)){ url += '&screw_rand=' + rand; } else { url += '?screw_rand=' + rand; } // Preload image objImage = new Image(); objImage.src = url; var o = $(this); objImage.onload = function(){ o.append('<img style="display:none" id="screw-content-' + rand + '" class="screw-content" src="' + url + '" />'); $('#screw-loading-' + rand).fadeOut('slow', function(){ $('#screw-content-' + rand).fadeIn('slow'); o.addClass('screw-loaded'); }); }; } } }); $(".screw").each(function(){ var pos = $(this).offset(), rand = Math.round(Math.random()*1000); if(t >= pos.top){ if(!$(this).hasClass('screw-loaded') || $(this).hasClass('screw-repeat')){ var o = $(this); if(option.loadingHTML){ o.html('<div id="screw-loading-' + rand + '">' + option.loadingHTML + '</div>'); } if(o.hasClass('screw-append')){ if($(this).attr('rel')){ $.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }); } else if($(this).attr('rev')){ o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>'); showContent(rand); } } else if(o.hasClass('screw-prepend')){ if($(this).attr('rel')){ $.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.prepend('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }); } else if($(this).attr('rev')){ o.prepend('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>'); showContent(rand); } } else if(o.hasClass('screw-before')){ if($(this).attr('rel')){ $.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }); } else if($(this).attr('rev')){ o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>'); showContent(rand); } if(o.hasClass('screw-repeat') && pos.top < $(window).height()){ if($(this).attr('rel')){ $.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }); } else if($(this).attr('rev')){ o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>'); showContent(rand); } } } else if(o.hasClass('screw-after')){ if($(this).attr('rel')){ $.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.after('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }); } else if($(this).attr('rev')){ o.after('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>'); showContent(rand); } } else { if($(this).attr('rel')){ $.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }); } else if($(this).attr('rev')){ o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>'); showContent(rand); } } o.addClass('screw-loaded'); } } }); }; var showContent = function(rand){ if(option.loadingHTML){ $('#screw-loading-' + rand).fadeOut('slow', function(){ $('#screw-content-' + rand).fadeIn('slow'); }); } else { $('#screw-content-' + rand).fadeIn('slow'); } }; screwIt($(window)); }); } }); })(jQuery); -->
JavaScript
/** * jQuery upload v1 * @author xwz * http://pxblog.sinaapp.com */ (function($) { var noop = function(){ return true; }; var frameCount = 0; $.uploadDefault = { url: '', fileName: 'filedata', dataType: 'json', params: {}, onSend: noop, onComplate: noop }; $.upload = function(options) { var opts = $.extend(jQuery.uploadDefault, options); if (opts.url == '') { return; } var canSend = opts.onSend(); if (!canSend) { return; } var frameName = 'upload_frame_' + (frameCount++); var iframe = $('<iframe style="position:absolute;top:-9999px" />').attr('name', frameName); var form = $('<form method="post" style="display:none;" enctype="multipart/form-data" />').attr('name', 'form_' + frameName); form.attr("target", frameName).attr('action', opts.url); // form中增加数据域 var formHtml = '<input type="file" name="' + opts.fileName + '">'; for (key in opts.params) { formHtml += '<input type="hidden" name="' + key + '" value="' + opts.params[key] + '">'; } form.append(formHtml); iframe.appendTo("body"); form.appendTo("body"); // iframe 在提交完成之后 iframe.load(function() { var contents = $(this).contents().get(0); var data = $(contents).find('body').html(); if ('json' == opts.dataType) { data = window.eval('(' + data + ')'); } opts.onComplate(data); setTimeout(function() { iframe.remove(); form.remove(); }, 5000); }); // 文件框 var fileInput = $('input[type=file][name=' + opts.fileName + ']', form); fileInput.change(function() { form.submit(); }); fileInput.click(); }; })(jQuery);
JavaScript
/** * AJAX Upload ( http://valums.com/ajax-upload/ ) * Copyright (c) Andrew Valums * Licensed under the MIT license */ (function () { /** * Attaches event to a dom element. * @param {Element} el * @param type event name * @param fn callback This refers to the passed element */ function addEvent(el, type, fn){ if (el.addEventListener) { el.addEventListener(type, fn, false); } else if (el.attachEvent) { el.attachEvent('on' + type, function(){ fn.call(el); }); } else { throw new Error('not supported or DOM not loaded'); } } /** * Attaches resize event to a window, limiting * number of event fired. Fires only when encounteres * delay of 100 after series of events. * * Some browsers fire event multiple times when resizing * http://www.quirksmode.org/dom/events/resize.html * * @param fn callback This refers to the passed element */ function addResizeEvent(fn){ var timeout; addEvent(window, 'resize', function(){ if (timeout){ clearTimeout(timeout); } timeout = setTimeout(fn, 100); }); } // Needs more testing, will be rewriten for next version // getOffset function copied from jQuery lib (http://jquery.com/) if (document.documentElement.getBoundingClientRect){ // Get Offset using getBoundingClientRect // http://ejohn.org/blog/getboundingclientrect-is-awesome/ var getOffset = function(el){ var box = el.getBoundingClientRect(); var doc = el.ownerDocument; var body = doc.body; var docElem = doc.documentElement; // for ie var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; // In Internet Explorer 7 getBoundingClientRect property is treated as physical, // while others are logical. Make all logical, like in IE8. var zoom = 1; if (body.getBoundingClientRect) { var bound = body.getBoundingClientRect(); zoom = (bound.right - bound.left) / body.clientWidth; } if (zoom > 1) { clientTop = 0; clientLeft = 0; } var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft; return { top: top, left: left }; }; } else { // Get offset adding all offsets var getOffset = function(el){ var top = 0, left = 0; do { top += el.offsetTop || 0; left += el.offsetLeft || 0; el = el.offsetParent; } while (el); return { left: left, top: top }; }; } /** * Returns left, top, right and bottom properties describing the border-box, * in pixels, with the top-left relative to the body * @param {Element} el * @return {Object} Contains left, top, right,bottom */ function getBox(el){ var left, right, top, bottom; var offset = getOffset(el); left = offset.left; top = offset.top; right = left + el.offsetWidth; bottom = top + el.offsetHeight; return { left: left, right: right, top: top, bottom: bottom }; } /** * Helper that takes object literal * and add all properties to element.style * @param {Element} el * @param {Object} styles */ function addStyles(el, styles){ for (var name in styles) { if (styles.hasOwnProperty(name)) { el.style[name] = styles[name]; } } } /** * Function places an absolutely positioned * element on top of the specified element * copying position and dimentions. * @param {Element} from * @param {Element} to */ function copyLayout(from, to){ var box = getBox(from); addStyles(to, { position: 'absolute', left : box.left + 'px', top : box.top + 'px', width : from.offsetWidth + 'px', height : from.offsetHeight + 'px' }); } /** * Creates and returns element from html chunk * Uses innerHTML to create an element */ var toElement = (function(){ var div = document.createElement('div'); return function(html){ div.innerHTML = html; var el = div.firstChild; return div.removeChild(el); }; })(); /** * Function generates unique id * @return unique id */ var getUID = (function(){ var id = 0; return function(){ return 'ValumsAjaxUpload' + id++; }; })(); /** * Get file name from path * @param {String} file path to file * @return filename */ function fileFromPath(file){ return file.replace(/.*(\/|\\)/, ""); } /** * Get file extension lowercase * @param {String} file name * @return file extenstion */ function getExt(file){ return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : ''; } function hasClass(el, name){ var re = new RegExp('\\b' + name + '\\b'); return re.test(el.className); } function addClass(el, name){ if ( ! hasClass(el, name)){ el.className += ' ' + name; } } function removeClass(el, name){ var re = new RegExp('\\b' + name + '\\b'); el.className = el.className.replace(re, ''); } function removeNode(el){ el.parentNode.removeChild(el); } /** * Easy styling and uploading * @constructor * @param button An element you want convert to * upload button. Tested dimentions up to 500x500px * @param {Object} options See defaults below. */ window.AjaxUpload = function(button, options){ this._settings = { // Location of the server-side upload script action: 'upload.php', // File upload name name: 'userfile', // Select & upload multiple files at once FF3.6+, Chrome 4+ multiple: false, // Additional data to send data: {}, // Submit file as soon as it's selected autoSubmit: true, // The type of data that you're expecting back from the server. // html and xml are detected automatically. // Only useful when you are using json data as a response. // Set to "json" in that case. responseType: false, // Class applied to button when mouse is hovered hoverClass: 'hover', // Class applied to button when button is focused focusClass: 'focus', // Class applied to button when AU is disabled disabledClass: 'disabled', // When user selects a file, useful with autoSubmit disabled // You can return false to cancel upload onChange: function(file, extension){ }, // Callback to fire before file is uploaded // You can return false to cancel upload onSubmit: function(file, extension){ }, // Fired when file upload is completed // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE! onComplete: function(file, response){ } }; // Merge the users options with our defaults for (var i in options) { if (options.hasOwnProperty(i)){ this._settings[i] = options[i]; } } // button isn't necessary a dom element if (button.jquery){ // jQuery object was passed button = button[0]; } else if (typeof button == "string") { if (/^#.*/.test(button)){ // If jQuery user passes #elementId don't break it button = button.slice(1); } button = document.getElementById(button); } if ( ! button || button.nodeType !== 1){ throw new Error("Please make sure that you're passing a valid element"); } if ( button.nodeName.toUpperCase() == 'A'){ // disable link addEvent(button, 'click', function(e){ if (e && e.preventDefault){ e.preventDefault(); } else if (window.event){ window.event.returnValue = false; } }); } // DOM element this._button = button; // DOM element this._input = null; // If disabled clicking on button won't do anything this._disabled = false; // if the button was disabled before refresh if will remain // disabled in FireFox, let's fix it this.enable(); this._rerouteClicks(); }; // assigning methods to our class AjaxUpload.prototype = { setData: function(data){ this._settings.data = data; }, disable: function(){ addClass(this._button, this._settings.disabledClass); this._disabled = true; var nodeName = this._button.nodeName.toUpperCase(); if (nodeName == 'INPUT' || nodeName == 'BUTTON'){ this._button.setAttribute('disabled', 'disabled'); } // hide input if (this._input){ if (this._input.parentNode) { // We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it // has display none when user selects a file this._input.parentNode.style.visibility = 'hidden'; } } }, enable: function(){ removeClass(this._button, this._settings.disabledClass); this._button.removeAttribute('disabled'); this._disabled = false; }, /** * Creates invisible file input * that will hover above the button * <div><input type='file' /></div> */ _createInput: function(){ var self = this; var input = document.createElement("input"); input.setAttribute('type', 'file'); input.setAttribute('name', this._settings.name); if(this._settings.multiple) input.setAttribute('multiple', 'multiple'); addStyles(input, { 'position' : 'absolute', // in Opera only 'browse' button // is clickable and it is located at // the right side of the input 'right' : 0, 'margin' : 0, 'padding' : 0, 'fontSize' : '480px', // in Firefox if font-family is set to // 'inherit' the input doesn't work 'fontFamily' : 'sans-serif', 'cursor' : 'pointer' }); var div = document.createElement("div"); addStyles(div, { 'display' : 'block', 'position' : 'absolute', 'overflow' : 'hidden', 'margin' : 0, 'padding' : 0, 'opacity' : 0, // Make sure browse button is in the right side // in Internet Explorer 'direction' : 'ltr', //Max zIndex supported by Opera 9.0-9.2 'zIndex': 2147483583 }); // Make sure that element opacity exists. // Otherwise use IE filter if ( div.style.opacity !== "0") { if (typeof(div.filters) == 'undefined'){ throw new Error('Opacity not supported by the browser'); } div.style.filter = "alpha(opacity=0)"; } addEvent(input, 'change', function(){ if ( ! input || input.value === ''){ return; } // Get filename from input, required // as some browsers have path instead of it var file = fileFromPath(input.value); if (false === self._settings.onChange.call(self, file, getExt(file))){ self._clearInput(); return; } // Submit form when value is changed if (self._settings.autoSubmit) { self.submit(); } }); addEvent(input, 'mouseover', function(){ addClass(self._button, self._settings.hoverClass); }); addEvent(input, 'mouseout', function(){ removeClass(self._button, self._settings.hoverClass); removeClass(self._button, self._settings.focusClass); if (input.parentNode) { // We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it // has display none when user selects a file input.parentNode.style.visibility = 'hidden'; } }); addEvent(input, 'focus', function(){ addClass(self._button, self._settings.focusClass); }); addEvent(input, 'blur', function(){ removeClass(self._button, self._settings.focusClass); }); div.appendChild(input); document.body.appendChild(div); this._input = input; }, _clearInput : function(){ if (!this._input){ return; } // this._input.value = ''; Doesn't work in IE6 removeNode(this._input.parentNode); this._input = null; this._createInput(); removeClass(this._button, this._settings.hoverClass); removeClass(this._button, this._settings.focusClass); }, /** * Function makes sure that when user clicks upload button, * the this._input is clicked instead */ _rerouteClicks: function(){ var self = this; // IE will later display 'access denied' error // if you use using self._input.click() // other browsers just ignore click() addEvent(self._button, 'mouseover', function(){ if (self._disabled){ return; } if ( ! self._input){ self._createInput(); } var div = self._input.parentNode; copyLayout(self._button, div); div.style.visibility = 'visible'; }); // commented because we now hide input on mouseleave /** * When the window is resized the elements * can be misaligned if button position depends * on window size */ //addResizeEvent(function(){ // if (self._input){ // copyLayout(self._button, self._input.parentNode); // } //}); }, /** * Creates iframe with unique name * @return {Element} iframe */ _createIframe: function(){ // We can't use getTime, because it sometimes return // same value in safari :( var id = getUID(); // We can't use following code as the name attribute // won't be properly registered in IE6, and new window // on form submit will open // var iframe = document.createElement('iframe'); // iframe.setAttribute('name', id); var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />'); // src="javascript:false; was added // because it possibly removes ie6 prompt // "This page contains both secure and nonsecure items" // Anyway, it doesn't do any harm. iframe.setAttribute('id', id); iframe.style.display = 'none'; document.body.appendChild(iframe); return iframe; }, /** * Creates form, that will be submitted to iframe * @param {Element} iframe Where to submit * @return {Element} form */ _createForm: function(iframe){ var settings = this._settings; // We can't use the following code in IE6 // var form = document.createElement('form'); // form.setAttribute('method', 'post'); // form.setAttribute('enctype', 'multipart/form-data'); // Because in this case file won't be attached to request var form = toElement('<form method="post" enctype="multipart/form-data"></form>'); form.setAttribute('action', settings.action); form.setAttribute('target', iframe.name); form.style.display = 'none'; document.body.appendChild(form); // Create hidden input element for each data key for (var prop in settings.data) { if (settings.data.hasOwnProperty(prop)){ var el = document.createElement("input"); el.setAttribute('type', 'hidden'); el.setAttribute('name', prop); el.setAttribute('value', settings.data[prop]); form.appendChild(el); } } return form; }, /** * Gets response from iframe and fires onComplete event when ready * @param iframe * @param file Filename to use in onComplete callback */ _getResponse : function(iframe, file){ // getting response var toDeleteFlag = false, self = this, settings = this._settings; addEvent(iframe, 'load', function(){ if (// For Safari iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For FF, IE iframe.src == "javascript:'<html></html>';"){ // First time around, do not delete. // We reload to blank page, so that reloading main page // does not re-submit the post. if (toDeleteFlag) { // Fix busy state in FF3 setTimeout(function(){ removeNode(iframe); }, 0); } return; } var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document; // fixing Opera 9.26,10.00 if (doc.readyState && doc.readyState != 'complete') { // Opera fires load event multiple times // Even when the DOM is not ready yet // this fix should not affect other browsers return; } // fixing Opera 9.64 if (doc.body && doc.body.innerHTML == "false") { // In Opera 9.64 event was fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec return; } var response; if (doc.XMLDocument) { // response is a xml document Internet Explorer property response = doc.XMLDocument; } else if (doc.body){ // response is html document or plain text response = doc.body.innerHTML; if (settings.responseType && settings.responseType.toLowerCase() == 'json') { // If the document was sent as 'application/javascript' or // 'text/javascript', then the browser wraps the text in a <pre> // tag and performs html encoding on the contents. In this case, // we need to pull the original text content from the text node's // nodeValue property to retrieve the unmangled content. // Note that IE6 only understands text/html if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') { doc.normalize(); response = doc.body.firstChild.firstChild.nodeValue; } if (response) { response = eval("(" + response + ")"); } else { response = {}; } } } else { // response is a xml document response = doc; } settings.onComplete.call(self, file, response); // Reload blank page, so that reloading main page // does not re-submit the post. Also, remember to // delete the frame toDeleteFlag = true; // Fix IE mixed content issue iframe.src = "javascript:'<html></html>';"; }); }, /** * Upload file contained in this._input */ submit: function(){ var self = this, settings = this._settings; if ( ! this._input || this._input.value === ''){ return; } var file = fileFromPath(this._input.value); // user returned false to cancel upload if (false === settings.onSubmit.call(this, file, getExt(file))){ this._clearInput(); return; } // sending request var iframe = this._createIframe(); var form = this._createForm(iframe); // assuming following structure // div -> input type='file' removeNode(this._input.parentNode); removeClass(self._button, self._settings.hoverClass); removeClass(self._button, self._settings.focusClass); form.appendChild(this._input); form.submit(); // request set, clean up removeNode(form); form = null; removeNode(this._input); this._input = null; // Get response from iframe and fire onComplete event when ready this._getResponse(iframe, file); // get ready for next request this._createInput(); } }; })();
JavaScript
$(document).ready(function(){ //图片切换 var imgLen = 0; var figure=0; var picTimer; $(".group_list").hover(function() { clearInterval(picTimer); },function() { var obj = $(this).parent(); imgLen =obj.find(".autonum").attr('auto-length'); picTimer = setInterval(function() { figure= obj.find('.autonum').attr('auto-site'); figure=figure*1 + 2; if(figure > imgLen) { figure = 0; } showPics(obj,figure); },5000); }).trigger("mouseleave"); $('.gtBtn').click(function(){ var obj = $(this).parent().parent().parent().parent().parent() ; imgLen =obj.find(".group_show").length; figure= obj.find('.autonum').attr('auto-site'); figure=figure*1 + 2; if(figure >= imgLen) { figure = 0; } showPics(obj,figure); }) $('.ltBtn').click(function(){ var obj = $(this).parent().parent().parent().parent().parent() ; imgLen =obj.find(".group_show").length; figure = obj.find('.autonum').attr('auto-site'); figure = figure-2; if(figure < 0) { figure = imgLen-2; } showPics(obj,figure); }) }) function showPics(obj,figure) { var imgWidth = $(".group_show").width(); obj.find('.autonum').text(figure/2+1); obj.find('.autonum').attr('auto-site',figure); var nowLeft = - figure * (imgWidth*1 + 20) ; obj.find(".group_list").stop(true,false).animate({"left":nowLeft}, 500); // $("#prouducts-banner .prouducts-triggers span").removeClass("one").eq(figure).addClass("one"); }
JavaScript
/* * xiaodu * 690898325@qq.com *http://www.sameus.com */ function $Gid(name,value){ if(value != null){ document.getElementById(name).id = value; } return document.getElementById(name); } function $Gname(name,value){ if(value != null){ document.getElementsByName(name) = value; } return document.getElementsByName(name) ; } function $Gtagname(name,value){ if(value != null){ document.getElementsByTagName(name) = value; } return document.getElementsByTagName(name) ; } function $Gtitle(name,value){ if(value != null){ $Gid(name).title = value; return $Gid(name); }else{ return $Gid(name).title; } } function $Gstyle(name){ return $Gid(name).style ; } function $Gbackground(name,value){ if(value != null){ $Gstyle(name).background = value; return $Gstyle(name) ; }else{ return $Gstyle(name).background; } } function $GbackgroundColor(name,value){ if(value != null){ $Gstyle(name).backgroundColor = value; return $Gstyle(name) ; }else{ return $Gstyle(name).backgroundColor; } } function $Gborder(name,value){ if(value != null){ $Gstyle(name).border = value; return $Gstyle(name) ; }else{ return $Gstyle(name).border; } } function $Gmargin(name,value){ if(value != null){ $Gstyle(name).margin = value; return $Gstyle(name) ; }else{ return $Gstyle(name).margin; } } function $Gpadding(name,value){ if(value != null){ $Gstyle(name).padding = value; return $Gstyle(name) ; }else{ return $Gstyle(name).padding ; } } function $Gclear(name,value){ if(value != null){ $Gstyle(name).clear = value; return $Gstyle(name) ; }else{ return $Gstyle(name).clear ; } } function $Gtop(name,value){ if(value != null){ $Gstyle(name).top = parseInt(value)+"px"; return $Gstyle(name) ; }else{ return $Gstyle(name).top ; } } function $Gleft(name,value){ if(value != null){ $Gstyle(name).left = parseInt(value)+"px"; return $Gstyle(name) ; }else{ return $Gstyle(name).left ; } } function $Gofftop(name,value){ var t; var gid = $Gid(name); if(value != null){ gid.offsetTop = value; return gid ; }else{ t = gid.offsetTop ; // while (gid = gid.offsetParent) { // t += gid.offsetTop; // } return t; } } function $Goffleft(name,value){ var l; var gid = $Gid(name); if(value != null){ gid.offsetLeft = value; return gid; }else{ l = gid.offsetLeft ; // while (gid = $Gstyle(name).offsetParent) { // l += gid.offsetLeft; //叠加父容器的左边距 // } return l ; } } function $Gshow(name){ $Gstyle(name).display= 'block'; } function $Ghide(name){ $Gstyle(name).display= 'none'; }
JavaScript
$(document).ready(function(){ var button = $('#upload_grouplogo'), interval; var fileType = "pic",fileNum = "one"; new AjaxUpload(button,{ action: url+'/grouplogo_edit?gid='+gid, type:'POST', name: 'userfile', data:{ 'gid':'3' /* //传值module:"ajaxupload", 'buttoninfo':button.text()*/ }, responseType:'json', onSubmit : function(file, ext){ if(fileType == "pic") { if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){ this.setData({ 'info': '文件类型为图片' }); } else { $('<li></li>').appendTo('#uplogo_p').text('非图片类型文件,请重传'); return false; } } button.val('文件上传中'); if(fileNum == 'one') this.disable(); interval = window.setInterval(function(){ var text = button.text(); if (text.length < 14){ button.val(text + '.'); } else { button.val('文件上传中'); } }, 200); }, onComplete: function(file,response){ button.val('修改Logo'); window.clearInterval(interval); this.enable(); if(response.status == "1"){ var timenow = new Date().getTime(); $("#group_mainlogo").attr('src',puburl+'/Uploads/GroupLogo/m_'+response.data+'?'+timenow); $("#group_logoshow").attr('src',puburl+'/Uploads/GroupLogo/m_'+response.data+'?'+timenow); }else{ alert("上传失败!"); } }//onComplete: });//new AjaxUpload结束 });
JavaScript
<!-- /* Screw - A jQuery plugin ================================================================== ©2010-2012 JasonLau.biz - Version 1.0.5 ================================================================== This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function($){ $.fn.extend({ screw: function(options) { var defaults = { loadingHTML : 'Loading ... ' }, option = $.extend(defaults, options); var obj = $(this); return this.each(function() { var is_viewable = function(mother, baby){ var x1 = mother.offset().left, y1 = mother.offset().top, w = mother.outerWidth(), h = mother.outerHeight(); var xp1 = baby.offset().left, yp1 = baby.offset().top, wp = baby.outerWidth(), hp = baby.outerHeight(); var x2 = x1+w, y2 = y1+h, xp2 = xp1+wp, yp2 = yp1+hp; if(xp1 >= x1 && xp1 <= x2){ if(yp1 >= y1 && yp1 <= y2){ return true; } else if(y1>=yp1 && y1<=yp2){ return true; } } else if(x1>=xp1 && x1<=xp2){ if(yp1>=y1 && yp1<=y2){ return true; } else if(y1>=yp1 && y1<=yp2){ return true; } } return false; }; // is_viewable var screwIt = function(){ if(!obj.css('position') || obj.css('position') == 'static'){ obj.css({ position: 'relative' }); } var box_width = obj.width(), box_height = obj.height(), parent_scrollTop = obj.scrollTop(), parent_scrollLeft = obj.scrollLeft(); if(obj.is("body")){ box_width = $("body").width(), box_height = $(window).height()-10, parent_scrollTop = $(window).scrollTop(), parent_scrollLeft = $(window).scrollLeft(); } $(".screw-hit-test-box").show(); $(".screw-hit-test-box").css({ 'width': box_width+'px', 'min-width': box_width+'px', 'max-width': box_width+'px', 'height': box_height+'px', 'min-height': box_height+'px', 'max-height': box_height+'px', 'position': 'absolute', 'top': parent_scrollTop+'px', 'left': parent_scrollLeft+'px', 'padding': '0px', 'margin': '0px', 'border': '0px solid red' }); /**/ $(".screw-image").each(function(){ var o = $(this), mother = $(".screw-hit-test-box"), rand = Math.round(Math.random()*1000), data = o.data(); if(is_viewable(mother, o)){ if(!o.hasClass('screw-loaded') && !o.hasClass('screw-loading')){ if(data.debug) try{console.log("Screw loading");}catch(e){} o.addClass('screw-loading').html('<div id="screw-loading-' + rand + '">' + option.loadingHTML + '</div>'); // Stop cache var url = o.attr('rel'), patt = /&/g; if(patt.test(url)){ url += '&screw_rand=' + rand; } else { url += '?screw_rand=' + rand; } // Preload image if(data.debug) try{console.log("Preloading image");}catch(e){} objImage = new Image(); objImage.src = url; objImage.onload = function(){ o.append('<img style="display:none" id="screw-content-' + rand + '" class="screw-content" src="' + url + '" />'); if(data.debug) try{console.log("Preloading complete");}catch(e){} $('#screw-loading-' + rand).fadeOut('slow', function(){ $('#screw-content-' + rand).fadeIn('slow'); o.removeClass('screw-loading').addClass('screw-loaded'); if(data.debug) try{console.log("Image loaded successfully");}catch(e){} }); }; } } }); $(".screw").each(function(){ var o = $(this), mother = $(".screw-hit-test-box"), rand = Math.round(Math.random()*1000), data = o.data(), data_type = 'html'; if(is_viewable(mother, o)){ if(o.hasClass('screw-xml')){ data_type = 'xml'; } else if(o.hasClass('screw-json')){ data_type = 'json'; } else if(o.hasClass('screw-script')){ data_type = 'script'; } if(data.debug) try{console.log("Data type: " + data_type);}catch(e){} if((!o.hasClass('screw-loaded') || o.hasClass('screw-repeat') && !o.hasClass('screw-loading'))){ if(data.debug) try{console.log("Screw loading");}catch(e){} o.addClass('screw-loading'); if(option.loadingHTML){ if(data.debug) try{console.log("Applying loading html");}catch(e){} o.html('<div id="screw-loading-' + rand + '">' + option.loadingHTML + '</div>'); } if(o.hasClass('screw-replace')){ if(data.debug) try{console.log("Screw replace");}catch(e){} if(o.attr('rel')){ $.get(o.attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.replaceWith(data); }, data_type); } else if(o.attr('rev')){ o.replaceWith(o.attr('rev')); } } else if(o.hasClass('screw-append')){ if(data.debug) try{console.log("Screw append");}catch(e){} if(o.attr('rel')){ $.get(o.attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }, data_type); } else if(o.attr('rev')){ o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + o.attr('rev') + '</div>'); showContent(rand); } } else if(o.hasClass('screw-prepend')){ if(data.debug) try{console.log("Screw prepend");}catch(e){} if(o.attr('rel')){ $.get(o.attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.prepend('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }, data_type); } else if(o.attr('rev')){ o.prepend('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + o.attr('rev') + '</div>'); showContent(rand); } } else if(o.hasClass('screw-before')){ if(data.debug) try{console.log("Screw before");}catch(e){} if(o.attr('rel')){ $.get(o.attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }, data_type); } else if(o.attr('rev')){ o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + o.attr('rev') + '</div>'); showContent(rand); } if(o.hasClass('screw-repeat') && t >= Math.round(os.top) && true_left >= Math.round(os.left)){ if(data.debug) try{console.log("Screw repeat");}catch(e){} if(o.attr('rel')){ $.get(o.attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }, data_type); } else if(o.attr('rev')){ o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + o.attr('rev') + '</div>'); showContent(rand); } } } else if(o.hasClass('screw-after')){ if(data.debug) try{console.log("Screw after");}catch(e){} if(o.attr('rel')){ $.get(o.attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.after('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }, data_type); } else if(o.attr('rev')){ o.after('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + o.attr('rev') + '</div>'); showContent(rand); } } else { if(o.attr('rel')){ $.get(o.attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) { o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>'); showContent(rand); }, data_type); } else if(o.attr('rev')){ o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + o.attr('rev') + '</div>'); showContent(rand); } } o.removeClass('screw-loading').addClass('screw-loaded'); if(data.debug) try{console.log("Screw loaded successfully");}catch(e){} } } }); $(".screw-remove").each(function(){ var o = $(this), mother = $(".screw-hit-test-box"), rand = Math.round(Math.random()*1000), data = o.data(); if(o.hasClass('screw-loaded') && is_viewable(mother, o)){ if(data.debug) try{console.log("Has Class screw-remove.");}catch(e){} if(o.is(':visible')){ o.fadeOut('slow'); o.removeClass('screw-loaded'); if(data.debug) try{console.log("Screw removed successfully");}catch(e){} } } }); $(".screw-hit-test-box").hide(); }; // screwIt var showContent = function(rand){ if(option.loadingHTML){ $('#screw-loading-' + rand).fadeOut('slow', function(){ $('#screw-content-' + rand).fadeIn('slow'); }); } else { $('#screw-content-' + rand).fadeIn('slow'); } }; // showContent if(!$(".screw-hit-test-box").width()){ obj.prepend('<div class="screw-hit-test-box"></div>'); } if(obj.is("body")){ $(window).scroll(function() { screwIt(); }).resize(function() { screwIt(); }); } else { obj.scroll(function() { screwIt(); }).resize(function() { screwIt(); }); } screwIt(); // init }); // each } // screw }); // extend })(jQuery); -->
JavaScript