code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * List compiled by mystix on the extjs.com forums. * Thank you Mystix! * * English Translations * updated to 2.2 by Condor (8 Aug 2008) */ Ext.onReady(function() { var cm = Ext.ClassManager, exists = Ext.Function.bind(cm.get, cm); if (Ext.Updater) { Ext.Updater.defaults.indicatorText = '<div class="loading-indicator">Loading...</div>'; } if (exists('Ext.data.Types')) { Ext.data.Types.stripRe = /[\$,%]/g; } Ext.define("Ext.locale.en.view.View", { override: "Ext.view.View", emptyText: "" }); Ext.define("Ext.locale.en.grid.Panel", { override: "Ext.grid.Panel", ddText: "{0} selected row{1}" }); // changing the msg text below will affect the LoadMask Ext.define("Ext.locale.en.view.AbstractView", { override: "Ext.view.AbstractView", msg: "Loading..." }); if (Ext.Date) { Ext.Date.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; Ext.Date.getShortMonthName = function(month) { return Ext.Date.monthNames[month].substring(0, 3); }; Ext.Date.monthNumbers = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }; Ext.Date.getMonthNumber = function(name) { return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; }; Ext.Date.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; Ext.Date.getShortDayName = function(day) { return Ext.Date.dayNames[day].substring(0, 3); }; Ext.Date.parseCodes.S.s = "(?:st|nd|rd|th)"; } if (Ext.MessageBox) { Ext.MessageBox.buttonText = { ok: "OK", cancel: "Cancel", yes: "Yes", no: "No" }; } if (exists('Ext.util.Format')) { Ext.apply(Ext.util.Format, { thousandSeparator: ',', decimalSeparator: '.', currencySign: '$', dateFormat: 'm/d/Y' }); } Ext.define("Ext.locale.en.picker.Date", { override: "Ext.picker.Date", todayText: "Today", minText: "This date is before the minimum date", maxText: "This date is after the maximum date", disabledDaysText: "", disabledDatesText: "", monthNames: Ext.Date.monthNames, dayNames: Ext.Date.dayNames, nextText: 'Next Month (Control+Right)', prevText: 'Previous Month (Control+Left)', monthYearText: 'Choose a month (Control+Up/Down to move years)', todayTip: "{0} (Spacebar)", format: "m/d/y", startDay: 0 }); Ext.define("Ext.locale.en.picker.Month", { override: "Ext.picker.Month", okText: "&#160;OK&#160;", cancelText: "Cancel" }); Ext.define("Ext.locale.en.toolbar.Paging", { override: "Ext.PagingToolbar", beforePageText: "Page", afterPageText: "of {0}", firstText: "First Page", prevText: "Previous Page", nextText: "Next Page", lastText: "Last Page", refreshText: "Refresh", displayMsg: "Displaying {0} - {1} of {2}", emptyMsg: 'No data to display' }); Ext.define("Ext.locale.en.form.Basic", { override: "Ext.form.Basic", waitTitle: "Please Wait..." }); Ext.define("Ext.locale.en.form.field.Base", { override: "Ext.form.field.Base", invalidText: "The value in this field is invalid" }); Ext.define("Ext.locale.en.form.field.Text", { override: "Ext.form.field.Text", minLengthText: "The minimum length for this field is {0}", maxLengthText: "The maximum length for this field is {0}", blankText: "This field is required", regexText: "", emptyText: null }); Ext.define("Ext.locale.en.form.field.Number", { override: "Ext.form.field.Number", decimalSeparator: ".", decimalPrecision: 2, minText: "The minimum value for this field is {0}", maxText: "The maximum value for this field is {0}", nanText: "{0} is not a valid number" }); Ext.define("Ext.locale.en.form.field.Date", { override: "Ext.form.field.Date", disabledDaysText: "Disabled", disabledDatesText: "Disabled", minText: "The date in this field must be after {0}", maxText: "The date in this field must be before {0}", invalidText: "{0} is not a valid date - it must be in the format {1}", format: "m/d/y", altFormats: "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d" }); Ext.define("Ext.locale.en.form.field.ComboBox", { override: "Ext.form.field.ComboBox", valueNotFoundText: undefined }, function() { Ext.apply(Ext.form.field.ComboBox.prototype.defaultListConfig, { loadingText: "Loading..." }); }); if (exists('Ext.form.field.VTypes')) { Ext.apply(Ext.form.field.VTypes, { emailText: 'This field should be an e-mail address in the format "user@example.com"', urlText: 'This field should be a URL in the format "http:/' + '/www.example.com"', alphaText: 'This field should only contain letters and _', alphanumText: 'This field should only contain letters, numbers and _' }); } Ext.define("Ext.locale.en.form.field.HtmlEditor", { override: "Ext.form.field.HtmlEditor", createLinkText: 'Please enter the URL for the link:' }, function() { Ext.apply(Ext.form.field.HtmlEditor.prototype, { buttonTips: { bold: { title: 'Bold (Ctrl+B)', text: 'Make the selected text bold.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, italic: { title: 'Italic (Ctrl+I)', text: 'Make the selected text italic.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, underline: { title: 'Underline (Ctrl+U)', text: 'Underline the selected text.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, increasefontsize: { title: 'Grow Text', text: 'Increase the font size.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, decreasefontsize: { title: 'Shrink Text', text: 'Decrease the font size.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, backcolor: { title: 'Text Highlight Color', text: 'Change the background color of the selected text.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, forecolor: { title: 'Font Color', text: 'Change the color of the selected text.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyleft: { title: 'Align Text Left', text: 'Align text to the left.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifycenter: { title: 'Center Text', text: 'Center text in the editor.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyright: { title: 'Align Text Right', text: 'Align text to the right.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertunorderedlist: { title: 'Bullet List', text: 'Start a bulleted list.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertorderedlist: { title: 'Numbered List', text: 'Start a numbered list.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, createlink: { title: 'Hyperlink', text: 'Make the selected text a hyperlink.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, sourceedit: { title: 'Source Edit', text: 'Switch to source editing mode.', cls: Ext.baseCSSPrefix + 'html-editor-tip' } } }); }); Ext.define("Ext.locale.en.grid.header.Container", { override: "Ext.grid.header.Container", sortAscText: "Sort Ascending", sortDescText: "Sort Descending", columnsText: "Columns" }); Ext.define("Ext.locale.en.grid.GroupingFeature", { override: "Ext.grid.GroupingFeature", emptyGroupText: '(None)', groupByText: 'Group By This Field', showGroupsText: 'Show in Groups' }); Ext.define("Ext.locale.en.grid.PropertyColumnModel", { override: "Ext.grid.PropertyColumnModel", nameText: "Name", valueText: "Value", dateFormat: "m/j/Y", trueText: "true", falseText: "false" }); Ext.define("Ext.locale.en.grid.BooleanColumn", { override: "Ext.grid.BooleanColumn", trueText: "true", falseText: "false", undefinedText: '&#160;' }); Ext.define("Ext.locale.en.grid.NumberColumn", { override: "Ext.grid.NumberColumn", format: '0,000.00' }); Ext.define("Ext.locale.en.grid.DateColumn", { override: "Ext.grid.DateColumn", format: 'm/d/Y' }); Ext.define("Ext.locale.en.form.field.Time", { override: "Ext.form.field.Time", minText: "The time in this field must be equal to or after {0}", maxText: "The time in this field must be equal to or before {0}", invalidText: "{0} is not a valid time", format: "g:i A", altFormats: "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H" }); Ext.define("Ext.locale.en.form.CheckboxGroup", { override: "Ext.form.CheckboxGroup", blankText: "You must select at least one item in this group" }); Ext.define("Ext.locale.en.form.RadioGroup", { override: "Ext.form.RadioGroup", blankText: "You must select one item in this group" }); });
JavaScript
/** * Estonian Translations * By Rene Saarsoo (2012-05-28) */ Ext.onReady(function() { var cm = Ext.ClassManager, exists = Ext.Function.bind(cm.get, cm); if (Ext.Updater) { Ext.Updater.defaults.indicatorText = '<div class="loading-indicator">Laen...</div>'; } Ext.define("Ext.locale.et.view.View", { override: "Ext.view.View", emptyText: "" }); Ext.define("Ext.locale.et.grid.Panel", { override: "Ext.grid.Panel", ddText: "{0} valitud rida" }); // changing the msg text below will affect the LoadMask Ext.define("Ext.locale.et.view.AbstractView", { override: "Ext.view.AbstractView", msg: "Laen..." }); if (Ext.Date) { Ext.Date.monthNames = ["Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"]; // Month names aren't shortened to strictly three letters var shortMonthNames = ["Jaan", "Veeb", "Märts", "Apr", "Mai", "Juuni", "Juuli", "Aug", "Sept", "Okt", "Nov", "Dets"]; Ext.Date.getShortMonthName = function(month) { return shortMonthNames[month]; }; Ext.Date.monthNumbers = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }; Ext.Date.getMonthNumber = function(name) { return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; }; Ext.Date.dayNames = ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"]; // Weekday names are abbreviated to single letter Ext.Date.getShortDayName = function(day) { return Ext.Date.dayNames[day].substring(0, 1); }; } if (Ext.MessageBox) { Ext.MessageBox.buttonText = { ok: "OK", cancel: "Katkesta", yes: "Jah", no: "Ei" }; } if (exists('Ext.util.Format')) { Ext.apply(Ext.util.Format, { thousandSeparator: ' ', decimalSeparator: ',', currencySign: '\u20ac', // Euro dateFormat: 'd.m.Y' }); } Ext.define("Ext.locale.et.picker.Date", { override: "Ext.picker.Date", todayText: "Täna", minText: "See kuupäev on enne määratud vanimat kuupäeva", maxText: "See kuupäev on pärast määratud hiliseimat kuupäeva", disabledDaysText: "", disabledDatesText: "", monthNames: Ext.Date.monthNames, dayNames: Ext.Date.dayNames, nextText: 'Järgmine kuu (Ctrl+Paremale)', prevText: 'Eelmine kuu (Ctrl+Vasakule)', monthYearText: 'Vali kuu (Ctrl+Üles/Alla aastate muutmiseks)', todayTip: "{0} (Tühik)", format: "d.m.Y", startDay: 1 }); Ext.define("Ext.locale.et.picker.Month", { override: "Ext.picker.Month", okText: "&#160;OK&#160;", cancelText: "Katkesta" }); Ext.define("Ext.locale.et.toolbar.Paging", { override: "Ext.PagingToolbar", beforePageText: "Lehekülg", afterPageText: "{0}-st", firstText: "Esimene lk", prevText: "Eelmine lk", nextText: "Järgmine lk", lastText: "Viimane lk", refreshText: "Värskenda", displayMsg: "Näitan {0} - {1} {2}-st", emptyMsg: 'Puuduvad andmed mida näidata' }); Ext.define("Ext.locale.et.form.Basic", { override: "Ext.form.Basic", waitTitle: "Palun oota..." }); Ext.define("Ext.locale.et.form.field.Base", { override: "Ext.form.field.Base", invalidText: "Välja sisu ei vasta nõuetele" }); Ext.define("Ext.locale.et.form.field.Text", { override: "Ext.form.field.Text", minLengthText: "Selle välja minimaalne pikkus on {0}", maxLengthText: "Selle välja maksimaalne pikkus on {0}", blankText: "Selle välja täitmine on nõutud", regexText: "", emptyText: null }); Ext.define("Ext.locale.et.form.field.Number", { override: "Ext.form.field.Number", minText: "Selle välja vähim väärtus võib olla {0}", maxText: "Selle välja suurim väärtus võib olla {0}", nanText: "{0} pole korrektne number" }); Ext.define("Ext.locale.et.form.field.Date", { override: "Ext.form.field.Date", disabledDaysText: "Võimetustatud", disabledDatesText: "Võimetustatud", minText: "Kuupäev peab olema alates kuupäevast: {0}", maxText: "Kuupäev peab olema kuni kuupäevani: {0}", invalidText: "{0} ei ole sobiv kuupäev - õige formaat on: {1}", format: "d.m.Y" }); Ext.define("Ext.locale.et.form.field.ComboBox", { override: "Ext.form.field.ComboBox", valueNotFoundText: undefined }, function() { Ext.apply(Ext.form.field.ComboBox.prototype.defaultListConfig, { loadingText: "Laen..." }); }); if (exists('Ext.form.field.VTypes')) { Ext.apply(Ext.form.field.VTypes, { emailText: 'Selle välja sisuks peab olema e-posti aadress kujul "kasutaja@domeen.com"', urlText: 'Selle välja sisuks peab olema veebiaadress kujul "http:/'+'/www.domeen.com"', alphaText: 'See väli võib sisaldada vaid tähemärke ja alakriipsu', alphanumText: 'See väli võib sisaldada vaid tähemärke, numbreid ja alakriipsu' }); } Ext.define("Ext.locale.et.form.field.HtmlEditor", { override: "Ext.form.field.HtmlEditor", createLinkText: 'Palun sisestage selle lingi internetiaadress:' }, function() { Ext.apply(Ext.form.field.HtmlEditor.prototype, { buttonTips: { bold: { title: 'Rasvane kiri (Ctrl+B)', text: 'Muuda valitud tekst rasvaseks.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, italic: { title: 'Kursiiv (Ctrl+I)', text: 'Pane valitud tekst kaldkirja.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, underline: { title: 'Allakriipsutus (Ctrl+U)', text: 'Jooni valitud tekst alla.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, increasefontsize: { title: 'Suurenda', text: 'Suurenda teksti suurust.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, decreasefontsize: { title: 'Vähenda', text: 'Vähenda teksti suurust.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, backcolor: { title: 'Tausta värv', text: 'Muuda valitud teksti taustavärvi.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, forecolor: { title: 'Teksti värv', text: 'Muuda valitud teksti värvi.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyleft: { title: 'Vasakule', text: 'Joonda tekst vasakule.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifycenter: { title: 'Keskele', text: 'Joonda tekst keskele.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyright: { title: 'Paremale', text: 'Joonda tekst paremale.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertunorderedlist: { title: 'Loetelu', text: 'Alusta loetelu.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertorderedlist: { title: 'Numereeritud list', text: 'Alusta numereeritud nimekirja.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, createlink: { title: 'Link', text: 'Muuda tekst lingiks.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, sourceedit: { title: 'Lähtekoodi muutmine', text: 'Lülitu lähtekoodi muutmise režiimi.', cls: Ext.baseCSSPrefix + 'html-editor-tip' } } }); }); Ext.define("Ext.locale.et.grid.header.Container", { override: "Ext.grid.header.Container", sortAscText: "Järjesta kasvavalt", sortDescText: "Järjesta kahanevalt", columnsText: "Tulbad" }); Ext.define("Ext.locale.et.grid.feature.Grouping", { override: "Ext.grid.feature.Grouping", emptyGroupText: '(Tühi)', groupByText: 'Grupeeri selle välja järgi', showGroupsText: 'Näita gruppides' }); Ext.define("Ext.locale.et.grid.property.HeaderContainer", { override: "Ext.grid.property.HeaderContainer", nameText: "Nimi", valueText: "Väärtus", dateFormat: "d.m.Y" }); Ext.define("Ext.locale.et.grid.column.Date", { override: "Ext.grid.column.Date", format: 'd.m.Y' }); Ext.define("Ext.locale.et.form.field.Time", { override: "Ext.form.field.Time", minText: "Kellaaeg peab olema alates {0}", maxText: "Kellaaeg peab olema kuni {0}", invalidText: "{0} ei ole sobiv kellaaeg", format: "H:i" }); Ext.define("Ext.locale.et.form.CheckboxGroup", { override: "Ext.form.CheckboxGroup", blankText: "Vähemalt üks väli selles grupis peab olema valitud" }); Ext.define("Ext.locale.et.form.RadioGroup", { override: "Ext.form.RadioGroup", blankText: "Vähemalt üks väli selles grupis peab olema valitud" }); });
JavaScript
(function() { var url = getUrl(), thisDir = getDir(url), params = getMergedQueryParams(url), theme = getTheme(params), css = getCss(theme), js = getJs(theme); document.write(Ext.String.format('<link rel="stylesheet" type="text/css" href="{0}/../../resources/css/ext-{1}.css" />', thisDir, css)); if (js) { document.write(Ext.String.format('<script type="text/javascript" src="{0}/../../ext-{1}.js"></script>', thisDir, js)); } if (params.themes_combo != null) { Ext.require('Ext.panel.Panel'); Ext.require('Ext.data.ArrayStore'); Ext.require('Ext.form.field.ComboBox'); Ext.onReady(function() { Ext.create('Ext.panel.Panel', { autoShow: true, frame: true, renderTo: Ext.getBody(), items: { editable: false, fieldLabel: 'Theme', labelWidth: 50, value: theme, width: 180, xtype: 'combo', listeners: { change: function(combo, value) { params.theme = value; location.search = Ext.Object.toQueryString(params); } }, store: [ ['classic', 'Classic'], ['gray', 'Gray'], ['access', 'Accessibility'], ['neptune', 'Neptune'] ], style: { margin: '2px' } }, style: { position: 'absolute', right: '10px', top: '10px' } }); }); } // Extract the URL used to load this script file function getUrl() { var scripts = document.getElementsByTagName('script'), thisScript = scripts[scripts.length - 1]; return thisScript.src; } // The directory of this script file function getDir(url) { return url.slice(0, url.lastIndexOf('/')); } // Combines the query parameters from the page URL and the script URL function getMergedQueryParams(url) { var searchIndex = url.indexOf('?'), parse = Ext.Object.fromQueryString; return Ext.apply(searchIndex === -1 ? {} : parse(url.slice(searchIndex)), parse(location.search)); } // Get the canonical theme name from the query parameters function getTheme(params) { return { access: 'access', accessibility: 'access', gray: 'gray', grey: 'gray', neptune: 'neptune' }[params.theme || params.css] || 'classic'; } // Get the CSS file name from the theme name function getCss(theme) { return { access: 'all-access', classic: 'all', gray: 'all-gray', neptune: 'neptune' }[theme]; } // Get the JS file name from the theme name function getJs(theme) { return { neptune: 'neptune' }[theme]; } })();
JavaScript
// some data used in the examples Ext.namespace('Ext.example'); Ext.example.states = [ ['AL', 'Alabama', 'The Heart of Dixie'], ['AK', 'Alaska', 'The Land of the Midnight Sun'], ['AZ', 'Arizona', 'The Grand Canyon State'], ['AR', 'Arkansas', 'The Natural State'], ['CA', 'California', 'The Golden State'], ['CO', 'Colorado', 'The Mountain State'], ['CT', 'Connecticut', 'The Constitution State'], ['DE', 'Delaware', 'The First State'], ['DC', 'District of Columbia', "The Nation's Capital"], ['FL', 'Florida', 'The Sunshine State'], ['GA', 'Georgia', 'The Peach State'], ['HI', 'Hawaii', 'The Aloha State'], ['ID', 'Idaho', 'Famous Potatoes'], ['IL', 'Illinois', 'The Prairie State'], ['IN', 'Indiana', 'The Hospitality State'], ['IA', 'Iowa', 'The Corn State'], ['KS', 'Kansas', 'The Sunflower State'], ['KY', 'Kentucky', 'The Bluegrass State'], ['LA', 'Louisiana', 'The Bayou State'], ['ME', 'Maine', 'The Pine Tree State'], ['MD', 'Maryland', 'Chesapeake State'], ['MA', 'Massachusetts', 'The Spirit of America'], ['MI', 'Michigan', 'Great Lakes State'], ['MN', 'Minnesota', 'North Star State'], ['MS', 'Mississippi', 'Magnolia State'], ['MO', 'Missouri', 'Show Me State'], ['MT', 'Montana', 'Big Sky Country'], ['NE', 'Nebraska', 'Beef State'], ['NV', 'Nevada', 'Silver State'], ['NH', 'New Hampshire', 'Granite State'], ['NJ', 'New Jersey', 'Garden State'], ['NM', 'New Mexico', 'Land of Enchantment'], ['NY', 'New York', 'Empire State'], ['NC', 'North Carolina', 'First in Freedom'], ['ND', 'North Dakota', 'Peace Garden State'], ['OH', 'Ohio', 'The Heart of it All'], ['OK', 'Oklahoma', 'Oklahoma is OK'], ['OR', 'Oregon', 'Pacific Wonderland'], ['PA', 'Pennsylvania', 'Keystone State'], ['RI', 'Rhode Island', 'Ocean State'], ['SC', 'South Carolina', 'Nothing Could be Finer'], ['SD', 'South Dakota', 'Great Faces, Great Places'], ['TN', 'Tennessee', 'Volunteer State'], ['TX', 'Texas', 'Lone Star State'], ['UT', 'Utah', 'Salt Lake State'], ['VT', 'Vermont', 'Green Mountain State'], ['VA', 'Virginia', 'Mother of States'], ['WA', 'Washington', 'Green Tree State'], ['WV', 'West Virginia', 'Mountain State'], ['WI', 'Wisconsin', "America's Dairyland"], ['WY', 'Wyoming', 'Like No Place on Earth'] ];
JavaScript
Ext.example = function(){ var msgCt; function createBox(t, s){ // return ['<div class="msg">', // '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>', // '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>', // '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>', // '</div>'].join(''); return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>'; } return { msg : function(title, format){ if(!msgCt){ msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true); } var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1)); var m = Ext.DomHelper.append(msgCt, createBox(title, s), true); m.hide(); m.slideIn('t').ghost("t", { delay: 1000, remove: true}); }, init : function(){ if(!msgCt){ // It's better to create the msg-div here in order to avoid re-layouts // later that could interfere with the HtmlEditor and reset its iFrame. msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true); } // var t = Ext.get('exttheme'); // if(!t){ // run locally? // return; // } // var theme = Cookies.get('exttheme') || 'aero'; // if(theme){ // t.dom.value = theme; // Ext.getBody().addClass('x-'+theme); // } // t.on('change', function(){ // Cookies.set('exttheme', t.getValue()); // setTimeout(function(){ // window.location.reload(); // }, 250); // }); // // var lb = Ext.get('lib-bar'); // if(lb){ // lb.show(); // } } }; }(); Ext.onReady(Ext.example.init, Ext.example); Ext.example.shortBogusMarkup = '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, '+ 'sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales '+ 'non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet '+ 'tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla.</p>'; Ext.example.bogusMarkup = '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, '+ 'porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, '+ 'lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis '+ 'vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.<br/><br/>'+ 'Aliquam commodo ullamcorper erat. Nullam vel justo in neque porttitor laoreet. Aenean lacus dui, consequat eu, adipiscing '+ 'eget, nonummy non, nisi. Morbi nunc est, dignissim non, ornare sed, luctus eu, massa. Vivamus eget quam. Vivamus tincidunt '+ 'diam nec urna. Curabitur velit. Lorem ipsum dolor sit amet.</p>'; // old school cookie functions var Cookies = {}; Cookies.set = function(name, value){ var argv = arguments; var argc = arguments.length; var expires = (argc > 2) ? argv[2] : null; var path = (argc > 3) ? argv[3] : '/'; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : ""); }; Cookies.get = function(name){ var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; var j = 0; while(i < clen){ j = i + alen; if (document.cookie.substring(i, j) == arg) return Cookies.getCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if(i == 0) break; } return null; }; Cookies.clear = function(name) { if(Cookies.get(name)){ document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } }; Cookies.getCookieVal = function(offset){ var endstr = document.cookie.indexOf(";", offset); if(endstr == -1){ endstr = document.cookie.length; } return unescape(document.cookie.substring(offset, endstr)); };
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ var windowIndex = 0; Ext.define('MyDesktop.BogusModule', { extend: 'Ext.ux.desktop.Module', init : function(){ this.launcher = { text: 'Window '+(++windowIndex), iconCls:'bogus', handler : this.createWindow, scope: this, windowId:windowIndex } }, createWindow : function(src){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('bogus'+src.windowId); if(!win){ win = desktop.createWindow({ id: 'bogus'+src.windowId, title:src.text, width:640, height:480, html : '<p>Something useful would be in here.</p>', iconCls: 'bogus', animCollapse:false, constrainHeader:true }); } win.show(); return win; } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.ux.desktop.Desktop * @extends Ext.panel.Panel * <p>This class manages the wallpaper, shortcuts and taskbar.</p> */ Ext.define('Ext.ux.desktop.Desktop', { extend: 'Ext.panel.Panel', alias: 'widget.desktop', uses: [ 'Ext.util.MixedCollection', 'Ext.menu.Menu', 'Ext.view.View', // dataview 'Ext.window.Window', 'Ext.ux.desktop.TaskBar', 'Ext.ux.desktop.Wallpaper' ], activeWindowCls: 'ux-desktop-active-win', inactiveWindowCls: 'ux-desktop-inactive-win', lastActiveWindow: null, border: false, html: '&#160;', layout: 'fit', xTickSize: 1, yTickSize: 1, app: null, /** * @cfg {Array|Store} shortcuts * The items to add to the DataView. This can be a {@link Ext.data.Store Store} or a * simple array. Items should minimally provide the fields in the * {@link Ext.ux.desktop.ShorcutModel ShortcutModel}. */ shortcuts: null, /** * @cfg {String} shortcutItemSelector * This property is passed to the DataView for the desktop to select shortcut items. * If the {@link #shortcutTpl} is modified, this will probably need to be modified as * well. */ shortcutItemSelector: 'div.ux-desktop-shortcut', /** * @cfg {String} shortcutTpl * This XTemplate is used to render items in the DataView. If this is changed, the * {@link shortcutItemSelect} will probably also need to changed. */ shortcutTpl: [ '<tpl for=".">', '<div class="ux-desktop-shortcut" id="{name}-shortcut">', '<div class="ux-desktop-shortcut-icon {iconCls}">', '<img src="',Ext.BLANK_IMAGE_URL,'" title="{name}">', '</div>', '<span class="ux-desktop-shortcut-text">{name}</span>', '</div>', '</tpl>', '<div class="x-clear"></div>' ], /** * @cfg {Object} taskbarConfig * The config object for the TaskBar. */ taskbarConfig: null, windowMenu: null, initComponent: function () { var me = this; me.windowMenu = new Ext.menu.Menu(me.createWindowMenu()); me.bbar = me.taskbar = new Ext.ux.desktop.TaskBar(me.taskbarConfig); me.taskbar.windowMenu = me.windowMenu; me.windows = new Ext.util.MixedCollection(); me.contextMenu = new Ext.menu.Menu(me.createDesktopMenu()); me.items = [ { xtype: 'wallpaper', id: me.id+'_wallpaper' }, me.createDataView() ]; me.callParent(); me.shortcutsView = me.items.getAt(1); me.shortcutsView.on('itemclick', me.onShortcutItemClick, me); var wallpaper = me.wallpaper; me.wallpaper = me.items.getAt(0); if (wallpaper) { me.setWallpaper(wallpaper, me.wallpaperStretch); } }, afterRender: function () { var me = this; me.callParent(); me.el.on('contextmenu', me.onDesktopMenu, me); }, //------------------------------------------------------ // Overrideable configuration creation methods createDataView: function () { var me = this; return { xtype: 'dataview', overItemCls: 'x-view-over', trackOver: true, itemSelector: me.shortcutItemSelector, store: me.shortcuts, style: { position: 'absolute' }, x: 0, y: 0, tpl: new Ext.XTemplate(me.shortcutTpl) }; }, createDesktopMenu: function () { var me = this, ret = { items: me.contextMenuItems || [] }; if (ret.items.length) { ret.items.push('-'); } ret.items.push( { text: 'Tile', handler: me.tileWindows, scope: me, minWindows: 1 }, { text: 'Cascade', handler: me.cascadeWindows, scope: me, minWindows: 1 }) return ret; }, createWindowMenu: function () { var me = this; return { defaultAlign: 'br-tr', items: [ { text: 'Restore', handler: me.onWindowMenuRestore, scope: me }, { text: 'Minimize', handler: me.onWindowMenuMinimize, scope: me }, { text: 'Maximize', handler: me.onWindowMenuMaximize, scope: me }, '-', { text: 'Close', handler: me.onWindowMenuClose, scope: me } ], listeners: { beforeshow: me.onWindowMenuBeforeShow, hide: me.onWindowMenuHide, scope: me } }; }, //------------------------------------------------------ // Event handler methods onDesktopMenu: function (e) { var me = this, menu = me.contextMenu; e.stopEvent(); if (!menu.rendered) { menu.on('beforeshow', me.onDesktopMenuBeforeShow, me); } menu.showAt(e.getXY()); menu.doConstrain(); }, onDesktopMenuBeforeShow: function (menu) { var me = this, count = me.windows.getCount(); menu.items.each(function (item) { var min = item.minWindows || 0; item.setDisabled(count < min); }); }, onShortcutItemClick: function (dataView, record) { var me = this, module = me.app.getModule(record.data.module), win = module && module.createWindow(); if (win) { me.restoreWindow(win); } }, onWindowClose: function(win) { var me = this; me.windows.remove(win); me.taskbar.removeTaskButton(win.taskButton); me.updateActiveWindow(); }, //------------------------------------------------------ // Window context menu handlers onWindowMenuBeforeShow: function (menu) { var items = menu.items.items, win = menu.theWin; items[0].setDisabled(win.maximized !== true && win.hidden !== true); // Restore items[1].setDisabled(win.minimized === true); // Minimize items[2].setDisabled(win.maximized === true || win.hidden === true); // Maximize }, onWindowMenuClose: function () { var me = this, win = me.windowMenu.theWin; win.close(); }, onWindowMenuHide: function (menu) { menu.theWin = null; }, onWindowMenuMaximize: function () { var me = this, win = me.windowMenu.theWin; win.maximize(); win.toFront(); }, onWindowMenuMinimize: function () { var me = this, win = me.windowMenu.theWin; win.minimize(); }, onWindowMenuRestore: function () { var me = this, win = me.windowMenu.theWin; me.restoreWindow(win); }, //------------------------------------------------------ // Dynamic (re)configuration methods getWallpaper: function () { return this.wallpaper.wallpaper; }, setTickSize: function(xTickSize, yTickSize) { var me = this, xt = me.xTickSize = xTickSize, yt = me.yTickSize = (arguments.length > 1) ? yTickSize : xt; me.windows.each(function(win) { var dd = win.dd, resizer = win.resizer; dd.xTickSize = xt; dd.yTickSize = yt; resizer.widthIncrement = xt; resizer.heightIncrement = yt; }); }, setWallpaper: function (wallpaper, stretch) { this.wallpaper.setWallpaper(wallpaper, stretch); return this; }, //------------------------------------------------------ // Window management methods cascadeWindows: function() { var x = 0, y = 0, zmgr = this.getDesktopZIndexManager(); zmgr.eachBottomUp(function(win) { if (win.isWindow && win.isVisible() && !win.maximized) { win.setPosition(x, y); x += 20; y += 20; } }); }, createWindow: function(config, cls) { var me = this, win, cfg = Ext.applyIf(config || {}, { stateful: false, isWindow: true, constrainHeader: true, minimizable: true, maximizable: true }); cls = cls || Ext.window.Window; win = me.add(new cls(cfg)); me.windows.add(win); win.taskButton = me.taskbar.addTaskButton(win); win.animateTarget = win.taskButton.el; win.on({ activate: me.updateActiveWindow, beforeshow: me.updateActiveWindow, deactivate: me.updateActiveWindow, minimize: me.minimizeWindow, destroy: me.onWindowClose, scope: me }); win.on({ boxready: function () { win.dd.xTickSize = me.xTickSize; win.dd.yTickSize = me.yTickSize; if (win.resizer) { win.resizer.widthIncrement = me.xTickSize; win.resizer.heightIncrement = me.yTickSize; } }, single: true }); // replace normal window close w/fadeOut animation: win.doClose = function () { win.doClose = Ext.emptyFn; // dblclick can call again... win.el.disableShadow(); win.el.fadeOut({ listeners: { afteranimate: function () { win.destroy(); } } }); }; return win; }, getActiveWindow: function () { var win = null, zmgr = this.getDesktopZIndexManager(); if (zmgr) { // We cannot rely on activate/deactive because that fires against non-Window // components in the stack. zmgr.eachTopDown(function (comp) { if (comp.isWindow && !comp.hidden) { win = comp; return false; } return true; }); } return win; }, getDesktopZIndexManager: function () { var windows = this.windows; // TODO - there has to be a better way to get this... return (windows.getCount() && windows.getAt(0).zIndexManager) || null; }, getWindow: function(id) { return this.windows.get(id); }, minimizeWindow: function(win) { win.minimized = true; win.hide(); }, restoreWindow: function (win) { if (win.isVisible()) { win.restore(); win.toFront(); } else { win.show(); } return win; }, tileWindows: function() { var me = this, availWidth = me.body.getWidth(true); var x = me.xTickSize, y = me.yTickSize, nextY = y; me.windows.each(function(win) { if (win.isVisible() && !win.maximized) { var w = win.el.getWidth(); // Wrap to next row if we are not at the line start and this Window will // go off the end if (x > me.xTickSize && x + w > availWidth) { x = me.xTickSize; y = nextY; } win.setPosition(x, y); x += w + me.xTickSize; nextY = Math.max(nextY, y + win.el.getHeight() + me.yTickSize); } }); }, updateActiveWindow: function () { var me = this, activeWindow = me.getActiveWindow(), last = me.lastActiveWindow; if (activeWindow === last) { return; } if (last) { if (last.el.dom) { last.addCls(me.inactiveWindowCls); last.removeCls(me.activeWindowCls); } last.active = false; } me.lastActiveWindow = activeWindow; if (activeWindow) { activeWindow.addCls(me.activeWindowCls); activeWindow.removeCls(me.inactiveWindowCls); activeWindow.minimized = false; activeWindow.active = true; } me.taskbar.setActiveButton(activeWindow && activeWindow.taskButton); } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('Ext.ux.desktop.Module', { mixins: { observable: 'Ext.util.Observable' }, constructor: function (config) { this.mixins.observable.constructor.call(this, config); this.init(); }, init: Ext.emptyFn });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ // From code originally written by David Davis (http://www.sencha.com/blog/html5-video-canvas-and-ext-js/) /* -NOTICE- * For HTML5 video to work, your server must * send the right content type, for more info see: * http://developer.mozilla.org/En/HTML/Element/Video */ Ext.define('Ext.ux.desktop.Video', { extend: 'Ext.panel.Panel', alias: 'widget.video', layout: 'fit', autoplay: false, controls: true, bodyStyle: 'background-color:#000;color:#fff', html: '', initComponent: function () { this.callParent(); }, afterRender: function () { var fallback; if (this.fallbackHTML) { fallback = this.fallbackHTML; } else { fallback = "Your browser does not support HTML5 Video. "; if (Ext.isChrome) { fallback += 'Upgrade Chrome.'; } else if (Ext.isGecko) { fallback += 'Upgrade to Firefox 3.5 or newer.'; } else { var chrome = '<a href="http://www.google.com/chrome">Chrome</a>'; fallback += 'Please try <a href="http://www.mozilla.com">Firefox</a>'; if (Ext.isIE) { fallback += ', ' + chrome + ' or <a href="http://www.apple.com/safari/">Safari</a>.'; } else { fallback += ' or ' + chrome + '.'; } } } // match the video size to the panel dimensions var size = this.getSize(); var cfg = Ext.copyTo({ tag : 'video', width : size.width, height: size.height }, this, 'poster,start,loopstart,loopend,playcount,autobuffer,loop'); // just having the params exist enables them if (this.autoplay) { cfg.autoplay = 1; } if (this.controls) { cfg.controls = 1; } // handle multiple sources if (Ext.isArray(this.src)) { cfg.children = []; for (var i = 0, len = this.src.length; i < len; i++) { if (!Ext.isObject(this.src[i])) { Ext.Error.raise('The src list passed to "video" must be an array of objects'); } cfg.children.push( Ext.applyIf({tag: 'source'}, this.src[i]) ); } cfg.children.push({ html: fallback }); } else { cfg.src = this.src; cfg.html = fallback; } this.video = this.body.createChild(cfg); var el = this.video.dom; this.supported = (el && el.tagName.toLowerCase() == 'video'); }, afterComponentLayout : function() { var me = this; me.callParent(arguments); if (me.video) { me.video.setSize(me.body.getSize()); } }, onDestroy: function () { var video = this.video; if (video) { var videoDom = video.dom; if (videoDom && videoDom.pause) { videoDom.pause(); } video.remove(); this.video = null; } this.callParent(); } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('Ext.ux.desktop.StartMenu', { extend: 'Ext.panel.Panel', requires: [ 'Ext.menu.Menu', 'Ext.toolbar.Toolbar' ], ariaRole: 'menu', cls: 'x-menu ux-start-menu', defaultAlign: 'bl-tl', iconCls: 'user', floating: true, shadow: true, // We have to hardcode a width because the internal Menu cannot drive our width. // This is combined with changing the align property of the menu's layout from the // typical 'stretchmax' to 'stretch' which allows the the items to fill the menu // area. width: 300, initComponent: function() { var me = this, menu = me.menu; me.menu = new Ext.menu.Menu({ cls: 'ux-start-menu-body', border: false, floating: false, items: menu }); me.menu.layout.align = 'stretch'; me.items = [me.menu]; me.layout = 'fit'; Ext.menu.Manager.register(me); me.callParent(); // TODO - relay menu events me.toolbar = new Ext.toolbar.Toolbar(Ext.apply({ dock: 'right', cls: 'ux-start-menu-toolbar', vertical: true, width: 100 }, me.toolConfig)); me.toolbar.layout.align = 'stretch'; me.addDocked(me.toolbar); delete me.toolItems; me.on('deactivate', function () { me.hide(); }); }, addMenuItem: function() { var cmp = this.menu; cmp.add.apply(cmp, arguments); }, addToolItem: function() { var cmp = this.toolbar; cmp.add.apply(cmp, arguments); }, showBy: function(cmp, pos, off) { var me = this; if (me.floating && cmp) { me.layout.autoSize = true; me.show(); // Component or Element cmp = cmp.el || cmp; // Convert absolute to floatParent-relative coordinates if necessary. var xy = me.el.getAlignToXY(cmp, pos || me.defaultAlign, off); if (me.floatParent) { var r = me.floatParent.getTargetEl().getViewRegion(); xy[0] -= r.x; xy[1] -= r.y; } me.showAt(xy); me.doConstrain(); } return me; } }); // StartMenu
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.ux.desktop.Wallpaper * @extends Ext.Component * <p>This component renders an image that stretches to fill the component.</p> */ Ext.define('Ext.ux.desktop.Wallpaper', { extend: 'Ext.Component', alias: 'widget.wallpaper', cls: 'ux-wallpaper', html: '<img src="'+Ext.BLANK_IMAGE_URL+'">', stretch: false, wallpaper: null, stateful : true, stateId : 'desk-wallpaper', afterRender: function () { var me = this; me.callParent(); me.setWallpaper(me.wallpaper, me.stretch); }, applyState: function () { var me = this, old = me.wallpaper; me.callParent(arguments); if (old != me.wallpaper) { me.setWallpaper(me.wallpaper); } }, getState: function () { return this.wallpaper && { wallpaper: this.wallpaper }; }, setWallpaper: function (wallpaper, stretch) { var me = this, imgEl, bkgnd; me.stretch = (stretch !== false); me.wallpaper = wallpaper; if (me.rendered) { imgEl = me.el.dom.firstChild; if (!wallpaper || wallpaper == Ext.BLANK_IMAGE_URL) { Ext.fly(imgEl).hide(); } else if (me.stretch) { imgEl.src = wallpaper; me.el.removeCls('ux-wallpaper-tiled'); Ext.fly(imgEl).setStyle({ width: '100%', height: '100%' }).show(); } else { Ext.fly(imgEl).hide(); bkgnd = 'url('+wallpaper+')'; me.el.addCls('ux-wallpaper-tiled'); } me.el.setStyle({ backgroundImage: bkgnd || '' }); if(me.stateful) { me.saveState(); } } return me; } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.ux.desktop.ShortcutModel * @extends Ext.data.Model * This model defines the minimal set of fields for desktop shortcuts. */ Ext.define('Ext.ux.desktop.ShortcutModel', { extend: 'Ext.data.Model', fields: [ { name: 'name' }, { name: 'iconCls' }, { name: 'module' } ] });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('Ext.ux.desktop.App', { mixins: { observable: 'Ext.util.Observable' }, requires: [ 'Ext.container.Viewport', 'Ext.ux.desktop.Desktop' ], isReady: false, modules: null, useQuickTips: true, constructor: function (config) { var me = this; me.addEvents( 'ready', 'beforeunload' ); me.mixins.observable.constructor.call(this, config); if (Ext.isReady) { Ext.Function.defer(me.init, 10, me); } else { Ext.onReady(me.init, me); } }, init: function() { var me = this, desktopCfg; if (me.useQuickTips) { Ext.QuickTips.init(); } me.modules = me.getModules(); if (me.modules) { me.initModules(me.modules); } desktopCfg = me.getDesktopConfig(); me.desktop = new Ext.ux.desktop.Desktop(desktopCfg); me.viewport = new Ext.container.Viewport({ layout: 'fit', items: [ me.desktop ] }); Ext.EventManager.on(window, 'beforeunload', me.onUnload, me); me.isReady = true; me.fireEvent('ready', me); }, /** * This method returns the configuration object for the Desktop object. A derived * class can override this method, call the base version to build the config and * then modify the returned object before returning it. */ getDesktopConfig: function () { var me = this, cfg = { app: me, taskbarConfig: me.getTaskbarConfig() }; Ext.apply(cfg, me.desktopConfig); return cfg; }, getModules: Ext.emptyFn, /** * This method returns the configuration object for the Start Button. A derived * class can override this method, call the base version to build the config and * then modify the returned object before returning it. */ getStartConfig: function () { var me = this, cfg = { app: me, menu: [] }, launcher; Ext.apply(cfg, me.startConfig); Ext.each(me.modules, function (module) { launcher = module.launcher; if (launcher) { launcher.handler = launcher.handler || Ext.bind(me.createWindow, me, [module]); cfg.menu.push(module.launcher); } }); return cfg; }, createWindow: function(module) { var window = module.createWindow(); window.show(); }, /** * This method returns the configuration object for the TaskBar. A derived class * can override this method, call the base version to build the config and then * modify the returned object before returning it. */ getTaskbarConfig: function () { var me = this, cfg = { app: me, startConfig: me.getStartConfig() }; Ext.apply(cfg, me.taskbarConfig); return cfg; }, initModules : function(modules) { var me = this; Ext.each(modules, function (module) { module.app = me; }); }, getModule : function(name) { var ms = this.modules; for (var i = 0, len = ms.length; i < len; i++) { var m = ms[i]; if (m.id == name || m.appType == name) { return m; } } return null; }, onReady : function(fn, scope) { if (this.isReady) { fn.call(scope, this); } else { this.on({ ready: fn, scope: scope, single: true }); } }, getDesktop : function() { return this.desktop; }, onUnload : function(e) { if (this.fireEvent('beforeunload', this) === false) { e.stopEvent(); } } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.ux.desktop.TaskBar * @extends Ext.toolbar.Toolbar */ Ext.define('Ext.ux.desktop.TaskBar', { extend: 'Ext.toolbar.Toolbar', // TODO - make this a basic hbox panel... requires: [ 'Ext.button.Button', 'Ext.resizer.Splitter', 'Ext.menu.Menu', 'Ext.ux.desktop.StartMenu' ], alias: 'widget.taskbar', cls: 'ux-taskbar', /** * @cfg {String} startBtnText * The text for the Start Button. */ startBtnText: 'Start', initComponent: function () { var me = this; me.startMenu = new Ext.ux.desktop.StartMenu(me.startConfig); me.quickStart = new Ext.toolbar.Toolbar(me.getQuickStart()); me.windowBar = new Ext.toolbar.Toolbar(me.getWindowBarConfig()); me.tray = new Ext.toolbar.Toolbar(me.getTrayConfig()); me.items = [ { xtype: 'button', cls: 'ux-start-button', iconCls: 'ux-start-button-icon', menu: me.startMenu, menuAlign: 'bl-tl', text: me.startBtnText }, me.quickStart, { xtype: 'splitter', html: '&#160;', height: 14, width: 2, // TODO - there should be a CSS way here cls: 'x-toolbar-separator x-toolbar-separator-horizontal' }, //'-', me.windowBar, '-', me.tray ]; me.callParent(); }, afterLayout: function () { var me = this; me.callParent(); me.windowBar.el.on('contextmenu', me.onButtonContextMenu, me); }, /** * This method returns the configuration object for the Quick Start toolbar. A derived * class can override this method, call the base version to build the config and * then modify the returned object before returning it. */ getQuickStart: function () { var me = this, ret = { minWidth: 20, width: 60, items: [], enableOverflow: true }; Ext.each(this.quickStart, function (item) { ret.items.push({ tooltip: { text: item.name, align: 'bl-tl' }, //tooltip: item.name, overflowText: item.name, iconCls: item.iconCls, module: item.module, handler: me.onQuickStartClick, scope: me }); }); return ret; }, /** * This method returns the configuration object for the Tray toolbar. A derived * class can override this method, call the base version to build the config and * then modify the returned object before returning it. */ getTrayConfig: function () { var ret = { width: 80, items: this.trayItems }; delete this.trayItems; return ret; }, getWindowBarConfig: function () { return { flex: 1, cls: 'ux-desktop-windowbar', items: [ '&#160;' ], layout: { overflowHandler: 'Scroller' } }; }, getWindowBtnFromEl: function (el) { var c = this.windowBar.getChildByElement(el); return c || null; }, onQuickStartClick: function (btn) { var module = this.app.getModule(btn.module), window; if (module) { window = module.createWindow(); window.show(); } }, onButtonContextMenu: function (e) { var me = this, t = e.getTarget(), btn = me.getWindowBtnFromEl(t); if (btn) { e.stopEvent(); me.windowMenu.theWin = btn.win; me.windowMenu.showBy(t); } }, onWindowBtnClick: function (btn) { var win = btn.win; if (win.minimized || win.hidden) { win.show(); } else if (win.active) { win.minimize(); } else { win.toFront(); } }, addTaskButton: function(win) { var config = { iconCls: win.iconCls, enableToggle: true, toggleGroup: 'all', width: 140, margins: '0 2 0 3', text: Ext.util.Format.ellipsis(win.title, 20), listeners: { click: this.onWindowBtnClick, scope: this }, win: win }; var cmp = this.windowBar.add(config); cmp.toggle(true); return cmp; }, removeTaskButton: function (btn) { var found, me = this; me.windowBar.items.each(function (item) { if (item === btn) { found = item; } return !found; }); if (found) { me.windowBar.remove(found); } return found; }, setActiveButton: function(btn) { if (btn) { btn.toggle(true); } else { this.windowBar.items.each(function (item) { if (item.isButton) { item.toggle(false); } }); } } }); /** * @class Ext.ux.desktop.TrayClock * @extends Ext.toolbar.TextItem * This class displays a clock on the toolbar. */ Ext.define('Ext.ux.desktop.TrayClock', { extend: 'Ext.toolbar.TextItem', alias: 'widget.trayclock', cls: 'ux-desktop-trayclock', html: '&#160;', timeFormat: 'g:i A', tpl: '{time}', initComponent: function () { var me = this; me.callParent(); if (typeof(me.tpl) == 'string') { me.tpl = new Ext.XTemplate(me.tpl); } }, afterRender: function () { var me = this; Ext.Function.defer(me.updateTime, 100, me); me.callParent(); }, onDestroy: function () { var me = this; if (me.timer) { window.clearTimeout(me.timer); me.timer = null; } me.callParent(); }, updateTime: function () { var me = this, time = Ext.Date.format(new Date(), me.timeFormat), text = me.tpl.apply({ time: time }); if (me.lastText != text) { me.setText(text); me.lastText = text; } me.timer = Ext.Function.defer(me.updateTime, 10000, me); } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.WallpaperModel', { extend: 'Ext.data.Model', fields: [ { name: 'text' }, { name: 'img' } ] });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.Settings', { extend: 'Ext.window.Window', uses: [ 'Ext.tree.Panel', 'Ext.tree.View', 'Ext.form.field.Checkbox', 'Ext.layout.container.Anchor', 'Ext.layout.container.Border', 'Ext.ux.desktop.Wallpaper', 'MyDesktop.WallpaperModel' ], layout: 'anchor', title: 'Change Settings', modal: true, width: 640, height: 480, border: false, initComponent: function () { var me = this; me.selected = me.desktop.getWallpaper(); me.stretch = me.desktop.wallpaper.stretch; me.preview = Ext.create('widget.wallpaper'); me.preview.setWallpaper(me.selected); me.tree = me.createTree(); me.buttons = [ { text: 'OK', handler: me.onOK, scope: me }, { text: 'Cancel', handler: me.close, scope: me } ]; me.items = [ { anchor: '0 -30', border: false, layout: 'border', items: [ me.tree, { xtype: 'panel', title: 'Preview', region: 'center', layout: 'fit', items: [ me.preview ] } ] }, { xtype: 'checkbox', boxLabel: 'Stretch to fit', checked: me.stretch, listeners: { change: function (comp) { me.stretch = comp.checked; } } } ]; me.callParent(); }, createTree : function() { var me = this; function child (img) { return { img: img, text: me.getTextOfWallpaper(img), iconCls: '', leaf: true }; } var tree = new Ext.tree.Panel({ title: 'Desktop Background', rootVisible: false, lines: false, autoScroll: true, width: 150, region: 'west', split: true, minWidth: 100, listeners: { afterrender: { fn: this.setInitialSelection, delay: 100 }, select: this.onSelect, scope: this }, store: new Ext.data.TreeStore({ model: 'MyDesktop.WallpaperModel', root: { text:'Wallpaper', expanded: true, children:[ { text: "None", iconCls: '', leaf: true }, child('Blue-Sencha.jpg'), child('Dark-Sencha.jpg'), child('Wood-Sencha.jpg'), child('blue.jpg'), child('desk.jpg'), child('desktop.jpg'), child('desktop2.jpg'), child('sky.jpg') ] } }) }); return tree; }, getTextOfWallpaper: function (path) { var text = path, slash = path.lastIndexOf('/'); if (slash >= 0) { text = text.substring(slash+1); } var dot = text.lastIndexOf('.'); text = Ext.String.capitalize(text.substring(0, dot)); text = text.replace(/[-]/g, ' '); return text; }, onOK: function () { var me = this; if (me.selected) { me.desktop.setWallpaper(me.selected, me.stretch); } me.destroy(); }, onSelect: function (tree, record) { var me = this; if (record.data.img) { me.selected = 'wallpapers/' + record.data.img; } else { me.selected = Ext.BLANK_IMAGE_URL; } me.preview.setWallpaper(me.selected); }, setInitialSelection: function () { var s = this.desktop.getWallpaper(); if (s) { var path = '/Wallpaper/' + this.getTextOfWallpaper(s); this.tree.selectPath(path, 'text'); } } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.AccordionWindow', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.data.TreeStore', 'Ext.layout.container.Accordion', 'Ext.toolbar.Spacer', 'Ext.tree.Panel' ], id:'acc-win', init : function(){ this.launcher = { text: 'Accordion Window', iconCls:'accordion' }; }, createTree : function(){ var tree = Ext.create('Ext.tree.Panel', { id:'im-tree', title: 'Online Users', rootVisible:false, lines:false, autoScroll:true, tools:[{ type: 'refresh', handler: function(c, t) { tree.setLoading(true, tree.body); var root = tree.getRootNode(); root.collapseChildren(true, false); Ext.Function.defer(function() { // mimic a server call tree.setLoading(false); root.expand(true, true); }, 1000); } }], store: Ext.create('Ext.data.TreeStore', { root: { text:'Online', expanded: true, children:[{ text:'Friends', expanded:true, children:[ { text:'Brian', iconCls:'user', leaf:true }, { text:'Kevin', iconCls:'user', leaf:true }, { text:'Mark', iconCls:'user', leaf:true }, { text:'Matt', iconCls:'user', leaf:true }, { text:'Michael', iconCls:'user', leaf:true }, { text:'Mike Jr', iconCls:'user', leaf:true }, { text:'Mike Sr', iconCls:'user', leaf:true }, { text:'JR', iconCls:'user', leaf:true }, { text:'Rich', iconCls:'user', leaf:true }, { text:'Nige', iconCls:'user', leaf:true }, { text:'Zac', iconCls:'user', leaf:true } ] },{ text:'Family', expanded:true, children:[ { text:'Kiana', iconCls:'user-girl', leaf:true }, { text:'Aubrey', iconCls:'user-girl', leaf:true }, { text:'Cale', iconCls:'user-kid', leaf:true } ] }] } }) }); return tree; }, createWindow : function(){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('acc-win'); if (!win) { win = desktop.createWindow({ id: 'acc-win', title: 'Accordion Window', width: 250, height: 400, iconCls: 'accordion', animCollapse: false, constrainHeader: true, bodyBorder: true, tbar: { xtype: 'toolbar', ui: 'plain', items: [{ tooltip:{title:'Rich Tooltips', text:'Let your users know what they can do!'}, iconCls:'connect' }, '-', { tooltip:'Add a new user', iconCls:'user-add' }, ' ', { tooltip:'Remove the selected user', iconCls:'user-delete' }] }, layout: 'accordion', border: false, items: [ this.createTree(), { title: 'Settings', html:'<p>Something useful would be in here.</p>', autoScroll:true }, { title: 'Even More Stuff', html : '<p>Something useful would be in here.</p>' }, { title: 'My Stuff', html : '<p>Something useful would be in here.</p>' } ] }); } return win; } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.TabWindow', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.tab.Panel' ], id:'tab-win', init : function(){ this.launcher = { text: 'Tab Window', iconCls:'tabs' } }, createWindow : function(){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('tab-win'); if(!win){ win = desktop.createWindow({ id: 'tab-win', title:'Tab Window', width:740, height:480, iconCls: 'tabs', animCollapse:false, border:false, constrainHeader:true, layout: 'fit', items: [ { xtype: 'tabpanel', activeTab:0, bodyStyle: 'padding: 5px;', items: [{ title: 'Tab Text 1', header:false, html : '<p>Something useful would be in here.</p>', border:false },{ title: 'Tab Text 2', header:false, html : '<p>Something useful would be in here.</p>', border:false },{ title: 'Tab Text 3', header:false, html : '<p>Something useful would be in here.</p>', border:false },{ title: 'Tab Text 4', header:false, html : '<p>Something useful would be in here.</p>', border:false }] } ] }); } return win; } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.SystemStatus', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.chart.*' ], id: 'systemstatus', refreshRate: 500, init : function() { // No launcher means we don't appear on the Start Menu... // this.launcher = { // text: 'SystemStatus', // iconCls:'cpustats' // }; Ext.chart.theme.Memory = Ext.extend(Ext.chart.theme.Base, { constructor: function(config) { Ext.chart.theme.Memory.superclass.constructor.call(this, Ext.apply({ colors: [ 'rgb(244, 16, 0)', 'rgb(248, 130, 1)', 'rgb(0, 7, 255)', 'rgb(84, 254, 0)'] }, config)); } }); }, createNewWindow: function () { var me = this, desktop = me.app.getDesktop(); me.cpuLoadData = []; me.cpuLoadStore = Ext.create('store.json', { fields: ['core1', 'core2', 'time'] }); me.memoryArray = ['Wired', 'Active', 'Inactive', 'Free']; me.memoryStore = Ext.create('store.json', { fields: ['name', 'memory'], data: me.generateData(me.memoryArray) }); me.pass = 0; me.processArray = ['explorer', 'monitor', 'charts', 'desktop', 'Ext3', 'Ext4']; me.processesMemoryStore = Ext.create('store.json', { fields: ['name', 'memory'], data: me.generateData(me.processArray) }); me.generateCpuLoad(); return desktop.createWindow({ id: 'systemstatus', title: 'System Status', width: 800, height: 600, animCollapse:false, constrainHeader:true, border: false, layout: { type: 'hbox', align: 'stretch' }, bodyStyle: { 'background-color': '#FFF' }, listeners: { afterrender: { fn: me.updateCharts, delay: 100 }, destroy: function () { clearTimeout(me.updateTimer); me.updateTimer = null; }, scope: me }, items: [{ flex: 1, xtype: 'container', layout: { type: 'vbox', align: 'stretch' }, items: [ me.createCpu1LoadChart(), me.createCpu2LoadChart() ] }, { flex: 1, xtype: 'container', layout: { type: 'vbox', align: 'stretch' }, items: [ me.createMemoryPieChart(), me.createProcessChart() ] }] }); }, createWindow : function() { var win = this.app.getDesktop().getWindow(this.id); if (!win) { win = this.createNewWindow(); } return win; }, createCpu1LoadChart: function () { return { flex: 1, xtype: 'chart', theme: 'Category1', animate: false, store: this.cpuLoadStore, legend: { position: 'bottom' }, axes: [{ type: 'Numeric', position: 'left', minimum: 0, maximum: 100, fields: ['core1'], title: 'CPU Load', grid: true, labelTitle: { font: '13px Arial' }, label: { font: '11px Arial' } }], series: [{ title: 'Core 1 (3.4GHz)', type: 'line', lineWidth: 4, showMarkers: false, fill: true, axis: 'left', xField: 'time', yField: 'core1', style: { 'stroke-width': 1 } }] }; }, createCpu2LoadChart: function () { return { flex: 1, xtype: 'chart', theme: 'Category2', animate: false, store: this.cpuLoadStore, legend: { position: 'bottom' }, axes: [{ type: 'Numeric', position: 'left', minimum: 0, maximum: 100, grid: true, fields: ['core2'], title: 'CPU Load', labelTitle: { font: '13px Arial' }, label: { font: '11px Arial' } }], series: [{ title: 'Core 2 (3.4GHz)', type: 'line', lineWidth: 4, showMarkers: false, fill: true, axis: 'left', xField: 'time', yField: 'core2', style: { 'stroke-width': 1 } }] }; }, createMemoryPieChart: function () { var me = this; return { flex: 1, xtype: 'chart', animate: { duration: 250 }, store: this.memoryStore, shadow: true, legend: { position: 'right' }, insetPadding: 40, theme: 'Memory:gradients', series: [{ donut: 30, type: 'pie', field: 'memory', showInLegend: true, tips: { trackMouse: true, width: 140, height: 28, renderer: function(storeItem, item) { //calculate percentage. var total = 0; me.memoryStore.each(function(rec) { total += rec.get('memory'); }); this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('memory') / total * 100) + '%'); } }, highlight: { segment: { margin: 20 } }, labelTitle: { font: '13px Arial' }, label: { field: 'name', display: 'rotate', contrast: true, font: '12px Arial' } }] }; }, createProcessChart: function () { return { flex: 1, xtype: 'chart', theme: 'Category1', store: this.processesMemoryStore, animate: { easing: 'ease-in-out', duration: 750 }, axes: [{ type: 'Numeric', position: 'left', minimum: 0, maximum: 10, fields: ['memory'], title: 'Memory', labelTitle: { font: '13px Arial' }, label: { font: '11px Arial' } },{ type: 'Category', position: 'bottom', fields: ['name'], title: 'System Processes', labelTitle: { font: 'bold 14px Arial' }, label: { rotation: { degrees: 45 } } },{ type: 'Numeric', position: 'top', fields: ['memory'], title: 'Memory Usage', labelTitle: { font: 'bold 14px Arial' }, label: { fill: '#FFFFFF', stroke: '#FFFFFF' }, axisStyle: { fill: '#FFFFFF', stroke: '#FFFFFF' } }], series: [{ title: 'Processes', type: 'column', xField: 'name', yField: 'memory', renderer: function(sprite, record, attr, index, store) { var lowColor = Ext.draw.Color.fromString('#b1da5a'), value = record.get('memory'), color; if (value > 5) { color = lowColor.getDarker((value - 5) / 15).toString(); } else { color = lowColor.getLighter(((5 - value) / 20)).toString(); } if (value >= 8) { color = '#CD0000'; } return Ext.apply(attr, { fill: color }); } }] }; }, generateCpuLoad: function () { var me = this, data = me.cpuLoadData; function generate(factor) { var value = factor + ((Math.floor(Math.random() * 2) % 2) ? -1 : 1) * Math.floor(Math.random() * 9); if (value < 0 || value > 100) { value = 50; } return value; } if (data.length === 0) { data.push({ core1: 0, core2: 0, time: 0 }); for (var i = 1; i < 100; i++) { data.push({ core1: generate(data[i - 1].core1), core2: generate(data[i - 1].core2), time: i }); } me.cpuLoadStore.loadData(data); } else { me.cpuLoadStore.data.removeAt(0); me.cpuLoadStore.data.each(function(item, key) { item.data.time = key; }); var lastData = me.cpuLoadStore.last().data; me.cpuLoadStore.loadData([{ core1: generate(lastData.core1), core2: generate(lastData.core2), time: lastData.time + 1 }], true); } }, generateData: function (names) { var data = [], i, rest = names.length, consume; for (i = 0; i < names.length; i++) { consume = Math.floor(Math.random() * rest * 100) / 100 + 2; rest = rest - (consume - 5); data.push({ name: names[i], memory: consume }); } return data; }, updateCharts: function () { var me = this; clearTimeout(me.updateTimer); me.updateTimer = setTimeout(function() { var start = new Date().getTime(); if (me.pass % 3 === 0) { me.memoryStore.loadData(me.generateData(me.memoryArray)); } if (me.pass % 5 === 0) { me.processesMemoryStore.loadData(me.generateData(me.processArray)); } me.generateCpuLoad(); var end = new Date().getTime(); // no more than 25% average CPU load me.refreshRate = Math.max(me.refreshRate, (end - start) * 4); me.updateCharts(); me.pass++; }, me.refreshRate); } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.App', { extend: 'Ext.ux.desktop.App', requires: [ 'Ext.window.MessageBox', 'Ext.ux.desktop.ShortcutModel', 'MyDesktop.SystemStatus', 'MyDesktop.VideoWindow', 'MyDesktop.GridWindow', 'MyDesktop.TabWindow', 'MyDesktop.AccordionWindow', 'MyDesktop.Notepad', 'MyDesktop.BogusMenuModule', 'MyDesktop.BogusModule', // 'MyDesktop.Blockalanche', 'MyDesktop.Settings' ], init: function() { // custom logic before getXYZ methods get called... this.callParent(); // now ready... }, getModules : function(){ return [ new MyDesktop.VideoWindow(), //new MyDesktop.Blockalanche(), new MyDesktop.SystemStatus(), new MyDesktop.GridWindow(), new MyDesktop.TabWindow(), new MyDesktop.AccordionWindow(), new MyDesktop.Notepad(), new MyDesktop.BogusMenuModule(), new MyDesktop.BogusModule() ]; }, getDesktopConfig: function () { var me = this, ret = me.callParent(); return Ext.apply(ret, { //cls: 'ux-desktop-black', contextMenuItems: [ { text: 'Change Settings', handler: me.onSettings, scope: me } ], shortcuts: Ext.create('Ext.data.Store', { model: 'Ext.ux.desktop.ShortcutModel', data: [ { name: 'Grid Window', iconCls: 'grid-shortcut', module: 'grid-win' }, { name: 'Accordion Window', iconCls: 'accordion-shortcut', module: 'acc-win' }, { name: 'Notepad', iconCls: 'notepad-shortcut', module: 'notepad' }, { name: 'System Status', iconCls: 'cpu-shortcut', module: 'systemstatus'} ] }), wallpaper: 'wallpapers/Blue-Sencha.jpg', wallpaperStretch: false }); }, // config for the start menu getStartConfig : function() { var me = this, ret = me.callParent(); return Ext.apply(ret, { title: 'Don Griffin', iconCls: 'user', height: 300, toolConfig: { width: 100, items: [ { text:'Settings', iconCls:'settings', handler: me.onSettings, scope: me }, '-', { text:'Logout', iconCls:'logout', handler: me.onLogout, scope: me } ] } }); }, getTaskbarConfig: function () { var ret = this.callParent(); return Ext.apply(ret, { quickStart: [ { name: 'Accordion Window', iconCls: 'accordion', module: 'acc-win' }, { name: 'Grid Window', iconCls: 'icon-grid', module: 'grid-win' } ], trayItems: [ { xtype: 'trayclock', flex: 1 } ] }); }, onLogout: function () { Ext.Msg.confirm('Logout', 'Are you sure you want to logout?'); }, onSettings: function () { var dlg = new MyDesktop.Settings({ desktop: this.desktop }); dlg.show(); } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.BogusMenuModule', { extend: 'MyDesktop.BogusModule', init : function() { this.launcher = { text: 'More items', iconCls: 'bogus', handler: function() { return false; }, menu: { items: [] } }; for (var i = 0; i < 5; ++i) { this.launcher.menu.items.push({ text: 'Window '+(++windowIndex), iconCls:'bogus', handler : this.createWindow, scope: this, windowId: windowIndex }); } } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.GridWindow', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.data.ArrayStore', 'Ext.util.Format', 'Ext.grid.Panel', 'Ext.grid.RowNumberer' ], id:'grid-win', init : function(){ this.launcher = { text: 'Grid Window', iconCls:'icon-grid' }; }, createWindow : function(){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('grid-win'); if(!win){ win = desktop.createWindow({ id: 'grid-win', title:'Grid Window', width:740, height:480, iconCls: 'icon-grid', animCollapse:false, constrainHeader:true, layout: 'fit', items: [ { border: false, xtype: 'grid', store: new Ext.data.ArrayStore({ fields: [ { name: 'company' }, { name: 'price', type: 'float' }, { name: 'change', type: 'float' }, { name: 'pctChange', type: 'float' } ], data: MyDesktop.GridWindow.getDummyData() }), columns: [ new Ext.grid.RowNumberer(), { text: "Company", flex: 1, sortable: true, dataIndex: 'company' }, { text: "Price", width: 70, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price' }, { text: "Change", width: 70, sortable: true, dataIndex: 'change' }, { text: "% Change", width: 70, sortable: true, dataIndex: 'pctChange' } ] } ], tbar:[{ text:'Add Something', tooltip:'Add a new row', iconCls:'add' }, '-', { text:'Options', tooltip:'Modify options', iconCls:'option' },'-',{ text:'Remove Something', tooltip:'Remove the selected item', iconCls:'remove' }] }); } return win; }, statics: { getDummyData: function () { return [ ['3m Co',71.72,0.02,0.03,'9/1 12:00am'], ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'], ['American Express Company',52.55,0.01,0.02,'9/1 12:00am'], ['American International Group, Inc.',64.13,0.31,0.49,'9/1 12:00am'], ['AT&T Inc.',31.61,-0.48,-1.54,'9/1 12:00am'], ['Caterpillar Inc.',67.27,0.92,1.39,'9/1 12:00am'], ['Citigroup, Inc.',49.37,0.02,0.04,'9/1 12:00am'], ['Exxon Mobil Corp',68.1,-0.43,-0.64,'9/1 12:00am'], ['General Electric Company',34.14,-0.08,-0.23,'9/1 12:00am'], ['General Motors Corporation',30.27,1.09,3.74,'9/1 12:00am'], ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'], ['Honeywell Intl Inc',38.77,0.05,0.13,'9/1 12:00am'], ['Intel Corporation',19.88,0.31,1.58,'9/1 12:00am'], ['Johnson & Johnson',64.72,0.06,0.09,'9/1 12:00am'], ['Merck & Co., Inc.',40.96,0.41,1.01,'9/1 12:00am'], ['Microsoft Corporation',25.84,0.14,0.54,'9/1 12:00am'], ['The Coca-Cola Company',45.07,0.26,0.58,'9/1 12:00am'], ['The Procter & Gamble Company',61.91,0.01,0.02,'9/1 12:00am'], ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am'], ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81,'9/1 12:00am'] ]; } } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ // From code originally written by David Davis (http://www.sencha.com/blog/html5-video-canvas-and-ext-js/) Ext.define('MyDesktop.VideoWindow', { extend: 'Ext.ux.desktop.Module', uses: [ 'Ext.ux.desktop.Video' ], id:'video', windowId: 'video-window', tipWidth: 160, tipHeight: 96, init : function(){ this.launcher = { text: 'About Ext JS', iconCls:'video' } }, createWindow : function(){ var me = this, desktop = me.app.getDesktop(), win = desktop.getWindow(me.windowId); if (!win) { win = desktop.createWindow({ id: me.windowId, title: 'About Ext JS', width: 740, height: 480, iconCls: 'video', animCollapse: false, border: false, layout: 'fit', items: [ { xtype: 'video', id: 'video-player', src: [ // browser will pick the format it likes most: { src: 'http://dev.sencha.com/desktopvideo.mp4', type: 'video/mp4' }, { src: 'http://dev.sencha.com/desktopvideo.ogv', type: 'video/ogg' }, { src: 'http://dev.sencha.com/desktopvideo.mov', type: 'video/quicktime' } ], autobuffer: true, autoplay : true, controls : true, /* default */ listeners: { afterrender: function(video) { me.videoEl = video.video.dom; if (video.supported) { me.tip = new Ext.tip.ToolTip({ anchor : 'bottom', dismissDelay : 0, height : me.tipHeight, width : me.tipWidth, renderTpl: [ '<canvas width="', me.tipWidth, '" height="', me.tipHeight, '">' ], renderSelectors: { body: 'canvas' }, listeners: { afterrender: me.onTooltipRender, show: me.renderPreview, scope: me } }); // tip } } } } ], listeners: { beforedestroy: function() { me.tip = me.ctx = me.videoEl = null; } } }); } if (me.tip) { me.tip.setTarget(win.taskButton.el); } return win; }, onTooltipRender: function (tip) { // get the canvas 2d context var el = tip.body.dom, me = this; me.ctx = el.getContext && el.getContext('2d'); }, renderPreview: function() { var me = this; if ((me.tip && !me.tip.isVisible()) || !me.videoEl) { return; } if (me.ctx) { try { me.ctx.drawImage(me.videoEl, 0, 0, me.tipWidth, me.tipHeight); } catch(e) {}; } // 20ms to keep the tooltip video smooth Ext.Function.defer(me.renderPreview, 20, me); } });
JavaScript
/*! * Ext JS Library 4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('MyDesktop.Notepad', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.form.field.HtmlEditor' //'Ext.form.field.TextArea' ], id:'notepad', init : function(){ this.launcher = { text: 'Notepad', iconCls:'notepad' } }, createWindow : function(){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('notepad'); if(!win){ win = desktop.createWindow({ id: 'notepad', title:'Notepad', width:600, height:400, iconCls: 'notepad', animCollapse:false, border: false, //defaultFocus: 'notepad-editor', EXTJSIV-1300 // IE has a bug where it will keep the iframe's background visible when the window // is set to visibility:hidden. Hiding the window via position offsets instead gets // around this bug. hideMode: 'offsets', layout: 'fit', items: [ { xtype: 'htmleditor', //xtype: 'textarea', id: 'notepad-editor', value: [ 'Some <b>rich</b> <font color="red">text</font> goes <u>here</u><br>', 'Give it a try!' ].join('') } ] }); } return win; } });
JavaScript
$.TE.plugin("bold",{ title:"标题", cmd:"bold", click:function(){ this.editor.pasteHTML("sdfdf"); }, bold:function(){ alert('sdfsdf'); }, noRight:function(e){ if(e.type=="click"){ alert('noright'); } }, init:function(){ }, event:"click mouseover mouseout", mouseover:function(e){ this.$btn.css("color","red"); }, mouseout:function(e){ this.$btn.css("color","#000") } });
JavaScript
function te_upload_interface() { //初始化参数 var _args = arguments, _fn = _args.callee, _data = ''; if( _args[0] == 'reg' ) { //注册回调 _data = _args[1]; _fn.curr = _data['callid']; _fn.data = _data; jQuery('#temaxsize').val(_data['maxsize']); } else if( _args[0] == 'get' ) { //获取配置 return _fn.data || false; } else if( _args[0] == 'call' ) { //处理回调与实例不一致 if( _args[1] != _fn.curr ) { alert( '上传出错,请不要同时打开多个上传弹窗' ); return false; } //上传成功 if( _args[2] == 'success' ) { _fn.data['callback']( _args[3] ); } //上传失败 else if( _args[2] == 'failure' ) { alert( '[上传失败]\n错误信息:'+_args[3] ); } //文件类型检测错误 else if( _args[2] == 'filetype' ) { alert( '[上传失败]\n错误信息:您上传的文件类型有误' ); } //处理状态改变 else if( _args[2] == 'change' ) { // TODO 更细致的回调实现,此处返回true自动提交 return true; } } } //用户选择文件时 function checkTypes(id){ //校验文件类型 var filename = document.getElementById( 'teupload' ).value, filetype = document.getElementById( 'tefiletype' ).value.split( ',' ); currtype = filename.split( '.' ).pop(), checktype = false; if( filetype[0] == '*' ) { checktype = true; } else { for(var i=0; i<filetype.length; i++) { if( currtype == filetype[i] ) { checktype = true; break; } } } if( !checktype ) { alert( '[上传失败]\n错误信息:您上传的文件类型有误' ); return false; } else { //校验通过,提交 jQuery('#'+id).submit() } }
JavaScript
// 系统自带插件 ( function ( $ ) { //全屏 $.TE.plugin( "fullscreen", { fullscreen:function(e){ var $btn = this.$btn, opt = this.editor.opt; if($btn.is("."+opt.cssname.fulled)){ //取消全屏 this.editor.$main.removeAttr("style"); this.editor.$bottom.find("div").show(); this.editor.resize(opt.width,opt.height); $("html,body").css("overflow","auto"); $btn.removeClass(opt.cssname.fulled); $(window).scrollTop(this.scrolltop); }else{ //全屏 this.scrolltop=$(window).scrollTop(); this.editor.$main.attr("style","z-index:900000;position:absolute;left:0;top:0px"); $(window).scrollTop(0); $("html,body").css("overflow","hidden");//隐藏滚蛋条 this.editor.$bottom.find("div").hide();//隐藏底部的调整大小控制块 this.editor.resize($(window).width(),$(window).height()); $btn.addClass(opt.cssname.fulled); } } } ); //切换源码 $.TE.plugin( "source", { source:function(e){ var $btn = this.$btn, $area = this.editor.$area, $frame = this.editor.$frame, opt = this.editor.opt, _self = this; if($btn.is("."+opt.cssname.sourceMode)){ //切换到可视化 _self.editor.core.updateFrame(); $area.hide(); $frame.show(); $btn.removeClass(opt.cssname.sourceMode); }else{ //切换到源码 _self.editor.core.updateTextArea(); $area.show(); $frame.hide(); $btn.addClass(opt.cssname.sourceMode); } setTimeout(function(){_self.editor.refreshBtn()},100); } } ); //剪切 $.TE.plugin( 'cut', { click: function() { if( $.browser.mozilla ) { alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+X快捷键完成操作。'); } else { this.exec(); } } }); //复制 $.TE.plugin( 'copy', { click: function() { if( $.browser.mozilla ) { alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+C快捷键完成操作。'); } else { this.exec(); } } }); //粘贴 $.TE.plugin( 'paste', { click: function() { if( $.browser.mozilla ) { alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+V快捷键完成操作。'); } else { this.exec(); } } }); //创建链接 $.TE.plugin( "link", { click:function(e){ var _self = this; var $html = $( '<div class="te_dialog_link Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">创建链接</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">链接地址:</span>'+ ' <div class="Lfll">'+ ' <input id="te_dialog_url" name="" type="text" class="Lfll input1" />'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); if( _self.isie6() ) { window.selectionCache = [ /* 暂存选区对象 */ _self.editor.doc.selection.createRange(), /* 选区html内容 */ _self.editor.doc.selection.createRange().htmlText, /* 选区文本用来计算差值 */ _self.editor.doc.selection.createRange().text ]; } this.createDialog({ body:$html, ok:function(){ _self.value=$html.find("#te_dialog_url").val(); if( _self.isie6() ) { var _sCache = window.selectionCache, str1 = '<a href="'+_self.value+'">'+_sCache[1]+'</a>', str2 = '<a href="'+_self.value+'">'+_sCache[2]+'</a>'; _sCache[0].pasteHTML( str1 ); _sCache[0].moveStart( 'character', -_self.strlen( str2 ) + ( str2.length - _sCache[2].length ) ); _sCache[0].moveEnd( 'character', -0 ); _sCache[0].select(); //置空暂存对象 window.selectionCache = _sCache = null; } else { _self.exec(); } _self.hideDialog(); } }); }, strlen : function ( str ) { return window.ActiveXObject && str.indexOf("\n") != -1 ? str.replace(/\r?\n/g, "_").length : str.length; }, isie6 : function () { return $.browser.msie && $.browser.version == '6.0' ? true : false; } } ); $.TE.plugin( 'print', { click: function(e) { var _win = this.editor.core.$frame[0].contentWindow; if($.browser.msie) { this.exec(); } else if(_win.print) { _win.print(); } else { alert('您的系统不支持打印接口'); } } } ); $.TE.plugin( 'pagebreak', { exec: function() { var _self = this; _self.editor.pasteHTML('<div style="page-break-after: always;zoom:1; height:0px; clear:both; display:block; overflow:hidden; border-top:2px dotted #CCC;">&nbsp;</div><p>&nbsp;</p>'); } } ); $.TE.plugin( 'pastetext', { exec: function() { var _self = this, _html = ''; clipData = window.clipboardData ? window.clipboardData.getData('text') : false; if( clipData ) { _self.editor.pasteHTML( clipData.replace( /\r\n/g, '<br />' ) ); } else { _html = $( '<div class="te_dialog_pasteText">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">贴粘文本</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="pasteText">'+ ' <span class="tips Lmt5">请使用键盘快捷键(Ctrl/Cmd+V)把内容粘贴到下面的方框里。</span>'+ ' <textarea id="pasteText" name="" class="tarea1 Lmt5" rows="10" cols="30"></textarea>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); this.createDialog({ body : _html, ok : function(){ _self.editor.pasteHTML(_html.find('#pasteText').val().replace(/\n/g, '<br />')); _self.hideDialog(); } }); } } } ); $.TE.plugin( 'table', { exec : function (e) { var _self = this, _html = ''; _html = $( '<div class="te_dialog_table">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入表格</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="insertTable">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">行数:</span>'+ ' <input type="text" id="te_tab_rows" class="input1 Lfll" value="3" />'+ ' <span class="ltext Lfll">列数:</span>'+ ' <input type="text" id="te_tab_cols" class="input1 Lfll" value="2" />'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">宽度:</span>'+ ' <input type="text" id="te_tab_width" class="input1 Lfll" value="500" />'+ ' <span class="ltext Lfll">高度:</span>'+ ' <input type="text" id="te_tab_height" class="input1 Lfll" />'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">边框:</span>'+ ' <input type="text" id="te_tab_border" class="input1 Lfll" value="1" />'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); this.createDialog({ body : _html, ok : function () { //获取参数 var rows = parseInt(_html.find('#te_tab_rows').val()), cols = parseInt(_html.find('#te_tab_cols').val()), width = parseInt(_html.find('#te_tab_width').val()), height = parseInt(_html.find('#te_tab_height').val()), border = parseInt(_html.find('#te_tab_border').val()), tab_html = '<table width="'+width+'" border="'+border+'"'; if(height) tab_html += ' height="'+height+'"'; tab_html += '>'; for(var i=0; i<rows; i++) { tab_html += '<tr>'; for(var j=0; j<cols; j++) { tab_html += '<td>&nbsp;</td>'; } tab_html += '</tr>'; } tab_html += '</table>'; _self.editor.pasteHTML( tab_html ); _self.hideDialog(); } }); } } ); $.TE.plugin( 'blockquote', { exec : function () { var _self = this, _doc = _self.editor.doc, elem = '', //当前对象 isquote = false, //是否已被引用 node = '', child = false; //找到的引用对象 //取得当前对象 node = elem = this.getElement(); //判断是否已被引用 while( node !== _doc.body ) { if( node.nodeName.toLowerCase() == 'blockquote' ){ isquote = true; break; } node = node.parentNode; } if( isquote ) { //如果存在引用,则清理 if( node === _doc.body ) { node.innerHTML = elem.parentNode.innerHTML; } else { while (child = node.firstChild) { node.parentNode.insertBefore(child, node); } node.parentNode.removeChild(node); } } else { //不存在引用,创建引用 if( $.browser.msie ) { if( elem === _doc.body ) { elem.innerHTML = '<blockquote>' + elem.innerHTML + '</blockquote>'; } else { elem.outerHTML = '<blockquote>' + elem.outerHTML + '</blockquote>'; } } else { _doc.execCommand( 'formatblock', false, '<blockquote>' ) } } }, getElement : function () { var ret = false; if( $.browser.msie ) { ret = this.editor.doc.selection.createRange().parentElement(); } else { ret = this.editor.$frame.get( 0 ).contentWindow.getSelection().getRangeAt( 0 ).startContainer; } return ret; } } ); $.TE.plugin( 'image', { upid : 'te_image_upload', uptype : [ 'jpg', 'jpeg', 'gif', 'png', 'bmp' ], //文件大小 maxsize : 1024*1024*1024*2, // 2MB exec : function() { var _self = this, //上传地址 updir = _self.editor.opt.uploadURL, //传给上传页的参数 parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date()); if(updir && updir!='about:blank'){ if( updir.indexOf('?') > -1 ) { updir += '&' + parame; } else { updir += '?' + parame; } //弹出窗内容 var $html = $( '<div class="te_dialog_image">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="#" class="cstyle">插入图片</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="insertimage Lmt20 Lpb10">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">图片地址:</span>'+ ' <div class="Lfll Lovh">'+ ' <input type="text" id="te_image_url" class="imageurl input1 Lfll Lmr5" />'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">上传图片:</span>'+ ' <div class="Lfll Lovh">'+ ' <form id="form_img" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+ ' <div class="filebox">'+ ' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_img\');" class="upinput" type="file" hidefocus="true" />'+ ' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+ ' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+ ' <span class="upbtn">上传</span>'+ ' </div>'+ ' </form>'+ ' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">图片宽度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_image_width" name="" type="text" class="input2" />'+ ' </div>'+ ' <span class="ltext Lfll">图片高度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_image_height" name="" type="text" class="input2" />'+ ' </div>'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ), _upcall = function(path) { //获取上传的值 $html.find( '#te_image_url' ).val(path); // 刷新iframe上传页 //var _url = $html.find( 'iframe' ).attr( 'src' ); //_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) ); $html.find( 'iframe' ).attr( 'src', 'about:blank' ); } //注册通信 te_upload_interface( 'reg', { 'callid' : this.upid+this.editor.guid, 'filetype': this.uptype, 'maxsize' : this.maxsize, 'callback': _upcall } ); //创建对话框 this.createDialog( { body : $html, ok : function() { var _src = $html.find('#te_image_url').val(), _width = parseInt($html.find('#te_image_width').val()), _height = parseInt($html.find('#te_image_height').val()); _src = _APP+_src; var _insertHTML = '<img src="'+(_src||'http://www.baidu.com/img/baidu_sylogo1.gif')+'" '; if( _width ) _insertHTML += 'width="'+_width+'" '; if( _height ) _insertHTML += 'height="'+_height+'" '; _insertHTML += '/>'; _self.editor.pasteHTML( _insertHTML ); _self.hideDialog(); } } ); }else{ alert('请配置上传处理路径!'); } } } ); $.TE.plugin( 'flash', { upid : 'te_flash_upload', uptype : [ 'swf' ], //文件大小 maxsize : 1024*1024*1024*2, // 2MB exec : function() { var _self = this, //上传地址 updir = _self.editor.opt.uploadURL, //传给上传页的参数 parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date()); if(updir && updir!='about:blank'){ if( updir.indexOf('?') > -1 ) { updir += '&' + parame; } else { updir += '?' + parame; } //弹出窗内容 var $html = $( '<div class="te_dialog_flash">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入flash动画</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="insertflash Lmt20 Lpb10">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">flash地址:</span>'+ ' <div class="Lfll Lovh">'+ ' <input id="te_flash_url" type="text" class="imageurl input1 Lfll Lmr5" />'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">上传flash:</span>'+ ' <div class="Lfll Lovh">'+ ' <form id="form_swf" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+ ' <div class="filebox">'+ ' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_swf\');" class="upinput" type="file" hidefocus="true" />'+ ' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+ ' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+ ' <span class="upbtn">上传</span>'+ ' </div>'+ ' </form>'+ ' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">宽度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_flash_width" name="" type="text" class="input2" value="200" />'+ ' </div>'+ ' <span class="ltext Lfll">高度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_flash_height" name="" type="text" class="input2" value="60" />'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">&nbsp;</span>'+ ' <div class="Lfll">'+ ' <input id="te_flash_wmode" name="" type="checkbox" class="input3" />'+ ' <label for="te_flash_wmode" class="labeltext">开启背景透明</label>'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ), _upcall = function(path) { //获取上传的值 $html.find( '#te_flash_url' ).val(path); // 刷新iframe上传页 //var _url = $html.find( 'iframe' ).attr( 'src' ); //_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) ); $html.find( 'iframe' ).attr( 'src', 'about:blank' ); } //注册通信 te_upload_interface( 'reg', { 'callid' : this.upid+this.editor.guid, 'filetype': this.uptype, 'maxsize' : this.maxsize, 'callback': _upcall } ); //创建对话框 this.createDialog( { body : $html, ok : function() { var _src = $html.find('#te_flash_url').val(), _width = parseInt($html.find('#te_flash_width').val()), _height = parseInt($html.find('#te_flash_height').val()); _wmode = !!$html.find('#te_flash_wmode').attr('checked'); if( _src == '' ) { alert('请输入flash地址,或者从本地选择文件上传'); return true; } if( isNaN(_width) || isNaN(_height) ) { alert('请输入宽高'); return true; } _src = _APP+_src; var _data = "{'src':'"+_src+"','width':'"+_width+"','height':'"+_height+"','wmode':"+(_wmode)+"}"; var _insertHTML = '<img src="'+$.TE.basePath()+'skins/'+_self.editor.opt.skins+'/img/spacer.gif" class="_flash_position" style="'; if( _width ) _insertHTML += 'width:'+_width+'px;'; if( _height ) _insertHTML += 'height:'+_height+'px;'; _insertHTML += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:'+_height+'px;" '; _insertHTML += '_data="'+_data+'"'; _insertHTML += ' alt="flash占位符" />'; _self.editor.pasteHTML( _insertHTML ); _self.hideDialog(); } } ) }else{ alert('请配置上传处理路径!'); } } } ); $.TE.plugin( 'face', { exec: function() { var _self = this, //表情路径 _fp = _self.editor.opt.face_path, //弹出窗同容 $html = $( '<div class="te_dialog_face Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入表情</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="insertFace" style="background-image:url('+$.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'.gif'+');">'+ '<span face_num="0">&nbsp;</span>'+ '<span face_num="1">&nbsp;</span>'+ '<span face_num="2">&nbsp;</span>'+ '<span face_num="3">&nbsp;</span>'+ '<span face_num="4">&nbsp;</span>'+ '<span face_num="5">&nbsp;</span>'+ '<span face_num="6">&nbsp;</span>'+ '<span face_num="7">&nbsp;</span>'+ '<span face_num="8">&nbsp;</span>'+ '<span face_num="9">&nbsp;</span>'+ '<span face_num="10">&nbsp;</span>'+ '<span face_num="11">&nbsp;</span>'+ '<span face_num="12">&nbsp;</span>'+ '<span face_num="13">&nbsp;</span>'+ '<span face_num="14">&nbsp;</span>'+ '<span face_num="15">&nbsp;</span>'+ '<span face_num="16">&nbsp;</span>'+ '<span face_num="17">&nbsp;</span>'+ '<span face_num="18">&nbsp;</span>'+ '<span face_num="19">&nbsp;</span>'+ '<span face_num="20">&nbsp;</span>'+ '<span face_num="21">&nbsp;</span>'+ '<span face_num="22">&nbsp;</span>'+ '<span face_num="23">&nbsp;</span>'+ '<span face_num="24">&nbsp;</span>'+ '<span face_num="25">&nbsp;</span>'+ '<span face_num="26">&nbsp;</span>'+ '<span face_num="27">&nbsp;</span>'+ '<span face_num="28">&nbsp;</span>'+ '<span face_num="29">&nbsp;</span>'+ '<span face_num="30">&nbsp;</span>'+ '<span face_num="31">&nbsp;</span>'+ '<span face_num="32">&nbsp;</span>'+ '<span face_num="33">&nbsp;</span>'+ '<span face_num="34">&nbsp;</span>'+ '<span face_num="35">&nbsp;</span>'+ '<span face_num="36">&nbsp;</span>'+ '<span face_num="37">&nbsp;</span>'+ '<span face_num="38">&nbsp;</span>'+ '<span face_num="39">&nbsp;</span>'+ '<span face_num="40">&nbsp;</span>'+ '<span face_num="41">&nbsp;</span>'+ '<span face_num="42">&nbsp;</span>'+ '<span face_num="43">&nbsp;</span>'+ '<span face_num="44">&nbsp;</span>'+ '<span face_num="45">&nbsp;</span>'+ '<span face_num="46">&nbsp;</span>'+ '<span face_num="47">&nbsp;</span>'+ '<span face_num="48">&nbsp;</span>'+ '<span face_num="49">&nbsp;</span>'+ '<span face_num="50">&nbsp;</span>'+ '<span face_num="51">&nbsp;</span>'+ '<span face_num="52">&nbsp;</span>'+ '<span face_num="53">&nbsp;</span>'+ '<span face_num="54">&nbsp;</span>'+ '<span face_num="55">&nbsp;</span>'+ '<span face_num="56">&nbsp;</span>'+ '<span face_num="57">&nbsp;</span>'+ '<span face_num="58">&nbsp;</span>'+ '<span face_num="59">&nbsp;</span>'+ '<span face_num="60">&nbsp;</span>'+ '<span face_num="61">&nbsp;</span>'+ '<span face_num="62">&nbsp;</span>'+ '<span face_num="63">&nbsp;</span>'+ '<span face_num="64">&nbsp;</span>'+ '<span face_num="65">&nbsp;</span>'+ '<span face_num="66">&nbsp;</span>'+ '<span face_num="67">&nbsp;</span>'+ '<span face_num="68">&nbsp;</span>'+ '<span face_num="69">&nbsp;</span>'+ '<span face_num="70">&nbsp;</span>'+ '<span face_num="71">&nbsp;</span>'+ '<span face_num="72">&nbsp;</span>'+ '<span face_num="73">&nbsp;</span>'+ '<span face_num="74">&nbsp;</span>'+ '<span face_num="75">&nbsp;</span>'+ '<span face_num="76">&nbsp;</span>'+ '<span face_num="77">&nbsp;</span>'+ '<span face_num="78">&nbsp;</span>'+ '<span face_num="79">&nbsp;</span>'+ '<span face_num="80">&nbsp;</span>'+ '<span face_num="81">&nbsp;</span>'+ '<span face_num="82">&nbsp;</span>'+ '<span face_num="83">&nbsp;</span>'+ '<span face_num="84">&nbsp;</span>'+ '<span face_num="85">&nbsp;</span>'+ '<span face_num="86">&nbsp;</span>'+ '<span face_num="87">&nbsp;</span>'+ '<span face_num="88">&nbsp;</span>'+ '<span face_num="89">&nbsp;</span>'+ '<span face_num="90">&nbsp;</span>'+ '<span face_num="91">&nbsp;</span>'+ '<span face_num="92">&nbsp;</span>'+ '<span face_num="93">&nbsp;</span>'+ '<span face_num="94">&nbsp;</span>'+ '<span face_num="95">&nbsp;</span>'+ '<span face_num="96">&nbsp;</span>'+ '<span face_num="97">&nbsp;</span>'+ '<span face_num="98">&nbsp;</span>'+ '<span face_num="99">&nbsp;</span>'+ '<span face_num="100">&nbsp;</span>'+ '<span face_num="101">&nbsp;</span>'+ '<span face_num="102">&nbsp;</span>'+ '<span face_num="103">&nbsp;</span>'+ '<span face_num="104">&nbsp;</span>'+ '</div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); $html.find('.insertFace span').click(function( e ) { var _url = $.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'_'+$( this ).attr( 'face_num' )+'.gif', _insertHtml = '<img src="'+_url+'" />'; _self.editor.pasteHTML( _insertHtml ); _self.hideDialog(); }); this.createDialog( { body : $html } ); } } ); $.TE.plugin( 'code', { exec: function() { var _self = this, $html = $( '<div class="te_dialog_code Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入代码</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="Lmt10 Lml10">'+ ' <span>选择语言:</span>'+ ' <select id="langType" name="">'+ ' <option value="None">其它类型</option>'+ ' <option value="PHP">PHP</option>'+ ' <option value="HTML">HTML</option>'+ ' <option value="JS">JS</option>'+ ' <option value="CSS">CSS</option>'+ ' <option value="SQL">SQL</option>'+ ' <option value="C#">C#</option>'+ ' <option value="JAVA">JAVA</option>'+ ' <option value="VBS">VBS</option>'+ ' <option value="VB">VB</option>'+ ' <option value="XML">XML</option>'+ ' </select>'+ ' </div>'+ ' <textarea id="insertCode" name="" rows="10" class="tarea1 Lmt10" cols="30"></textarea>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); this.createDialog({ body : $html, ok : function(){ var _code = $html.find('#insertCode').val(), _type = $html.find('#langType').val(), _html = ''; _code = _code.replace( /</g, '&lt;' ); _code = _code.replace( />/g, '&gt;' ); _code = _code.split('\n'); _html += '<pre style="overflow-x:auto; padding:10px; color:blue; border:1px dotted #2BC1FF; background-color:#EEFAFF;" _syntax="'+_type+'">' _html += '语言类型:'+_type; _html += '<ol style="list-stype-type:decimal;">'; for(var i=0; i<_code.length; i++) { _html += '<li>'+_code[i].replace( /^(\t+)/g, function( $1 ) {return $1.replace(/\t/g, ' ');} );+'</li>'; } _html += '</ol></pre><p>&nbsp;</p>'; _self.editor.pasteHTML( _html ); _self.hideDialog(); } }); } } ); $.TE.plugin( 'style', { click: function() { var _self = this, $html = $( '<div class="te_dialog_style Lovh">'+ ' <div class="centbox">'+ ' <h1 title="设置当前内容为一级标题"><a href="###">一级标题</a></h1>'+ ' <h2 title="设置当前内容为二级标题"><a href="###">二级标题</a></h2>'+ ' <h3 title="设置当前内容为三级标题"><a href="###">三级标题</a></h3>'+ ' <h4 title="设置当前内容为四级标题"><a href="###">四级标题</a></h4>'+ ' <h5 title="设置当前内容为五级标题"><a href="###">五级标题</a></h5>'+ ' <h6 title="设置当前内容为六级标题"><a href="###">六级标题</a></h6>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.nodeName; _self.value= _value; _self.exec(); //_self.hideDialog(); }; $html.find( '>.centbox>*' ).click( _call ); this.createDialog( { body: $html } ); }, exec: function() { var _self = this, _html = '<'+_self.value+'>'+_self.editor.selectedHTML()+'</'+_self.value+'>'; _self.editor.pasteHTML( _html ); } } ); $.TE.plugin( 'font', { click: function() { var _self = this; $html = $( '<div class="te_dialog_font Lovh">'+ ' <div class="centbox">'+ ' <div><a href="###" style="font-family:\'宋体\',\'SimSun\'">宋体</a></div>'+ ' <div><a href="###" style="font-family:\'楷体\',\'楷体_GB2312\',\'SimKai\'">楷体</a></div>'+ ' <div><a href="###" style="font-family:\'隶书\',\'SimLi\'">隶书</a></div>'+ ' <div><a href="###" style="font-family:\'黑体\',\'SimHei\'">黑体</a></div>'+ ' <div><a href="###" style="font-family:\'微软雅黑\'">微软雅黑</a></div>'+ ' <span>------</span>'+ ' <div><a href="###" style="font-family:arial,helvetica,sans-serif;">Arial</a></div>'+ ' <div><a href="###" style="font-family:comic sans ms,cursive;">Comic Sans Ms</a></div>'+ ' <div><a href="###" style="font-family:courier new,courier,monospace;">Courier New</a></div>'+ ' <div><a href="###" style="font-family:georgia,serif;">Georgia</a></div>'+ ' <div><a href="###" style="font-family:lucida sans unicode,lucida grande,sans-serif;">Lucida Sans Unicode</a></div>'+ ' <div><a href="###" style="font-family:tahoma,geneva,sans-serif;">Tahoma</a></div>'+ ' <div><a href="###" style="font-family:times new roman,times,serif;">Times New Roman</a></div>'+ ' <div><a href="###" style="font-family:trebuchet ms,helvetica,sans-serif;">Trebuchet Ms</a></div>'+ ' <div><a href="###" style="font-family:verdana,geneva,sans-serif;">Verdana</a></div>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.fontFamily; _self.value= _value; _self.exec(); }; $html.find( '>.centbox a' ).click( _call ); this.createDialog( { body: $html } ); } } ); $.TE.plugin( 'fontsize', { click: function() { var _self = this, $html = $( '<div class="te_dialog_fontsize Lovh">'+ ' <div class="centbox">'+ ' <div><a href="#" style="font-size:10px">10</a></div>'+ ' <div><a href="#" style="font-size:12px">12</a></div>'+ ' <div><a href="#" style="font-size:14px">14</a></div>'+ ' <div><a href="#" style="font-size:16px">16</a></div>'+ ' <div><a href="#" style="font-size:18px">18</a></div>'+ ' <div><a href="#" style="font-size:20px">20</a></div>'+ ' <div><a href="#" style="font-size:22px">22</a></div>'+ ' <div><a href="#" style="font-size:24px">24</a></div>'+ ' <div><a href="#" style="font-size:36px">36</a></div>'+ ' <div><a href="#" style="font-size:48px">48</a></div>'+ ' <div><a href="#" style="font-size:60px">60</a></div>'+ ' <div><a href="#" style="font-size:72px">72</a></div>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.fontSize; _self.value= _value; _self.exec(); }; $html.find( '>.centbox a' ).click( _call ); this.createDialog( { body: $html } ); }, exec: function() { var _self = this, _html = '<span style="font-size:'+_self.value+'">'+_self.editor.selectedText()+'</span>'; _self.editor.pasteHTML( _html ); } } ); $.TE.plugin( 'fontcolor', { click: function() { var _self = this, $html = $( '<div class="te_dialog_fontcolor Lovh">'+ ' <div class="colorsel">'+ ' <!--第一列-->'+ ' <a href="###" style="background-color:#FF0000">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFA900">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF00">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#00FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#00AAFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#0055FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#5500FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#AA00FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FF007F">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFFF">&nbsp;</a>'+ ' <!--第二列-->'+ ' <a href="###" style="background-color:#FFE5E5">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFF2D9">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#EEFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFE0">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9F2FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9E6FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#F2D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFD9ED">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D9D9">&nbsp;</a>'+ ' <!--第三列-->'+ ' <a href="###" style="background-color:#E68A8A">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6C78A">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF99">&nbsp;</a>'+ ' <a href="###" style="background-color:#BFE673">&nbsp;</a>'+ ' <a href="###" style="background-color:#99EEA0">&nbsp;</a>'+ ' <a href="###" style="background-color:#A1E6E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#99DDFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#8AA8E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#998AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#C78AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#E68AB9">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第四列-->'+ ' <a href="###" style="background-color:#CC5252">&nbsp;</a>'+ ' <a href="###" style="background-color:#CCA352">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D957">&nbsp;</a>'+ ' <a href="###" style="background-color:#A7CC39">&nbsp;</a>'+ ' <a href="###" style="background-color:#57CE6D">&nbsp;</a>'+ ' <a href="###" style="background-color:#52CCCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#52A3CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#527ACC">&nbsp;</a>'+ ' <a href="###" style="background-color:#6652CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#A352CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#CC5291">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第五列-->'+ ' <a href="###" style="background-color:#991F1F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99701F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99991F">&nbsp;</a>'+ ' <a href="###" style="background-color:#59800D">&nbsp;</a>'+ ' <a href="###" style="background-color:#0F9932">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F9999">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F7099">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F4799">&nbsp;</a>'+ ' <a href="###" style="background-color:#471F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#701F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#991F5E">&nbsp;</a>'+ ' <a href="###" style="background-color:#404040">&nbsp;</a>'+ ' <!--第六列-->'+ ' <a href="###" style="background-color:#660000">&nbsp;</a>'+ ' <a href="###" style="background-color:#664B14">&nbsp;</a>'+ ' <a href="###" style="background-color:#666600">&nbsp;</a>'+ ' <a href="###" style="background-color:#3B5900">&nbsp;</a>'+ ' <a href="###" style="background-color:#005916">&nbsp;</a>'+ ' <a href="###" style="background-color:#146666">&nbsp;</a>'+ ' <a href="###" style="background-color:#144B66">&nbsp;</a>'+ ' <a href="###" style="background-color:#143066">&nbsp;</a>'+ ' <a href="###" style="background-color:#220066">&nbsp;</a>'+ ' <a href="###" style="background-color:#301466">&nbsp;</a>'+ ' <a href="###" style="background-color:#66143F">&nbsp;</a>'+ ' <a href="###" style="background-color:#000000">&nbsp;</a>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.backgroundColor; _self.value= _value; _self.exec(); }; $html.find( '>.colorsel a' ).click( _call ); this.createDialog( { body: $html } ); } } ); $.TE.plugin( 'backcolor', { click: function() { var _self = this, $html = $( '<div class="te_dialog_fontcolor Lovh">'+ ' <div class="colorsel">'+ ' <!--第一列-->'+ ' <a href="###" style="background-color:#FF0000">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFA900">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF00">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#00FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#00AAFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#0055FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#5500FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#AA00FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FF007F">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFFF">&nbsp;</a>'+ ' <!--第二列-->'+ ' <a href="###" style="background-color:#FFE5E5">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFF2D9">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#EEFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFE0">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9F2FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9E6FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#F2D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFD9ED">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D9D9">&nbsp;</a>'+ ' <!--第三列-->'+ ' <a href="###" style="background-color:#E68A8A">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6C78A">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF99">&nbsp;</a>'+ ' <a href="###" style="background-color:#BFE673">&nbsp;</a>'+ ' <a href="###" style="background-color:#99EEA0">&nbsp;</a>'+ ' <a href="###" style="background-color:#A1E6E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#99DDFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#8AA8E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#998AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#C78AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#E68AB9">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第四列-->'+ ' <a href="###" style="background-color:#CC5252">&nbsp;</a>'+ ' <a href="###" style="background-color:#CCA352">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D957">&nbsp;</a>'+ ' <a href="###" style="background-color:#A7CC39">&nbsp;</a>'+ ' <a href="###" style="background-color:#57CE6D">&nbsp;</a>'+ ' <a href="###" style="background-color:#52CCCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#52A3CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#527ACC">&nbsp;</a>'+ ' <a href="###" style="background-color:#6652CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#A352CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#CC5291">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第五列-->'+ ' <a href="###" style="background-color:#991F1F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99701F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99991F">&nbsp;</a>'+ ' <a href="###" style="background-color:#59800D">&nbsp;</a>'+ ' <a href="###" style="background-color:#0F9932">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F9999">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F7099">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F4799">&nbsp;</a>'+ ' <a href="###" style="background-color:#471F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#701F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#991F5E">&nbsp;</a>'+ ' <a href="###" style="background-color:#404040">&nbsp;</a>'+ ' <!--第六列-->'+ ' <a href="###" style="background-color:#660000">&nbsp;</a>'+ ' <a href="###" style="background-color:#664B14">&nbsp;</a>'+ ' <a href="###" style="background-color:#666600">&nbsp;</a>'+ ' <a href="###" style="background-color:#3B5900">&nbsp;</a>'+ ' <a href="###" style="background-color:#005916">&nbsp;</a>'+ ' <a href="###" style="background-color:#146666">&nbsp;</a>'+ ' <a href="###" style="background-color:#144B66">&nbsp;</a>'+ ' <a href="###" style="background-color:#143066">&nbsp;</a>'+ ' <a href="###" style="background-color:#220066">&nbsp;</a>'+ ' <a href="###" style="background-color:#301466">&nbsp;</a>'+ ' <a href="###" style="background-color:#66143F">&nbsp;</a>'+ ' <a href="###" style="background-color:#000000">&nbsp;</a>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.backgroundColor; _self.value= _value; _self.exec(); }; $html.find( '>.colorsel a' ).click( _call ); this.createDialog( { body: $html } ); } } ); $.TE.plugin( 'about', { 'click': function() { var _self = this, $html = $( '<div class="te_dialog_about Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">关于ThinkEditor</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="aboutcontent">'+ ' <p>ThinkPHP是一个免费开源的,快速、简单的面向对象的轻量级PHP开发框架,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业级应用开发而诞生的。拥有众多的优秀功能和特性,经历了三年多发展的同时,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,众多的典型案例确保可以稳定用于商业以及门户级的开发。</p>'+ ' <p>ThinkPHP借鉴了国外很多优秀的框架和模式,使用面向对象的开发结构和MVC模式,采用单一入口模式等,融合了Struts的Action思想和JSP的TagLib(标签库)、RoR的ORM映射和ActiveRecord模式,封装了CURD和一些常用操作,在项目配置、类库导入、模版引擎、查询语言、自动验证、视图模型、项目编译、缓存机制、SEO支持、分布式数据库、多数据库连接和切换、认证机制和扩展性方面均有独特的表现。</p>'+ ' <p>使用ThinkPHP,你可以更方便和快捷的开发和部署应用。当然不仅仅是企业级应用,任何PHP应用开发都可以从ThinkPHP的简单和快速的特性中受益。ThinkPHP本身具有很多的原创特性,并且倡导大道至简,开发由我的开发理念,用最少的代码完成更多的功能,宗旨就是让WEB应用开发更简单、更快速。为此ThinkPHP会不断吸收和融入更好的技术以保证其新鲜和活力,提供WEB应用开发的最佳实践!</p>'+ ' <p>ThinkPHP遵循Apache2开源许可协议发布,意味着你可以免费使用ThinkPHP,甚至允许把你基于ThinkPHP开发的应用开源或商业产品发布/销售。 </p>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="关闭" class="te_close" />'+ ' </div>'+ '</div>' ); _self.createDialog( { body: $html } ); } } ); //$.TE.plugin( 'eq', { // 'click': function() { // var _self = this, // $html = $( // '<div class="te_dialog_about Lovh">'+ // ' <div class="seltab">'+ // ' <div class="links Lovh">'+ // ' <a href="###" class="cstyle">关于ThinkEditor</a>'+ // ' </div>'+ // ' <div class="bdb">&nbsp;</div>'+ // ' </div>'+ // ' <div class="centbox">'+ // ' <div class="eqcontent">'+ // ' <label for="eq_name">名称</label>'+ // ' <input type="text" name="eq_name" id="eq_name"/></br>'+ // ' <label for="eq_name">值</label>'+ // ' <input type="text" name="eq_val" id="eq_val"/></br>'+ // ' <textarea name="eq_content" id="eq_content" cols="30" rows="2"></textarea>'+ // ' </div>'+ // ' </div>'+ // ' <div class="btnarea">'+ // ' <input type="button" value="确定" class="te_ok" />'+ // ' <input type="button" value="关闭" class="te_close" />'+ // ' </div>'+ // '</div>' // ); // // _self.createDialog({ // body: $html, // ok : function(){ // var _name = $html.find('#eq_name').val(), // _val = $html.find('#eq_val').val(), // _content = $html.find('#eq_content').val(), // _html = ''; // _html += '<eq name="' + _name +'" value="' + _val +'">'+ // _content + // '</eq>'; // _self.editor.pasteHTML( _html ); // _self.hideDialog(); // } // }); // // } //}); } )( jQuery );
JavaScript
(function ($) { var ie = $.browser.msie, iOS = /iphone|ipad|ipod/i.test(navigator.userAgent); $.TE = { version:'1.0', // 版本号 debug: 1, //调试开关 timeOut: 3000, //加载单个文件超时时间,单位为毫秒。 defaults: { //默认参数controls,noRigths,plugins,定义加载插件 controls: "source,|,undo,redo,|,cut,copy,paste,pastetext,selectAll,blockquote,|,image,flash,table,hr,pagebreak,face,code,|,link,unlink,|,print,fullscreen,|,eq,|,style,font,fontsize,|,fontcolor,backcolor,|,bold,italic,underline,strikethrough,unformat,|,leftalign,centeralign,rightalign,blockjustify,|,orderedlist,unorderedlist,indent,outdent,|,subscript,superscript", //noRights:"underline,strikethrough,superscript", width: 740, height: 500, skins: "default", resizeType: 2, face_path: ['qq_face', 'qq_face'], minHeight: 200, minWidth: 500, uploadURL: 'about:blank', theme: 'default' }, buttons: { //按钮属性 //eq: {title: '等于',cmd: 'bold'}, bold: { title: "加粗", cmd: "bold" }, pastetext: { title: "粘贴无格式", cmd: "bold" }, pastefromword: { title: "粘贴word格式", cmd: "bold" }, selectAll: { title: "全选", cmd: "selectall" }, blockquote: { title: "引用" }, find: { title: "查找", cmd: "bold" }, flash: { title: "插入flash", cmd: "bold" }, media: { title: "插入多媒体", cmd: "bold" }, table: { title: "插入表格" }, pagebreak: { title: "插入分页符" }, face: { title: "插入表情", cmd: "bold" }, code: { title: "插入源码", cmd: "bold" }, print: { title: "打印", cmd: "print" }, about: { title: "关于", cmd: "bold" }, fullscreen: { title: "全屏", cmd: "fullscreen" }, source: { title: "HTML代码", cmd: "source" }, undo: { title: "后退", cmd: "undo" }, redo: { title: "前进", cmd: "redo" }, cut: { title: "剪贴", cmd: "cut" }, copy: { title: "复制", cmd: "copy" }, paste: { title: "粘贴", cmd: "paste" }, hr: { title: "插入横线", cmd: "inserthorizontalrule" }, link: { title: "创建链接", cmd: "createlink" }, unlink: { title: "删除链接", cmd: "unlink" }, italic: { title: "斜体", cmd: "italic" }, underline: { title: "下划线", cmd: "underline" }, strikethrough: { title: "删除线", cmd: "strikethrough" }, unformat: { title: "清除格式", cmd: "removeformat" }, subscript: { title: "下标", cmd: "subscript" }, superscript: { title: "上标", cmd: "superscript" }, orderedlist: { title: "有序列表", cmd: "insertorderedlist" }, unorderedlist: { title: "无序列表", cmd: "insertunorderedlist" }, indent: { title: "增加缩进", cmd: "indent" }, outdent: { title: "减少缩进", cmd: "outdent" }, leftalign: { title: "左对齐", cmd: "justifyleft" }, centeralign: { title: "居中对齐", cmd: "justifycenter" }, rightalign: { title: "右对齐", cmd: "justifyright" }, blockjustify: { title: "两端对齐", cmd: "justifyfull" }, font: { title: "字体", cmd: "fontname", value: "微软雅黑" }, fontsize: { title: "字号", cmd: "fontsize", value: "4" }, style: { title: "段落标题", cmd: "formatblock", value: "" }, fontcolor: { title: "前景颜色", cmd: "forecolor", value: "#ff6600" }, backcolor: { title: "背景颜色", cmd: "hilitecolor", value: "#ff6600" }, image: { title: "插入图片", cmd: "insertimage", value: "" } }, defaultEvent: { event: "click mouseover mouseout", click: function (e) { this.exec(e); }, mouseover: function (e) { var opt = this.editor.opt; this.$btn.addClass(opt.cssname.mouseover); }, mouseout: function (e) { }, noRight: function (e) { }, init: function (e) { }, exec: function () { this.editor.restoreRange(); //执行命令 if ($.isFunction(this[this.cmd])) { this[this.cmd](); //如果有已当前cmd为名的方法,则执行 } else { this.editor.doc.execCommand(this.cmd, 0, this.value || null); } this.editor.focus(); this.editor.refreshBtn(); this.editor.hideDialog(); }, createDialog: function (v) { //创建对话框 var editor = this.editor, opt = editor.opt, $btn = this.$btn, _self = this; var defaults = { body: "", //对话框内容 closeBtn: opt.cssname.dialogCloseBtn, okBtn: opt.cssname.dialogOkBtn, ok: function () { //点击ok按钮后执行函数 }, setDialog: function ($dialog) { //设置对话框(位置) var y = $btn.offset().top + $btn.outerHeight(); var x = $btn.offset().left; $dialog.offset({ top: y, left: x }); } }; var options = $.extend(defaults, v); //初始化对话框 editor.$dialog.empty(); //加入内容 $body = $.type(options.body) == "string" ? $(options.body) : options.body; $dialog = $body.appendTo(editor.$dialog); $dialog.find("." + options.closeBtn).click(function () { _self.hideDialog(); }); $dialog.find("." + options.okBtn).click(options.ok); //设置对话框 editor.$dialog.show(); options.setDialog(editor.$dialog); }, hideDialog: function () { this.editor.hideDialog(); } //getEnable:function(){return false}, //disable:function(e){alert('disable')} }, plugin: function (name, v) { //新增或修改插件。 $.TE.buttons[name] = $.extend($.TE.buttons[name], v); }, config: function (name, value) { var _fn = arguments.callee; if (!_fn.conf) _fn.conf = {}; if (value) { _fn.conf[name] = value; return true; } else { return name == 'default' ? $.TE.defaults : _fn.conf[name]; } }, systemPlugins: ['system', 'upload_interface'], //系统自带插件 basePath: function () { var jsFile = "ThinkEditor.js"; var src = $("script[src$='" + jsFile + "']").attr("src"); return src.substr(0, src.length - jsFile.length); } }; $.fn.extend({ //调用插件 ThinkEditor: function (v) { //配置处理 var conf = '', temp = ''; conf = v ? $.extend($.TE.config(v.theme ? v.theme : 'default'), v) : $.TE.config('default'); v = conf; //配置处理完成 //载入皮肤 var skins = v.skins || $.TE.defaults.skins; //获得皮肤参数 var skinsDir = $.TE.basePath() + "skins/" + skins + "/", jsFile = "@" + skinsDir + "config.js", cssFile = "@" + skinsDir + "style.css"; var _self = this; //加载插件 if ($.defined(v.plugins)) { var myPlugins = $.type(v.plugins) == "string" ? [v.plugins] : v.plugins; var files = $.merge($.merge([], $.TE.systemPlugins), myPlugins); } else { var files = $.TE.systemPlugins; } $.each(files, function (i, v) { files[i] = v + ".js"; }) files.push(jsFile, cssFile); files.push("@" + skinsDir + "dialog/css/base.css"); files.push("@" + skinsDir + "dialog/css/te_dialog.css"); $.loadFile(files, function () { //设置css参数 v.cssname = $.extend({}, TECSS, v.cssname); //创建编辑器,存储对象 $(_self).each(function (idx, elem) { var data = $(elem).data("editorData"); if (!data) { data = new ThinkEditor(elem, v); $(elem).data("editorData", data); } }); }); } }); //编辑器对象。 function ThinkEditor(area, v) { //添加随机序列数防冲突 var _fn = arguments.callee; this.guid = !_fn.guid ? _fn.guid = 1 : _fn.guid += 1; //生成参数 var opt = this.opt = $.extend({}, $.TE.defaults, v); var _self = this; //结构:主层,工具层,分组层,按钮层,底部,dialog层 var $main = this.$main = $("<div></div>").addClass(opt.cssname.main), $toolbar_box = $('<div></div>').addClass(opt.cssname.toolbar_box).appendTo($main), $toolbar = this.$toolbar = $("<div></div>").addClass(opt.cssname.toolbar).appendTo($toolbar_box), /*$toolbar=this.$toolbar=$("<div></div>").addClass(opt.cssname.toolbar).appendTo($main),*/ $group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar), $bottom = this.$bottom = $("<div></div>").addClass(opt.cssname.bottom), $dialog = this.$dialog = $("<div></div>").addClass(opt.cssname.dialog), $area = $(area).hide(), $frame = $('<iframe frameborder="0"></iframe>'); opt.noRights = opt.noRights || ""; var noRights = opt.noRights.split(","); //调整结构 $main.insertBefore($area) .append($area); //加入frame $frame.appendTo($main); //加入bottom if (opt.resizeType != 0) { //拖动改变编辑器高度 $("<div></div>").addClass(opt.cssname.resizeCenter).mousedown(function (e) { var y = e.pageY, x = e.pageX, height = _self.$main.height(), width = _self.$main.width(); $(document).add(_self.doc).mousemove(function (e) { var mh = e.pageY - y; _self.resize(width, height + mh); }); $(document).add(_self.doc).mouseup(function (e) { $(document).add(_self.doc).unbind("mousemove"); $(document).add(_self.doc).unbind("mousemup"); }); }).appendTo($bottom); } if (opt.resizeType == 2) { //拖动改变编辑器高度和宽度 $("<div></div>").addClass(opt.cssname.resizeLeft).mousedown(function (e) { var y = e.pageY, x = e.pageX, height = _self.$main.height(), width = _self.$main.width(); $(document).add(_self.doc).mousemove(function (e) { var mh = e.pageY - y, mw = e.pageX - x; _self.resize(width + mw, height + mh); }); $(document).add(_self.doc).mouseup(function (e) { $(document).add(_self.doc).unbind("mousemove"); $(document).add(_self.doc).unbind("mousemup"); }); }).appendTo($bottom); } $bottom.appendTo($main); $dialog.appendTo($main); //循环按钮处理。 //TODO 默认参数处理 $.each(opt.controls.split(","), function (idx, bname) { var _fn = arguments.callee; if (_fn.count == undefined) { _fn.count = 0; } //处理分组 if (bname == "|") { //设定分组宽 if (_fn.count) { $toolbar.find('.' + opt.cssname.group + ':last').css('width', (opt.cssname.btnWidth * _fn.count + opt.cssname.lineWidth) + 'px'); _fn.count = 0; } //分组宽结束 $group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar); $("<div>&nbsp;</div>").addClass(opt.cssname.line).appendTo($group); } else { //更新统计数 _fn.count += 1; //获取按钮属性 var btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[bname]); //标记无权限 var noRightCss = "", noRightTitle = ""; if ($.inArray(bname, noRights) != -1) { noRightCss = " " + opt.cssname.noRight; noRightTitle = "(无权限)"; } $btn = $("<div></div>").addClass(opt.cssname.btn + " " + opt.cssname.btnpre + bname + noRightCss) .data("bname", bname) .attr("title", btn.title + noRightTitle) .appendTo($group) .bind(btn.event, function (e) { //不可用触发 if ($(this).is("." + opt.cssname.disable)) { if ($.isFunction(btn.disable)) btn.disable.call(btn, e); return false; } //判断权限和是否可用 if ($(this).is("." + opt.cssname.noRight)) { //点击时触发无权限说明 btn['noRight'].call(btn, e); return false; } if ($.isFunction(btn[e.type])) { //触发事件 btn[e.type].call(btn, e); //TODO 刷新按钮 } }); if ($.isFunction(btn.init)) btn.init.call(btn); //初始化 if (ie) $btn.attr("unselectable", "on"); btn.editor = _self; btn.$btn = $btn; } }); //调用核心 this.core = new editorCore($frame, $area); this.doc = this.core.doc; this.$frame = this.core.$frame; this.$area = this.core.$area; this.restoreRange = this.core.restoreRange; this.selectedHTML = function () { return this.core.selectedHTML(); } this.selectedText = function () { return this.core.selectedText(); } this.pasteHTML = function (v) { this.core.pasteHTML(v); } this.sourceMode = this.core.sourceMode; this.focus = this.core.focus; //监控变化 $(this.core.doc).click(function () { //隐藏对话框 _self.hideDialog(); }).bind("keyup mouseup", function () { _self.refreshBtn(); }) this.refreshBtn(); //调整大小 this.resize(opt.width, opt.height); //获取DOM层级 this.core.focus(); } //end ThinkEditor ThinkEditor.prototype.resize = function (w, h) { //最小高度和宽度 var opt = this.opt, h = h < opt.minHeight ? opt.minHeight : h, w = w < opt.minWidth ? opt.minWidth : w; this.$main.width(w).height(h); var height = h - (this.$toolbar.parent().outerHeight() + this.$bottom.height()); this.$frame.height(height).width("100%"); this.$area.height(height).width("100%"); }; //隐藏对话框 ThinkEditor.prototype.hideDialog = function () { var opt = this.opt; $("." + opt.cssname.dialog).hide(); }; //刷新按钮 ThinkEditor.prototype.refreshBtn = function () { var sourceMode = this.sourceMode(); // 标记状态。 var opt = this.opt; if (!iOS && $.browser.webkit && !this.focused) { this.$frame[0].contentWindow.focus(); window.focus(); this.focused = true; } var queryObj = this.doc; if (ie) queryObj = this.core.getRange(); //循环按钮 //TODO undo,redo等判断 this.$toolbar.find("." + opt.cssname.btn + ":not(." + opt.cssname.noRight + ")").each(function () { var enabled = true, btnName = $(this).data("bname"), btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[btnName]), command = btn.cmd; if (sourceMode && btnName != "source") { enabled = false; } else if ($.isFunction(btn.getEnable)) { enabled = btn.getEnable.call(btn); } else if ($.isFunction(btn[command])) { enabled = true; //如果命令为自定义命令,默认为可用 } else { if (!ie || btn.cmd != "inserthtml") { try { enabled = queryObj.queryCommandEnabled(command); $.debug(enabled.toString(), "命令:" + command); } catch (err) { enabled = false; } } //判断该功能是否有实现 @TODO 代码胶着 if ($.TE.buttons[btnName]) enabled = true; } if (enabled) { $(this).removeClass(opt.cssname.disable); } else { $(this).addClass(opt.cssname.disable); } }); }; //core code start function editorCore($frame, $area, v) { //TODO 参数改为全局的。 var defaults = { docType: '<!DOCTYPE HTML>', docCss: "", bodyStyle: "margin:4px; font:10pt Arial,Verdana; cursor:text", focusExt: function (editor) { //触发编辑器获得焦点时执行,比如刷新按钮 }, //textarea内容更新到iframe的处理函数 updateFrame: function (code) { //翻转flash为占位符 code = code.replace(/(<embed[^>]*?type="application\/x-shockwave-flash" [^>]*?>)/ig, function ($1) { var ret = '<img class="_flash_position" src="' + $.TE.basePath() + 'skins/default/img/spacer.gif" style="', _width = $1.match(/width="(\d+)"/), _height = $1.match(/height="(\d+)"/), _src = $1.match(/src="([^"]+)"/), _wmode = $1.match(/wmode="(\w+)"/), _data = ''; _width = _width && _width[1] ? parseInt(_width[1]) : 0; _height = _height && _height[1] ? parseInt(_height[1]) : 0; _src = _src && _src[1] ? _src[1] : ''; _wmode = _wmode && _wmode[1] ? true : false; _data = "{'src':'" + _src + "','width':'" + _width + "','height':'" + _height + "','wmode':" + (_wmode) + "}"; if (_width) ret += 'width:' + _width + 'px;'; if (_height) ret += 'height:' + _height + 'px;'; ret += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:' + _height + 'px;" '; ret += '_data="' + _data + '"'; ret += ' alt="flash占位符" />'; return ret; }); return code; }, //iframe更新到text的, TODO 去掉 updateTextArea: function (html) { //翻转占位符为flash html = html.replace(/(<img[^>]*?class=(?:"|)_flash_position(?:"|)[^>]*?>)/ig, function ($1) { var ret = '', data = $1.match(/_data="([^"]*)"/); if (data && data[1]) { data = eval('(' + data + ')'); } ret += '<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" '; ret += 'src="' + data.src + '" '; ret += 'width="' + data.width + '" '; ret += 'height="' + data.height + '" '; if (data.wmode) ret += 'wmode="transparent" '; ret += '/>'; return ret; }); return html; } }; options = $.extend({}, defaults, v); //存储属性 this.opt = options; this.$frame = $frame; this.$area = $area; var contentWindow = $frame[0].contentWindow, doc = this.doc = contentWindow.document, $doc = $(doc); var _self = this; //初始化 doc.open(); doc.write( options.docType + '<html>' + ((options.docCss === '') ? '' : '<head><link rel="stylesheet" type="text/css" href="' + options.docCss + '" /></head>') + '<body style="' + options.bodyStyle + '"></body></html>' ); doc.close(); //设置frame编辑模式 try { if (ie) { doc.body.contentEditable = true; } else { doc.designMode = "on"; } } catch (err) { $.debug(err, "创建编辑模式错误"); } //统一 IE FF 等的 execCommand 行为 try { this.e.execCommand("styleWithCSS", 0, 0) } catch (e) { try { this.e.execCommand("useCSS", 0, 1); } catch (e) { } } //监听 if (ie) $doc.click(function () { _self.focus(); }); this.updateFrame(); //更新内容 if (ie) { $doc.bind("beforedeactivate beforeactivate selectionchange keypress", function (e) { if (e.type == "beforedeactivate") _self.inactive = true; else if (e.type == "beforeactivate") { if (!_self.inactive && _self.range && _self.range.length > 1) _self.range.shift(); delete _self.inactive; } else if (!_self.inactive) { if (!_self.range) _self.range = []; _self.range.unshift(_self.getRange()); while (_self.range.length > 2) _self.range.pop(); } }); // Restore the text range when the iframe gains focus $frame.focus(function () { _self.restoreRange(); }); } ($.browser.mozilla ? $doc : $(contentWindow)).blur(function () { _self.updateTextArea(true); }); this.$area.blur(function () { // Update the iframe when the textarea loses focus _self.updateFrame(true); }); /* * //自动添加p标签 * $doc.keydown(function(e){ * if(e.keyCode == 13){ * //_self.pasteHTML('<p>&nbsp;</p>'); * //this.execCommand( 'formatblock', false, '<p>' ); * } * }); */ } //是否为源码模式 editorCore.prototype.sourceMode = function () { return this.$area.is(":visible"); }; //编辑器获得焦点 editorCore.prototype.focus = function () { var opt = this.opt; if (this.sourceMode()) { this.$area.focus(); } else { this.$frame[0].contentWindow.focus(); } if ($.isFunction(opt.focusExt)) opt.focusExt(this); }; //textarea内容更新到iframe editorCore.prototype.updateFrame = function (checkForChange) { var code = this.$area.val(), options = this.opt, updateFrameCallback = options.updateFrame, $body = $(this.doc.body); //判断是否已经修改 if (updateFrameCallback) { var sum = checksum(code); if (checkForChange && this.areaChecksum == sum) return; this.areaChecksum = sum; } //回调函数处理 var html = updateFrameCallback ? updateFrameCallback(code) : code; // 禁止script标签 html = html.replace(/<(?=\/?script)/ig, "&lt;"); // TODO,判断是否有作用 if (options.updateTextArea) this.frameChecksum = checksum(html); if (html != $body.html()) { $body.html(html); } }; editorCore.prototype.getRange = function () { if (ie) return this.getSelection().createRange(); return this.getSelection().getRangeAt(0); }; editorCore.prototype.getSelection = function () { if (ie) return this.doc.selection; return this.$frame[0].contentWindow.getSelection(); }; editorCore.prototype.restoreRange = function () { if (ie && this.range) this.range[0].select(); }; editorCore.prototype.selectedHTML = function () { this.restoreRange(); var range = this.getRange(); if (ie) return range.htmlText; var layer = $("<layer>")[0]; layer.appendChild(range.cloneContents()); var html = layer.innerHTML; layer = null; return html; }; editorCore.prototype.selectedText = function () { this.restoreRange(); if (ie) return this.getRange().text; return this.getSelection().toString(); }; editorCore.prototype.pasteHTML = function (value) { this.restoreRange(); if (ie) { this.getRange().pasteHTML(value); } else { this.doc.execCommand("inserthtml", 0, value || null); } //获得焦点 this.$frame[0].contentWindow.focus(); } editorCore.prototype.updateTextArea = function (checkForChange) { var html = $(this.doc.body).html(), options = this.opt, updateTextAreaCallback = options.updateTextArea, $area = this.$area; if (updateTextAreaCallback) { var sum = checksum(html); if (checkForChange && this.frameChecksum == sum) return; this.frameChecksum = sum; } var code = updateTextAreaCallback ? updateTextAreaCallback(html) : html; // TODO 判断是否有必要 if (options.updateFrame) this.areaChecksum = checksum(code); if (code != $area.val()) { $area.val(code); } }; function checksum(text) { var a = 1, b = 0; for (var index = 0; index < text.length; ++index) { a = (a + text.charCodeAt(index)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } $.extend({ teExt: { //扩展配置 }, debug: function (msg, group) { //判断是否有console对象 if ($.TE.debug && window.console !== undefined) { //分组开始 if (group) console.group(group); if ($.type(msg) == "string") { //是否为执行特殊函数,用双冒号隔开 if (msg.indexOf("::") != -1) { var arr = msg.split("::"); eval("console." + arr[0] + "('" + arr[1] + "')"); } else { console.debug(msg); } } else { if ($(msg).html() == null) { console.dir(msg); //输出对象或数组 } else { console.dirxml($(msg)[0]); //输出dom对象 } } //记录trace信息 if ($.TE.debug == 2) { console.group("trace 信息:"); console.trace(); console.groupEnd(); } //分组结束 if (group) console.groupEnd(); } }, //end debug defined: function (variable) { return $.type(variable) == "undefined" ? false : true; }, isTag: function (tn) { if (!tn) return false; return $(this)[0].tagName.toLowerCase() == tn ? true : false; }, //end istag include: function (file) { if (!$.defined($.TE.loadUrl)) $.TE.loadUrl = {}; //定义皮肤路径和插件路径。 var basePath = $.TE.basePath(), skinsDir = basePath + "skins/", pluginDir = basePath + "plugins/"; var files = $.type(file) == "string" ? [file] : file; for (var i = 0; i < files.length; i++) { var loadurl = name = $.trim(files[i]); //判断是否已经加载过 if ($.TE.loadUrl[loadurl]) { continue; } //判断是否有@ var at = false; if (name.indexOf("@") != -1) { at = true; name = name.substr(1); } var att = name.split('.'); var ext = att[att.length - 1].toLowerCase(); if (ext == "css") { //加载css var filepath = at ? name : skinsDir + name; var newNode = document.createElement("link"); newNode.setAttribute('type', 'text/css'); newNode.setAttribute('rel', 'stylesheet'); newNode.setAttribute('href', filepath); $.TE.loadUrl[loadurl] = 1; } else { var filepath = at ? name : pluginDir + name; //$("<scri"+"pt>"+"</scr"+"ipt>").attr({src:filepath,type:'text/javascript'}).appendTo('head'); var newNode = document.createElement("script"); newNode.type = "text/javascript"; newNode.src = filepath; newNode.id = loadurl; //实现批量加载 newNode.onload = function () { $.TE.loadUrl[this.id] = 1; }; newNode.onreadystatechange = function () { //针对ie if ((newNode.readyState == 'loaded' || newNode.readyState == 'complete')) { $.TE.loadUrl[this.id] = 1; } }; } $("head")[0].appendChild(newNode); } }, //end include loadedFile: function (file) { //判断是否加载 if (!$.defined($.TE.loadUrl)) return false; var files = $.type(file) == "string" ? [file] : file, result = true; $.each(files, function (i, name) { if (!$.TE.loadUrl[name]) result = false; //alert(name+':'+result); }); return result; }, //end loaded loadFile: function (file, fun) { //加载文件,加载完毕后执行fun函数。 $.include(file); var time = 0; var check = function () { //alert($.loadedFile(file)); if ($.loadedFile(file)) { if ($.isFunction(fun)) fun(); } else { //alert(time); if (time >= $.TE.timeOut) { // TODO 细化哪些文件加载失败。 $.debug(file, "文件加载失败"); } else { //alert('time:'+time); setTimeout(check, 50); time += 50; } } }; check(); } //end loadFile }); })(jQuery); jQuery.TE.config( 'mini', { 'controls' : 'font,fontsize,fontcolor,backcolor,bold,italic,underline,unformat,leftalign,centeralign,rightalign,orderedlist,unorderedlist', 'width':498, 'height':400, 'resizeType':1 } );
JavaScript
/** * SyntaxHighlighter * http://alexgorbatchev.com/SyntaxHighlighter * * SyntaxHighlighter is donationware. If you are using it, please donate. * http://alexgorbatchev.com/SyntaxHighlighter/donate.html * * @version * 3.0.83 (July 02 2010) * * @copyright * Copyright (C) 2004-2010 Alex Gorbatchev. * * @license * Dual licensed under the MIT and GPL licenses. */ eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(2(){1 h=5;h.I=2(){2 n(c,a){4(1 d=0;d<c.9;d++)i[c[d]]=a}2 o(c){1 a=r.H("J"),d=3;a.K=c;a.M="L/t";a.G="t";a.u=a.v=2(){6(!d&&(!8.7||8.7=="F"||8.7=="z")){d=q;e[c]=q;a:{4(1 p y e)6(e[p]==3)B a;j&&5.C(k)}a.u=a.v=x;a.D.O(a)}};r.N.R(a)}1 f=Q,l=h.P(),i={},e={},j=3,k=x,b;5.T=2(c){k=c;j=q};4(b=0;b<f.9;b++){1 m=f[b].w?f[b]:f[b].S(/\\s+/),g=m.w();n(m,g)}4(b=0;b<l.9;b++)6(g=i[l[b].E.A]){e[g]=3;o(g)}}})();',56,56,'|var|function|false|for|SyntaxHighlighter|if|readyState|this|length|||||||||||||||||true|document||javascript|onload|onreadystatechange|pop|null|in|complete|brush|break|highlight|parentNode|params|loaded|language|createElement|autoloader|script|src|text|type|body|removeChild|findElements|arguments|appendChild|split|all'.split('|'),0,{}))
JavaScript
/* * File: ColReorder.js * Version: 1.0.6 * CVS: $Id$ * Description: Controls for column visiblity in DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Created: Wed Sep 15 18:23:29 BST 2010 * Modified: $Date$ by $Author$ * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: DataTables * Contact: www.sprymedia.co.uk/contact * * Copyright 2010-2011 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd * */ (function($, window, document) { /** * Switch the key value pairing of an index array to be value key (i.e. the old value is now the * key). For example consider [ 2, 0, 1 ] this would be returned as [ 1, 2, 0 ]. * @method fnInvertKeyValues * @param array aIn Array to switch around * @returns array */ function fnInvertKeyValues( aIn ) { var aRet=[]; for ( var i=0, iLen=aIn.length ; i<iLen ; i++ ) { aRet[ aIn[i] ] = i; } return aRet; } /** * Modify an array by switching the position of two elements * @method fnArraySwitch * @param array aArray Array to consider, will be modified by reference (i.e. no return) * @param int iFrom From point * @param int iTo Insert point * @returns void */ function fnArraySwitch( aArray, iFrom, iTo ) { var mStore = aArray.splice( iFrom, 1 )[0]; aArray.splice( iTo, 0, mStore ); } /** * Switch the positions of nodes in a parent node (note this is specifically designed for * table rows). Note this function considers all element nodes under the parent! * @method fnDomSwitch * @param string sTag Tag to consider * @param int iFrom Element to move * @param int Point to element the element to (before this point), can be null for append * @returns void */ function fnDomSwitch( nParent, iFrom, iTo ) { var anTags = []; for ( var i=0, iLen=nParent.childNodes.length ; i<iLen ; i++ ) { if ( nParent.childNodes[i].nodeType == 1 ) { anTags.push( nParent.childNodes[i] ); } } var nStore = anTags[ iFrom ]; if ( iTo !== null ) { nParent.insertBefore( nStore, anTags[iTo] ); } else { nParent.appendChild( nStore ); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables plug-in API functions * * This are required by ColReorder in order to perform the tasks required, and also keep this * code portable, to be used for other column reordering projects with DataTables, if needed. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Plug-in for DataTables which will reorder the internal column structure by taking the column * from one position (iFrom) and insert it into a given point (iTo). * @method $.fn.dataTableExt.oApi.fnColReorder * @param object oSettings DataTables settings object - automatically added by DataTables! * @param int iFrom Take the column to be repositioned from this point * @param int iTo and insert it into this point * @returns void */ $.fn.dataTableExt.oApi.fnColReorder = function ( oSettings, iFrom, iTo ) { var i, iLen, j, jLen, iCols=oSettings.aoColumns.length, nTrs, oCol; /* Sanity check in the input */ if ( iFrom == iTo ) { /* Pointless reorder */ return; } if ( iFrom < 0 || iFrom >= iCols ) { this.oApi._fnLog( oSettings, 1, "ColReorder 'from' index is out of bounds: "+iFrom ); return; } if ( iTo < 0 || iTo >= iCols ) { this.oApi._fnLog( oSettings, 1, "ColReorder 'to' index is out of bounds: "+iTo ); return; } /* * Calculate the new column array index, so we have a mapping between the old and new */ var aiMapping = []; for ( i=0, iLen=iCols ; i<iLen ; i++ ) { aiMapping[i] = i; } fnArraySwitch( aiMapping, iFrom, iTo ); var aiInvertMapping = fnInvertKeyValues( aiMapping ); /* * Convert all internal indexing to the new column order indexes */ /* Sorting */ for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ ) { oSettings.aaSorting[i][0] = aiInvertMapping[ oSettings.aaSorting[i][0] ]; } /* Fixed sorting */ if ( oSettings.aaSortingFixed !== null ) { for ( i=0, iLen=oSettings.aaSortingFixed.length ; i<iLen ; i++ ) { oSettings.aaSortingFixed[i][0] = aiInvertMapping[ oSettings.aaSortingFixed[i][0] ]; } } /* Data column sorting (the column which the sort for a given column should take place on) */ for ( i=0, iLen=iCols ; i<iLen ; i++ ) { oCol = oSettings.aoColumns[i]; for ( j=0, jLen=oCol.aDataSort.length ; j<jLen ; j++ ) { oCol.aDataSort[j] = aiInvertMapping[ oCol.aDataSort[j] ]; } } /* Update the Get and Set functions for each column */ for ( i=0, iLen=iCols ; i<iLen ; i++ ) { oCol = oSettings.aoColumns[i]; if ( typeof oCol.mDataProp == 'number' ) { oCol.mDataProp = aiInvertMapping[ oCol.mDataProp ]; oCol.fnGetData = oSettings.oApi._fnGetObjectDataFn( oCol.mDataProp ); oCol.fnSetData = oSettings.oApi._fnSetObjectDataFn( oCol.mDataProp ); } } /* * Move the DOM elements */ if ( oSettings.aoColumns[iFrom].bVisible ) { /* Calculate the current visible index and the point to insert the node before. The insert * before needs to take into account that there might not be an element to insert before, * in which case it will be null, and an appendChild should be used */ var iVisibleIndex = this.oApi._fnColumnIndexToVisible( oSettings, iFrom ); var iInsertBeforeIndex = null; i = iTo < iFrom ? iTo : iTo + 1; while ( iInsertBeforeIndex === null && i < iCols ) { iInsertBeforeIndex = this.oApi._fnColumnIndexToVisible( oSettings, i ); i++; } /* Header */ nTrs = oSettings.nTHead.getElementsByTagName('tr'); for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex ); } /* Footer */ if ( oSettings.nTFoot !== null ) { nTrs = oSettings.nTFoot.getElementsByTagName('tr'); for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex ); } } /* Body */ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { fnDomSwitch( oSettings.aoData[i].nTr, iVisibleIndex, iInsertBeforeIndex ); } } } /* * Move the internal array elements */ /* Columns */ fnArraySwitch( oSettings.aoColumns, iFrom, iTo ); /* Search columns */ fnArraySwitch( oSettings.aoPreSearchCols, iFrom, iTo ); /* Array array - internal data anodes cache */ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( $.isArray( oSettings.aoData[i]._aData ) ) { fnArraySwitch( oSettings.aoData[i]._aData, iFrom, iTo ); } fnArraySwitch( oSettings.aoData[i]._anHidden, iFrom, iTo ); } /* Reposition the header elements in the header layout array */ for ( i=0, iLen=oSettings.aoHeader.length ; i<iLen ; i++ ) { fnArraySwitch( oSettings.aoHeader[i], iFrom, iTo ); } if ( oSettings.aoFooter !== null ) { for ( i=0, iLen=oSettings.aoFooter.length ; i<iLen ; i++ ) { fnArraySwitch( oSettings.aoFooter[i], iFrom, iTo ); } } /* * Update DataTables' event handlers */ /* Sort listener */ for ( i=0, iLen=iCols ; i<iLen ; i++ ) { $(oSettings.aoColumns[i].nTh).unbind('click'); this.oApi._fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i ); } /* Fire an event so other plug-ins can update */ $(oSettings.oInstance).trigger( 'column-reorder', [ oSettings, { "iFrom": iFrom, "iTo": iTo, "aiInvertMapping": aiInvertMapping } ] ); if ( typeof oSettings.oInstance._oPluginFixedHeader != 'undefined' ) { oSettings.oInstance._oPluginFixedHeader.fnUpdate(); } }; /** * ColReorder provides column visiblity control for DataTables * @class ColReorder * @constructor * @param {object} DataTables object * @param {object} ColReorder options */ ColReorder = function( oTable, oOpts ) { /* Santiy check that we are a new instance */ if ( !this.CLASS || this.CLASS != "ColReorder" ) { alert( "Warning: ColReorder must be initialised with the keyword 'new'" ); } if ( typeof oOpts == 'undefined' ) { oOpts = {}; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for ColReorder instance */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Initialisation object used for this instance * @property init * @type object * @default {} */ "init": oOpts, /** * Number of columns to fix (not allow to be reordered) * @property fixed * @type int * @default 0 */ "fixed": 0, /** * Callback function for once the reorder has been done * @property dropcallback * @type function * @default null */ "dropCallback": null, /** * @namespace Information used for the mouse drag */ "mouse": { "startX": -1, "startY": -1, "offsetX": -1, "offsetY": -1, "target": -1, "targetIndex": -1, "fromIndex": -1 }, /** * Information which is used for positioning the insert cusor and knowing where to do the * insert. Array of objects with the properties: * x: x-axis position * to: insert point * @property aoTargets * @type array * @default [] */ "aoTargets": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Dragging element (the one the mouse is moving) * @property drag * @type element * @default null */ "drag": null, /** * The insert cursor * @property pointer * @type element * @default null */ "pointer": null }; /* Constructor logic */ this.s.dt = oTable.fnSettings(); this._fnConstruct(); /* Store the instance for later use */ ColReorder.aoInstances.push( this ); return this; }; ColReorder.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ "fnReset": function () { var a = []; for ( var i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ ) { a.push( this.s.dt.aoColumns[i]._ColReorder_iOrigCol ); } this._fnOrderColumns( a ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @returns void * @private */ "_fnConstruct": function () { var that = this; var i, iLen; /* Columns discounted from reordering - counting left to right */ if ( typeof this.s.init.iFixedColumns != 'undefined' ) { this.s.fixed = this.s.init.iFixedColumns; } /* Drop callback initialisation option */ if ( typeof this.s.init.fnReorderCallback != 'undefined' ) { this.s.dropCallback = this.s.init.fnReorderCallback; } /* Add event handlers for the drag and drop, and also mark the original column order */ for ( i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ ) { if ( i > this.s.fixed-1 ) { this._fnMouseListener( i, this.s.dt.aoColumns[i].nTh ); } /* Mark the original column order for later reference */ this.s.dt.aoColumns[i]._ColReorder_iOrigCol = i; } /* State saving */ this.s.dt.oApi._fnCallbackReg( this.s.dt, 'aoStateSaveParams', function (oS, oData) { that._fnStateSave.call( that, oData ); }, "ColReorder_State" ); /* An initial column order has been specified */ var aiOrder = null; if ( typeof this.s.init.aiOrder != 'undefined' ) { aiOrder = this.s.init.aiOrder.slice(); } /* State loading, overrides the column order given */ if ( this.s.dt.oLoadedState && typeof this.s.dt.oLoadedState.ColReorder != 'undefined' && this.s.dt.oLoadedState.ColReorder.length == this.s.dt.aoColumns.length ) { aiOrder = this.s.dt.oLoadedState.ColReorder; } /* If we have an order to apply - do so */ if ( aiOrder ) { /* We might be called during or after the DataTables initialisation. If before, then we need * to wait until the draw is done, if after, then do what we need to do right away */ if ( !that.s.dt._bInitComplete ) { var bDone = false; this.s.dt.aoDrawCallback.push( { "fn": function () { if ( !that.s.dt._bInitComplete && !bDone ) { bDone = true; var resort = fnInvertKeyValues( aiOrder ); that._fnOrderColumns.call( that, resort ); } }, "sName": "ColReorder_Pre" } ); } else { var resort = fnInvertKeyValues( aiOrder ); that._fnOrderColumns.call( that, resort ); } } }, /** * Set the column order from an array * @method _fnOrderColumns * @param array a An array of integers which dictate the column order that should be applied * @returns void * @private */ "_fnOrderColumns": function ( a ) { if ( a.length != this.s.dt.aoColumns.length ) { this.s.dt.oInstance.oApi._fnLog( this.s.dt, 1, "ColReorder - array reorder does not "+ "match known number of columns. Skipping." ); return; } for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { var currIndex = $.inArray( i, a ); if ( i != currIndex ) { /* Reorder our switching array */ fnArraySwitch( a, currIndex, i ); /* Do the column reorder in the table */ this.s.dt.oInstance.fnColReorder( currIndex, i ); } } /* When scrolling we need to recalculate the column sizes to allow for the shift */ if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" ) { this.s.dt.oInstance.fnAdjustColumnSizing(); } /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState( this.s.dt ); }, /** * Because we change the indexes of columns in the table, relative to their starting point * we need to reorder the state columns to what they are at the starting point so we can * then rearrange them again on state load! * @method _fnStateSave * @param object oState DataTables state * @returns string JSON encoded cookie string for DataTables * @private */ "_fnStateSave": function ( oState ) { var i, iLen, aCopy, iOrigColumn; var oSettings = this.s.dt; /* Sorting */ for ( i=0 ; i<oState.aaSorting.length ; i++ ) { oState.aaSorting[i][0] = oSettings.aoColumns[ oState.aaSorting[i][0] ]._ColReorder_iOrigCol; } aSearchCopy = $.extend( true, [], oState.aoSearchCols ); oState.ColReorder = []; for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { iOrigColumn = oSettings.aoColumns[i]._ColReorder_iOrigCol; /* Column filter */ oState.aoSearchCols[ iOrigColumn ] = aSearchCopy[i]; /* Visibility */ oState.abVisCols[ iOrigColumn ] = oSettings.aoColumns[i].bVisible; /* Column reordering */ oState.ColReorder.push( iOrigColumn ); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Mouse drop and drag */ /** * Add a mouse down listener to a particluar TH element * @method _fnMouseListener * @param int i Column index * @param element nTh TH element clicked on * @returns void * @private */ "_fnMouseListener": function ( i, nTh ) { var that = this; $(nTh).bind( 'mousedown.ColReorder', function (e) { e.preventDefault(); that._fnMouseDown.call( that, e, nTh ); } ); }, /** * Mouse down on a TH element in the table header * @method _fnMouseDown * @param event e Mouse event * @param element nTh TH element to be dragged * @returns void * @private */ "_fnMouseDown": function ( e, nTh ) { var that = this, aoColumns = this.s.dt.aoColumns; /* Store information about the mouse position */ var nThTarget = e.target.nodeName == "TH" ? e.target : $(e.target).parents('TH')[0]; var offset = $(nThTarget).offset(); this.s.mouse.startX = e.pageX; this.s.mouse.startY = e.pageY; this.s.mouse.offsetX = e.pageX - offset.left; this.s.mouse.offsetY = e.pageY - offset.top; this.s.mouse.target = nTh; this.s.mouse.targetIndex = $('th', nTh.parentNode).index( nTh ); this.s.mouse.fromIndex = this.s.dt.oInstance.oApi._fnVisibleToColumnIndex( this.s.dt, this.s.mouse.targetIndex ); /* Calculate a cached array with the points of the column inserts, and the 'to' points */ this.s.aoTargets.splice( 0, this.s.aoTargets.length ); this.s.aoTargets.push( { "x": $(this.s.dt.nTable).offset().left, "to": 0 } ); var iToPoint = 0; for ( var i=0, iLen=aoColumns.length ; i<iLen ; i++ ) { /* For the column / header in question, we want it's position to remain the same if the * position is just to it's immediate left or right, so we only incremement the counter for * other columns */ if ( i != this.s.mouse.fromIndex ) { iToPoint++; } if ( aoColumns[i].bVisible ) { this.s.aoTargets.push( { "x": $(aoColumns[i].nTh).offset().left + $(aoColumns[i].nTh).outerWidth(), "to": iToPoint } ); } } /* Disallow columns for being reordered by drag and drop, counting left to right */ if ( this.s.fixed !== 0 ) { this.s.aoTargets.splice( 0, this.s.fixed ); } /* Add event handlers to the document */ $(document).bind( 'mousemove.ColReorder', function (e) { that._fnMouseMove.call( that, e ); } ); $(document).bind( 'mouseup.ColReorder', function (e) { that._fnMouseUp.call( that, e ); } ); }, /** * Deal with a mouse move event while dragging a node * @method _fnMouseMove * @param event e Mouse event * @returns void * @private */ "_fnMouseMove": function ( e ) { var that = this; if ( this.dom.drag === null ) { /* Only create the drag element if the mouse has moved a specific distance from the start * point - this allows the user to make small mouse movements when sorting and not have a * possibly confusing drag element showing up */ if ( Math.pow( Math.pow(e.pageX - this.s.mouse.startX, 2) + Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5 ) < 5 ) { return; } this._fnCreateDragNode(); } /* Position the element - we respect where in the element the click occured */ this.dom.drag.style.left = (e.pageX - this.s.mouse.offsetX) + "px"; this.dom.drag.style.top = (e.pageY - this.s.mouse.offsetY) + "px"; /* Based on the current mouse position, calculate where the insert should go */ var bSet = false; for ( var i=1, iLen=this.s.aoTargets.length ; i<iLen ; i++ ) { if ( e.pageX < this.s.aoTargets[i-1].x + ((this.s.aoTargets[i].x-this.s.aoTargets[i-1].x)/2) ) { this.dom.pointer.style.left = this.s.aoTargets[i-1].x +"px"; this.s.mouse.toIndex = this.s.aoTargets[i-1].to; bSet = true; break; } } /* The insert element wasn't positioned in the array (less than operator), so we put it at * the end */ if ( !bSet ) { this.dom.pointer.style.left = this.s.aoTargets[this.s.aoTargets.length-1].x +"px"; this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length-1].to; } }, /** * Finish off the mouse drag and insert the column where needed * @method _fnMouseUp * @param event e Mouse event * @returns void * @private */ "_fnMouseUp": function ( e ) { var that = this; $(document).unbind( 'mousemove.ColReorder' ); $(document).unbind( 'mouseup.ColReorder' ); if ( this.dom.drag !== null ) { /* Remove the guide elements */ document.body.removeChild( this.dom.drag ); document.body.removeChild( this.dom.pointer ); this.dom.drag = null; this.dom.pointer = null; /* Actually do the reorder */ this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex ); /* When scrolling we need to recalculate the column sizes to allow for the shift */ if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" ) { this.s.dt.oInstance.fnAdjustColumnSizing(); } if ( this.s.dropCallback !== null ) { this.s.dropCallback.call( this ); } /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState( this.s.dt ); } }, /** * Copy the TH element that is being drags so the user has the idea that they are actually * moving it around the page. * @method _fnCreateDragNode * @returns void * @private */ "_fnCreateDragNode": function () { var that = this; this.dom.drag = $(this.s.dt.nTHead.parentNode).clone(true)[0]; this.dom.drag.className += " DTCR_clonedTable"; while ( this.dom.drag.getElementsByTagName('caption').length > 0 ) { this.dom.drag.removeChild( this.dom.drag.getElementsByTagName('caption')[0] ); } while ( this.dom.drag.getElementsByTagName('tbody').length > 0 ) { this.dom.drag.removeChild( this.dom.drag.getElementsByTagName('tbody')[0] ); } while ( this.dom.drag.getElementsByTagName('tfoot').length > 0 ) { this.dom.drag.removeChild( this.dom.drag.getElementsByTagName('tfoot')[0] ); } $('thead tr:eq(0)', this.dom.drag).each( function () { $('th:not(:eq('+that.s.mouse.targetIndex+'))', this).remove(); } ); $('tr', this.dom.drag).height( $('tr:eq(0)', that.s.dt.nTHead).height() ); $('thead tr:gt(0)', this.dom.drag).remove(); $('thead th:eq(0)', this.dom.drag).each( function (i) { this.style.width = $('th:eq('+that.s.mouse.targetIndex+')', that.s.dt.nTHead).width()+"px"; } ); this.dom.drag.style.position = "absolute"; this.dom.drag.style.top = "0px"; this.dom.drag.style.left = "0px"; this.dom.drag.style.width = $('th:eq('+that.s.mouse.targetIndex+')', that.s.dt.nTHead).outerWidth()+"px"; this.dom.pointer = document.createElement( 'div' ); this.dom.pointer.className = "DTCR_pointer"; this.dom.pointer.style.position = "absolute"; if ( this.s.dt.oScroll.sX === "" && this.s.dt.oScroll.sY === "" ) { this.dom.pointer.style.top = $(this.s.dt.nTable).offset().top+"px"; this.dom.pointer.style.height = $(this.s.dt.nTable).height()+"px"; } else { this.dom.pointer.style.top = $('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top+"px"; this.dom.pointer.style.height = $('div.dataTables_scroll', this.s.dt.nTableWrapper).height()+"px"; } document.body.appendChild( this.dom.pointer ); document.body.appendChild( this.dom.drag ); } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static parameters * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Array of all ColReorder instances for later reference * @property ColReorder.aoInstances * @type array * @default [] * @static */ ColReorder.aoInstances = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static functions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Reset the column ordering for a DataTables instance * @method ColReorder.fnReset * @param object oTable DataTables instance to consider * @returns void * @static */ ColReorder.fnReset = function ( oTable ) { for ( var i=0, iLen=ColReorder.aoInstances.length ; i<iLen ; i++ ) { if ( ColReorder.aoInstances[i].s.dt.oInstance == oTable ) { ColReorder.aoInstances[i].fnReset(); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Name of this class * @constant CLASS * @type String * @default ColReorder */ ColReorder.prototype.CLASS = "ColReorder"; /** * ColReorder version * @constant VERSION * @type String * @default As code */ ColReorder.VERSION = "1.0.6"; ColReorder.prototype.VERSION = ColReorder.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var oTable = oDTSettings.oInstance; if ( typeof oTable._oPluginColReorder == 'undefined' ) { var opts = typeof oDTSettings.oInit.oColReorder != 'undefined' ? oDTSettings.oInit.oColReorder : {}; oTable._oPluginColReorder = new ColReorder( oDTSettings.oInstance, opts ); } else { oTable.oApi._fnLog( oDTSettings, 1, "ColReorder attempted to initialise twice. Ignoring second" ); } return null; /* No node to insert */ }, "cFeature": "R", "sFeature": "ColReorder" } ); } else { alert( "Warning: ColReorder requires DataTables 1.9.0 or greater - www.datatables.net/download"); } })(jQuery, window, document);
JavaScript
/* * File: TableTools.js * Version: 2.1.3 * Description: Tools and buttons for DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: DataTables * * Copyright 2009-2012 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd */ /* Global scope for TableTools */ var TableTools; (function($, window, document) { /** * TableTools provides flexible buttons and other tools for a DataTables enhanced table * @class TableTools * @constructor * @param {Object} oDT DataTables instance * @param {Object} oOpts TableTools options * @param {String} oOpts.sSwfPath ZeroClipboard SWF path * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi' * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection * @param {Function} oOpts.fnRowSelected Callback function just after row selection * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected * @param {Array} oOpts.aButtons List of buttons to be used */ TableTools = function( oDT, oOpts ) { /* Santiy check that we are a new instance */ if ( ! this instanceof TableTools ) { alert( "Warning: TableTools must be initialised with the keyword 'new'" ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for TableTools instance */ this.s = { /** * Store 'this' so the instance can be retrieved from the settings object * @property that * @type object * @default this */ "that": this, /** * DataTables settings objects * @property dt * @type object * @default <i>From the oDT init option</i> */ "dt": oDT.fnSettings(), /** * @namespace Print specific information */ "print": { /** * DataTables draw 'start' point before the printing display was shown * @property saveStart * @type int * @default -1 */ "saveStart": -1, /** * DataTables draw 'length' point before the printing display was shown * @property saveLength * @type int * @default -1 */ "saveLength": -1, /** * Page scrolling point before the printing display was shown so it can be restored * @property saveScroll * @type int * @default -1 */ "saveScroll": -1, /** * Wrapped function to end the print display (to maintain scope) * @property funcEnd * @type Function * @default function () {} */ "funcEnd": function () {} }, /** * A unique ID is assigned to each button in each instance * @property buttonCounter * @type int * @default 0 */ "buttonCounter": 0, /** * @namespace Select rows specific information */ "select": { /** * Select type - can be 'none', 'single' or 'multi' * @property type * @type string * @default "" */ "type": "", /** * Array of nodes which are currently selected * @property selected * @type array * @default [] */ "selected": [], /** * Function to run before the selection can take place. Will cancel the select if the * function returns false * @property preRowSelect * @type Function * @default null */ "preRowSelect": null, /** * Function to run when a row is selected * @property postSelected * @type Function * @default null */ "postSelected": null, /** * Function to run when a row is deselected * @property postDeselected * @type Function * @default null */ "postDeselected": null, /** * Indicate if all rows are selected (needed for server-side processing) * @property all * @type boolean * @default false */ "all": false, /** * Class name to add to selected TR nodes * @property selectedClass * @type String * @default "" */ "selectedClass": "" }, /** * Store of the user input customisation object * @property custom * @type object * @default {} */ "custom": {}, /** * SWF movie path * @property swfPath * @type string * @default "" */ "swfPath": "", /** * Default button set * @property buttonSet * @type array * @default [] */ "buttonSet": [], /** * When there is more than one TableTools instance for a DataTable, there must be a * master which controls events (row selection etc) * @property master * @type boolean * @default false */ "master": false, /** * Tag names that are used for creating collections and buttons * @namesapce */ "tags": {} }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * DIV element that is create and all TableTools buttons (and their children) put into * @property container * @type node * @default null */ "container": null, /** * The table node to which TableTools will be applied * @property table * @type node * @default null */ "table": null, /** * @namespace Nodes used for the print display */ "print": { /** * Nodes which have been removed from the display by setting them to display none * @property hidden * @type array * @default [] */ "hidden": [], /** * The information display saying telling the user about the print display * @property message * @type node * @default null */ "message": null }, /** * @namespace Nodes used for a collection display. This contains the currently used collection */ "collection": { /** * The div wrapper containing the buttons in the collection (i.e. the menu) * @property collection * @type node * @default null */ "collection": null, /** * Background display to provide focus and capture events * @property background * @type node * @default null */ "background": null } }; /** * @namespace Name space for the classes that this TableTools instance will use * @extends TableTools.classes */ this.classes = $.extend( true, {}, TableTools.classes ); if ( this.s.dt.bJUI ) { $.extend( true, this.classes, TableTools.classes_themeroller ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} TableTools settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ if ( typeof oOpts == 'undefined' ) { oOpts = {}; } this._fnConstruct( oOpts ); return this; }; TableTools.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @returns {array} List of TR nodes which are currently selected */ "fnGetSelected": function () { var out=[]; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( data[i].nTr ); } } return out; }, /** * Get the data source objects/arrays from DataTables for the selected rows (same as * fnGetSelected followed by fnGetData on each row from the table) * @returns {array} Data from the TR nodes which are currently selected */ "fnGetSelectedData": function () { var out = []; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( this.s.dt.oInstance.fnGetData(i) ); } } return out; }, /** * Check to see if a current row is selected or not * @param {Node} n TR node to check if it is currently selected or not * @returns {Boolean} true if select, false otherwise */ "fnIsSelected": function ( n ) { var pos = this.s.dt.oInstance.fnGetPosition( n ); return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false; }, /** * Select all rows in the table * @param {boolean} [filtered=false] Select only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are selected. */ "fnSelectAll": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowSelect( (filtered === true) ? s.dt.aiDisplay : s.dt.aoData ); }, /** * Deselect all rows in the table * @param {boolean} [filtered=false] Deselect only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are deselected. */ "fnSelectNone": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowDeselect( (filtered === true) ? s.dt.aiDisplay : s.dt.aoData ); }, /** * Select row(s) * @param {node|object|array} n The row(s) to select. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnSelect": function ( n ) { if ( this.s.select.type == "single" ) { this.fnSelectNone(); this._fnRowSelect( n ); } else if ( this.s.select.type == "multi" ) { this._fnRowSelect( n ); } }, /** * Deselect row(s) * @param {node|object|array} n The row(s) to deselect. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnDeselect": function ( n ) { this._fnRowDeselect( n ); }, /** * Get the title of the document - useful for file names. The title is retrieved from either * the configuration object's 'title' parameter, or the HTML document title * @param {Object} oConfig Button configuration object * @returns {String} Button title */ "fnGetTitle": function( oConfig ) { var sTitle = ""; if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if ( anTitle.length > 0 ) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ( "\u00A1".toString().length < 4 ) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }, /** * Calculate a unity array with the column width by proportion for a set of columns to be * included for a button. This is particularly useful for PDF creation, where we can use the * column widths calculated by the browser to size the columns in the PDF. * @param {Object} oConfig Button configuration object * @returns {Array} Unity array of column ratios */ "fnCalcColRatios": function ( oConfig ) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets( oConfig.mColumns ), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push( iWidth ); } } for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ ) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }, /** * Get the information contained in a table as a string * @param {Object} oConfig Button configuration object * @returns {String} Table data as a string */ "fnGetTableData": function ( oConfig ) { /* In future this could be used to get data from a plain HTML source as well as DataTables */ if ( this.s.dt ) { return this._fnGetDataTablesData( oConfig ); } }, /** * Pass text to a flash button instance, which will be used on the button's click handler * @param {Object} clip Flash button object * @param {String} text Text to set */ "fnSetText": function ( clip, text ) { this._fnFlashSetText( clip, text ); }, /** * Resize the flash elements of the buttons attached to this TableTools instance - this is * useful for when initialising TableTools when it is hidden (display:none) since sizes can't * be calculated at that time. */ "fnResizeButtons": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode ) { client.positionElement(); } } } }, /** * Check to see if any of the ZeroClipboard client's attached need to be resized */ "fnResizeRequired": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false ) { return true; } } } return false; }, /** * Programmatically enable or disable the print view * @param {boolean} [bView=true] Show the print view if true or not given. If false, then * terminate the print view and return to normal. * @param {object} [oConfig={}] Configuration for the print view * @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true * @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the * user to let them know what the print view is. * @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will * be included in the printed document. */ "fnPrint": function ( bView, oConfig ) { if ( oConfig === undefined ) { oConfig = {}; } if ( bView === undefined || bView ) { this._fnPrintStart( oConfig ); } else { this._fnPrintEnd(); } }, /** * Show a message to the end user which is nicely styled * @param {string} message The HTML string to show to the user * @param {int} time The duration the message is to be shown on screen for (mS) */ "fnInfo": function ( message, time ) { var nInfo = document.createElement( "div" ); nInfo.className = this.classes.print.info; nInfo.innerHTML = message; document.body.appendChild( nInfo ); setTimeout( function() { $(nInfo).fadeOut( "normal", function() { document.body.removeChild( nInfo ); } ); }, time ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnConstruct": function ( oOpts ) { var that = this; this._fnCustomiseSettings( oOpts ); /* Container element */ this.dom.container = document.createElement( this.s.tags.container ); this.dom.container.className = this.classes.container; /* Row selection config */ if ( this.s.select.type != 'none' ) { this._fnRowSelectConfig(); } /* Buttons */ this._fnButtonDefinations( this.s.buttonSet, this.dom.container ); /* Destructor - need to wipe the DOM for IE's garbage collector */ this.s.dt.aoDestroyCallback.push( { "sName": "TableTools", "fn": function () { that.dom.container.innerHTML = ""; } } ); }, /** * Take the user defined settings and the default settings and combine them. * @method _fnCustomiseSettings * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnCustomiseSettings": function ( oOpts ) { /* Is this the master control instance or not? */ if ( typeof this.s.dt._TableToolsInit == 'undefined' ) { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts ); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if ( typeof ZeroClipboard_TableTools != 'undefined' ) { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if ( this.s.custom.sSelectedClass ) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }, /** * Take the user input arrays and expand them to be fully defined, and then add them to a given * DOM element * @method _fnButtonDefinations * @param {array} buttonSet Set of user defined buttons * @param {node} wrapper Node to add the created buttons to * @returns void * @private */ "_fnButtonDefinations": function ( buttonSet, wrapper ) { var buttonDef; for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ ) { if ( typeof buttonSet[i] == "string" ) { if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i] ); continue; } buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true ); } else { if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends ); continue; } var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true ); buttonDef = $.extend( o, buttonSet[i], true ); } wrapper.appendChild( this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) ) ); } }, /** * Create and configure a TableTools button * @method _fnCreateButton * @param {Object} oConfig Button configuration object * @returns {Node} Button element * @private */ "_fnCreateButton": function ( oConfig, bCollectionButton ) { var nButton = this._fnButtonBase( oConfig, bCollectionButton ); if ( oConfig.sAction.match(/flash/) ) { this._fnFlashConfig( nButton, oConfig ); } else if ( oConfig.sAction == "text" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "div" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "collection" ) { this._fnTextConfig( nButton, oConfig ); this._fnCollectionConfig( nButton, oConfig ); } return nButton; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnButtonBase * @param {o} oConfig Button configuration object * @returns {Node} DIV element for the button * @private */ "_fnButtonBase": function ( o, bCollectionButton ) { var sTag, sLiner, sClass; if ( bCollectionButton ) { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement( sTag ), nSpan = document.createElement( sLiner ), masterS = this._fnGetMasterSettings(); nButton.className = sClass+" "+o.sButtonClass; nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter ); nButton.appendChild( nSpan ); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }, /** * Get the settings object for the master instance. When more than one TableTools instance is * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such, * we will typically want to interact with that master for global properties. * @method _fnGetMasterSettings * @returns {Object} TableTools settings object * @private */ "_fnGetMasterSettings": function () { if ( this.s.master ) { return this.s; } else { /* Look for the master which has the same DT as this one */ var instances = TableTools._aInstances; for ( var i=0, iLen=instances.length ; i<iLen ; i++ ) { if ( this.dom.table == instances[i].s.dt.nTable ) { return instances[i].s; } } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button collection functions */ /** * Create a collection button, when activated will present a drop down list of other buttons * @param {Node} nButton Button to use for the collection activation * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionConfig": function ( nButton, oConfig ) { var nHidden = document.createElement( this.s.tags.collection.container ); nHidden.style.display = "none"; nHidden.className = this.classes.collection.container; oConfig._collection = nHidden; document.body.appendChild( nHidden ); this._fnButtonDefinations( oConfig.aButtons, nHidden ); }, /** * Show a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionShow": function ( nButton, oConfig ) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX+"px"; nHidden.style.top = iDivY+"px"; nHidden.style.display = "block"; $(nHidden).css('opacity',0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity',0); document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } if ( iDivY + iDivHeight > iDocHeight ) { nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10 ); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); }, /** * Hide a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionHide": function ( nButton, oConfig ) { if ( oConfig !== null && oConfig.sExtends == 'collection' ) { return; } if ( this.dom.collection.collection !== null ) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; } ); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild( this ); } ); this.dom.collection.collection = null; this.dom.collection.background = null; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Row selection functions */ /** * Add event handlers to a table to allow for row selection * @method _fnRowSelectConfig * @returns void * @private */ "_fnRowSelectConfig": function () { if ( this.s.master ) { var that = this, i, iLen, dt = this.s.dt, aoOpenRows = this.s.dt.aoOpenRows; $(dt.nTable).addClass( this.classes.select.table ); $('tr', dt.nTBody).live( 'click', function(e) { /* Sub-table must be ignored (odd that the selector won't do this with >) */ if ( this.parentNode != dt.nTBody ) { return; } /* Check that we are actually working with a DataTables controlled row */ if ( dt.oInstance.fnGetData(this) === null ) { return; } /* User defined selection function */ if ( that.s.select.preRowSelect !== null && !that.s.select.preRowSelect.call(that, e) ) { return; } if ( that.fnIsSelected( this ) ) { that._fnRowDeselect( this ); } else if ( that.s.select.type == "single" ) { that.fnSelectNone(); that._fnRowSelect( this ); } else if ( that.s.select.type == "multi" ) { that._fnRowSelect( this ); } } ); // Bind a listener to the DataTable for when new rows are created. // This allows rows to be visually selected when they should be and // deferred rendering is used. dt.oApi._fnCallbackReg( dt, 'aoRowCreatedCallback', function (tr, data, index) { if ( dt.aoData[index]._DTTT_selected ) { $(tr).addClass( that.classes.select.row ); } }, 'TableTools-SelectAll' ); } }, /** * Select rows * @param {*} src Rows to select - see _fnSelectData for a description of valid inputs * @private */ "_fnRowSelect": function ( src ) { var data = this._fnSelectData( src ); var firstTr = data.length===0 ? null : data[0].nTr; for ( var i=0, iLen=data.length ; i<iLen ; i++ ) { data[i]._DTTT_selected = true; if ( data[i].nTr ) { $(data[i].nTr).addClass( this.classes.select.row ); } } if ( this.s.select.postSelected !== null ) { this.s.select.postSelected.call( this, firstTr ); } TableTools._fnEventDispatch( this, 'select', firstTr ); }, /** * Deselect rows * @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs * @private */ "_fnRowDeselect": function ( src ) { var data = this._fnSelectData( src ); var firstTr = data.length===0 ? null : data[0].nTr; for ( var i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i].nTr && data[i]._DTTT_selected ) { $(data[i].nTr).removeClass( this.classes.select.row ); } data[i]._DTTT_selected = false; } if ( this.s.select.postDeselected !== null ) { this.s.select.postDeselected.call( this, firstTr ); } TableTools._fnEventDispatch( this, 'select', firstTr ); }, /** * Take a data source for row selection and convert it into aoData points for the DT * @param {*} src Can be a single DOM TR node, an array of TR nodes (including a * a jQuery object), a single aoData point from DataTables, an array of aoData * points or an array of aoData indexes * @returns {array} An array of aoData points */ "_fnSelectData": function ( src ) { var out = [], pos, i, iLen; if ( src.nodeName ) { // Single node pos = this.s.dt.oInstance.fnGetPosition( src ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src.length !== 'undefined' ) { // jQuery object or an array of nodes, or aoData points for ( i=0, iLen=src.length ; i<iLen ; i++ ) { if ( src[i].nodeName ) { pos = this.s.dt.oInstance.fnGetPosition( src[i] ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src[i] === 'number' ) { out.push( this.s.dt.aoData[ src[i] ] ); } else { out.push( src[i] ); } } return out; } else { // A single aoData point out.push( src ); } return out; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Text button functions */ /** * Configure a text based button for interaction events * @method _fnTextConfig * @param {Node} nButton Button element which is being considered * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnTextConfig": function ( nButton, oConfig ) { var that = this; if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } if ( oConfig.sToolTip !== "" ) { nButton.title = oConfig.sToolTip; } $(nButton).hover( function () { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( this, nButton, oConfig, null ); } }, function () { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( this, nButton, oConfig, null ); } } ); if ( oConfig.fnSelect !== null ) { TableTools._fnEventListen( this, 'select', function (n) { oConfig.fnSelect.call( that, nButton, oConfig, n ); } ); } $(nButton).click( function (e) { //e.preventDefault(); if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, null ); } /* Provide a complete function to match the behaviour of the flash elements */ if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, null, null ); } that._fnCollectionHide( nButton, oConfig ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Flash button functions */ /** * Configure a flash based button for interaction events * @method _fnFlashConfig * @param {Node} nButton Button element which is being considered * @param {o} oConfig Button configuration object * @returns void * @private */ "_fnFlashConfig": function ( nButton, oConfig ) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } flash.setHandCursor( true ); if ( oConfig.sAction == "flash_save" ) { flash.setAction( 'save' ); flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' ); flash.setBomInc( oConfig.bBomInc ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else if ( oConfig.sAction == "flash_pdf" ) { flash.setAction( 'pdf' ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else { flash.setAction( 'copy' ); } flash.addEventListener('mouseOver', function(client) { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseOut', function(client) { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseDown', function(client) { if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('complete', function (client, text) { if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, flash, text ); } that._fnCollectionHide( nButton, oConfig ); } ); this._fnFlashGlue( flash, nButton, oConfig.sToolTip ); }, /** * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call * itself (using setTimeout) until it completes successfully * @method _fnFlashGlue * @param {Object} clip Zero clipboard object * @param {Node} node node to glue swf to * @param {String} text title of the flash movie * @returns void * @private */ "_fnFlashGlue": function ( flash, node, text ) { var that = this; var id = node.getAttribute('id'); if ( document.getElementById(id) ) { flash.glue( node, text ); } else { setTimeout( function () { that._fnFlashGlue( flash, node, text ); }, 100 ); } }, /** * Set the text for the flash clip to deal with * * This function is required for large information sets. There is a limit on the * amount of data that can be transferred between Javascript and Flash in a single call, so * we use this method to build up the text in Flash by sending over chunks. It is estimated * that the data limit is around 64k, although it is undocumented, and appears to be different * between different flash versions. We chunk at 8KiB. * @method _fnFlashSetText * @param {Object} clip the ZeroClipboard object * @param {String} sData the data to be set * @returns void * @private */ "_fnFlashSetText": function ( clip, sData ) { var asData = this._fnChunkData( sData, 8192 ); clip.clearText(); for ( var i=0, iLen=asData.length ; i<iLen ; i++ ) { clip.appendText( asData[i] ); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Data retrieval functions */ /** * Convert the mixed columns variable into a boolean array the same size as the columns, which * indicates which columns we want to include * @method _fnColumnTargets * @param {String|Array} mColumns The columns to be included in data retrieval. If a string * then it can take the value of "visible" or "hidden" (to include all visible or * hidden columns respectively). Or an array of column indexes * @returns {Array} A boolean array the length of the columns of the table, which each value * indicating if the column is to be included or not * @private */ "_fnColumnTargets": function ( mColumns ) { var aColumns = []; var dt = this.s.dt; if ( typeof mColumns == "object" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( false ); } for ( i=0, iLen=mColumns.length ; i<iLen ; i++ ) { aColumns[ mColumns[i] ] = true; } } else if ( mColumns == "visible" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? true : false ); } } else if ( mColumns == "hidden" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? false : true ); } } else if ( mColumns == "sortable" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bSortable ? true : false ); } } else /* all */ { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( true ); } } return aColumns; }, /** * New line character(s) depend on the platforms * @method method * @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine * @returns {String} Newline character */ "_fnNewline": function ( oConfig ) { if ( oConfig.sNewLine == "auto" ) { return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"; } else { return oConfig.sNewLine; } }, /** * Get data from DataTables' internals and format it for output * @method _fnGetDataTablesData * @param {Object} oConfig Button configuration object * @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string * @param {String} oConfig.sFieldSeperator Field separator for the data cells * @param {String} oConfig.sNewline New line options * @param {Mixed} oConfig.mColumns Which columns should be included in the output * @param {Boolean} oConfig.bHeader Include the header * @param {Boolean} oConfig.bFooter Include the footer * @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output * @returns {String} Concatenated string of data * @private */ "_fnGetDataTablesData": function ( oConfig ) { var i, iLen, j, jLen; var aRow, aData=[], sLoopData='', arr; var dt = this.s.dt, tr, child; var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */ var aColumnsInc = this._fnColumnTargets( oConfig.mColumns ); var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false; /* * Header */ if ( oConfig.bHeader ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g," ").replace( /<.*?>/g, "" ).replace(/^\s+|\s+$/g,""); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } /* * Body */ var aDataIndex = dt.aiDisplay; var aSelected = this.fnGetSelected(); if ( this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0 ) { aDataIndex = []; for ( i=0, iLen=aSelected.length ; i<iLen ; i++ ) { aDataIndex.push( dt.oInstance.fnGetPosition( aSelected[i] ) ); } } for ( j=0, jLen=aDataIndex.length ; j<jLen ; j++ ) { tr = dt.aoData[ aDataIndex[j] ].nTr; aRow = []; /* Columns */ for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { /* Convert to strings (with small optimisation) */ var mTypeData = dt.oApi._fnGetCellData( dt, aDataIndex[j], i, 'display' ); if ( oConfig.fnCellRender ) { sLoopData = oConfig.fnCellRender( mTypeData, i, tr, aDataIndex[j] )+""; } else if ( typeof mTypeData == "string" ) { /* Strip newlines, replace img tags with alt attr. and finally strip html... */ sLoopData = mTypeData.replace(/\n/g," "); sLoopData = sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi, '$1$2$3'); sLoopData = sLoopData.replace( /<.*?>/g, "" ); } else { sLoopData = mTypeData+""; } /* Trim and clean the data */ sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, ''); sLoopData = this._fnHtmlDecode( sLoopData ); /* Bound it and add it to the total data */ aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); /* Details rows from fnOpen */ if ( oConfig.bOpenRows ) { arr = $.grep(dt.aoOpenRows, function(o) { return o.nParent === tr; }); if ( arr.length === 1 ) { sLoopData = this._fnBoundData( $('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex ); aData.push( sLoopData ); } } } /* * Footer */ if ( oConfig.bFooter && dt.nTFoot !== null ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] && dt.aoColumns[i].nTf !== null ) { sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g," ").replace( /<.*?>/g, "" ); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } _sLastData = aData.join( this._fnNewline(oConfig) ); return _sLastData; }, /** * Wrap data up with a boundary string * @method _fnBoundData * @param {String} sData data to bound * @param {String} sBoundary bounding char(s) * @param {RegExp} regex search for the bounding chars - constructed outside for efficiency * in the loop * @returns {String} bound data * @private */ "_fnBoundData": function ( sData, sBoundary, regex ) { if ( sBoundary === "" ) { return sData; } else { return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary; } }, /** * Break a string up into an array of smaller strings * @method _fnChunkData * @param {String} sData data to be broken up * @param {Int} iSize chunk size * @returns {Array} String array of broken up text * @private */ "_fnChunkData": function ( sData, iSize ) { var asReturn = []; var iStrlen = sData.length; for ( var i=0 ; i<iStrlen ; i+=iSize ) { if ( i+iSize < iStrlen ) { asReturn.push( sData.substring( i, i+iSize ) ); } else { asReturn.push( sData.substring( i, iStrlen ) ); } } return asReturn; }, /** * Decode HTML entities * @method _fnHtmlDecode * @param {String} sData encoded string * @returns {String} decoded string * @private */ "_fnHtmlDecode": function ( sData ) { if ( sData.indexOf('&') == -1 ) { return sData; } var aData = this._fnChunkData( sData, 2048 ), n = document.createElement('div'), i, iLen, iIndex, sReturn = "", sInner; /* nodeValue has a limit in browsers - so we chunk the data into smaller segments to build * up the string. Note that the 'trick' here is to remember than we might have split over * an HTML entity, so we backtrack a little to make sure this doesn't happen */ for ( i=0, iLen=aData.length ; i<iLen ; i++ ) { /* Magic number 8 is because no entity is longer then strlen 8 in ISO 8859-1 */ iIndex = aData[i].lastIndexOf( '&' ); if ( iIndex != -1 && aData[i].length >= 8 && iIndex > aData[i].length - 8 ) { sInner = aData[i].substr( iIndex ); aData[i] = aData[i].substr( 0, iIndex ); } n.innerHTML = aData[i]; sReturn += n.childNodes[0].nodeValue; } return sReturn; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Printing functions */ /** * Show print display * @method _fnPrintStart * @param {Event} e Event object * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnPrintStart": function ( oConfig ) { var that = this; var oSetDT = this.s.dt; /* Parse through the DOM hiding everything that isn't needed for the table */ this._fnPrintHideNodes( oSetDT.nTable ); /* Show the whole table */ this.s.print.saveStart = oSetDT._iDisplayStart; this.s.print.saveLength = oSetDT._iDisplayLength; if ( oConfig.bShowAll ) { oSetDT._iDisplayStart = 0; oSetDT._iDisplayLength = -1; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); } /* Adjust the display for scrolling which might be done by DataTables */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollStart( oSetDT ); } /* Remove the other DataTables feature nodes - but leave the table! and info div */ var anFeature = oSetDT.aanFeatures; for ( var cFeature in anFeature ) { if ( cFeature != 'i' && cFeature != 't' && cFeature.length == 1 ) { for ( var i=0, iLen=anFeature[cFeature].length ; i<iLen ; i++ ) { this.dom.print.hidden.push( { "node": anFeature[cFeature][i], "display": "block" } ); anFeature[cFeature][i].style.display = "none"; } } } /* Print class can be used for styling */ $(document.body).addClass( this.classes.print.body ); /* Show information message to let the user know what is happening */ if ( oConfig.sInfo !== "" ) { this.fnInfo( oConfig.sInfo, 3000 ); } /* Add a message at the top of the page */ if ( oConfig.sMessage ) { this.dom.print.message = document.createElement( "div" ); this.dom.print.message.className = this.classes.print.message; this.dom.print.message.innerHTML = oConfig.sMessage; document.body.insertBefore( this.dom.print.message, document.body.childNodes[0] ); } /* Cache the scrolling and the jump to the top of the page */ this.s.print.saveScroll = $(window).scrollTop(); window.scrollTo( 0, 0 ); /* Bind a key event listener to the document for the escape key - * it is removed in the callback */ $(document).bind( "keydown.DTTT", function(e) { /* Only interested in the escape key */ if ( e.keyCode == 27 ) { e.preventDefault(); that._fnPrintEnd.call( that, e ); } } ); }, /** * Printing is finished, resume normal display * @method _fnPrintEnd * @param {Event} e Event object * @returns void * @private */ "_fnPrintEnd": function ( e ) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo( 0, oSetPrint.saveScroll ); /* Drop the print message */ if ( oDomPrint.message !== null ) { document.body.removeChild( oDomPrint.message ); oDomPrint.message = null; } /* Styling class */ $(document.body).removeClass( 'DTTT_Print' ); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); $(document).unbind( "keydown.DTTT" ); }, /** * Take account of scrolling in DataTables by showing the full table * @returns void * @private */ "_fnPrintScrollStart": function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ var nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { oSetDT.nTable.removeChild( nTheadSize[0] ); } if ( oSetDT.nTFoot !== null ) { var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { oSetDT.nTable.removeChild( nTfootSize[0] ); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] ); if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] ); } /* Now adjust the table's viewport so we can actually see it */ if ( oSetDT.oScroll.sX !== "" ) { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.overflow = "visible"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px"; nScrollBody.style.overflow = "visible"; } }, /** * Take account of scrolling in DataTables by showing the full table. Note that the redraw of * the DataTable that we do will actually deal with the majority of the hard work here * @returns void * @private */ "_fnPrintScrollEnd": function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if ( oSetDT.oScroll.sX !== "" ) { nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX ); nScrollBody.style.overflow = "auto"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY ); nScrollBody.style.overflow = "auto"; } }, /** * Resume the display of all TableTools hidden nodes * @method _fnPrintShowNodes * @returns void * @private */ "_fnPrintShowNodes": function ( ) { var anHidden = this.dom.print.hidden; for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ ) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice( 0, anHidden.length ); }, /** * Hide nodes which are not needed in order to display the table. Note that this function is * recursive * @method _fnPrintHideNodes * @param {Node} nNode Element which should be showing in a 'print' display * @returns void * @private */ "_fnPrintHideNodes": function ( nNode ) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ ) { if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 ) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if ( sDisplay != "none" ) { /* Cache the node and it's previous state so we can restore it */ anHidden.push( { "node": nChildren[i], "display": sDisplay } ); nChildren[i].style.display = "none"; } } } if ( nParent.nodeName != "BODY" ) { this._fnPrintHideNodes( nParent ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Store of all instances that have been created of TableTools, so one can look up other (when * there is need of a master) * @property _aInstances * @type Array * @default [] * @private */ TableTools._aInstances = []; /** * Store of all listeners and their callback functions * @property _aListeners * @type Array * @default [] */ TableTools._aListeners = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get an array of all the master instances * @method fnGetMasters * @returns {Array} List of master TableTools instances * @static */ TableTools.fnGetMasters = function () { var a = []; for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master ) { a.push( TableTools._aInstances[i] ); } } return a; }; /** * Get the master instance for a table node (or id if a string is given) * @method fnGetInstance * @returns {Object} ID of table OR table node, for which we want the TableTools instance * @static */ TableTools.fnGetInstance = function ( node ) { if ( typeof node != 'object' ) { node = document.getElementById(node); } for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node ) { return TableTools._aInstances[i]; } } return null; }; /** * Add a listener for a specific event * @method _fnEventListen * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Function} fn Function * @returns void * @private * @static */ TableTools._fnEventListen = function ( that, type, fn ) { TableTools._aListeners.push( { "that": that, "type": type, "fn": fn } ); }; /** * An event has occurred - look up every listener and fire it off. We check that the event we are * going to fire is attached to the same table (using the table node as reference) before firing * @method _fnEventDispatch * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Node} node Element that the event occurred on (may be null) * @returns void * @private * @static */ TableTools._fnEventDispatch = function ( that, type, node ) { var listeners = TableTools._aListeners; for ( var i=0, iLen=listeners.length ; i<iLen ; i++ ) { if ( that.dom.table == listeners[i].that.dom.table && listeners[i].type == type ) { listeners[i].fn( node ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TableTools.buttonBase = { // Button base "sAction": "text", "sTag": "default", "sLinerTag": "default", "sButtonClass": "DTTT_button_text", "sButtonText": "Button text", "sTitle": "", "sToolTip": "", // Common button specific options "sCharSet": "utf8", "bBomInc": false, "sFileName": "*.csv", "sFieldBoundary": "", "sFieldSeperator": "\t", "sNewLine": "auto", "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */ "bHeader": true, "bFooter": true, "bOpenRows": false, "bSelectedOnly": false, // Callbacks "fnMouseover": null, "fnMouseout": null, "fnClick": null, "fnSelect": null, "fnComplete": null, "fnInit": null, "fnCellRender": null }; /** * @namespace Default button configurations */ TableTools.BUTTONS = { "csv": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sButtonClass": "DTTT_button_csv", "sButtonText": "CSV", "sFieldBoundary": '"', "sFieldSeperator": ",", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "xls": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sCharSet": "utf16le", "bBomInc": true, "sButtonClass": "DTTT_button_xls", "sButtonText": "Excel", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "copy": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_copy", "sButtonClass": "DTTT_button_copy", "sButtonText": "Copy", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); }, "fnComplete": function(nButton, oConfig, flash, text) { var lines = text.split('\n').length, len = this.s.dt.nTFoot === null ? lines-1 : lines-2, plural = (len==1) ? "" : "s"; this.fnInfo( '<h6>Table copied</h6>'+ '<p>Copied '+len+' row'+plural+' to the clipboard.</p>', 1500 ); } } ), "pdf": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_pdf", "sNewLine": "\n", "sFileName": "*.pdf", "sButtonClass": "DTTT_button_pdf", "sButtonText": "PDF", "sPdfOrientation": "portrait", "sPdfSize": "A4", "sPdfMessage": "", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, "title:"+ this.fnGetTitle(oConfig) +"\n"+ "message:"+ oConfig.sPdfMessage +"\n"+ "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+ "orientation:"+ oConfig.sPdfOrientation +"\n"+ "size:"+ oConfig.sPdfSize +"\n"+ "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } } ), "print": $.extend( {}, TableTools.buttonBase, { "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to "+ "print this table. Press escape when finished.", "sMessage": null, "bShowAll": true, "sToolTip": "View print view", "sButtonClass": "DTTT_button_print", "sButtonText": "Print", "fnClick": function ( nButton, oConfig ) { this.fnPrint( true, oConfig ); } } ), "text": $.extend( {}, TableTools.buttonBase ), "select": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_single": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { var iSelected = this.fnGetSelected().length; if ( iSelected == 1 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_all": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select all", "fnClick": function( nButton, oConfig ) { this.fnSelectAll(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length == this.s.dt.fnRecordsDisplay() ) { $(nButton).addClass( this.classes.buttons.disabled ); } else { $(nButton).removeClass( this.classes.buttons.disabled ); } } } ), "select_none": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Deselect all", "fnClick": function( nButton, oConfig ) { this.fnSelectNone(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "ajax": $.extend( {}, TableTools.buttonBase, { "sAjaxUrl": "/xhr.php", "sButtonText": "Ajax button", "fnClick": function( nButton, oConfig ) { var sData = this.fnGetTableData(oConfig); $.ajax( { "url": oConfig.sAjaxUrl, "data": [ { "name": "tableData", "value": sData } ], "success": oConfig.fnAjaxComplete, "dataType": "json", "type": "POST", "cache": false, "error": function () { alert( "Error detected when sending table data to server" ); } } ); }, "fnAjaxComplete": function( json ) { alert( 'Ajax complete' ); } } ), "div": $.extend( {}, TableTools.buttonBase, { "sAction": "div", "sTag": "div", "sButtonClass": "DTTT_nonbutton", "sButtonText": "Text button" } ), "collection": $.extend( {}, TableTools.buttonBase, { "sAction": "collection", "sButtonClass": "DTTT_button_collection", "sButtonText": "Collection", "fnClick": function( nButton, oConfig ) { this._fnCollectionShow(nButton, oConfig); } } ) }; /* * on* callback parameters: * 1. node - button element * 2. object - configuration object for this button * 3. object - ZeroClipboard reference (flash button only) * 4. string - Returned string from Flash (flash button only - and only on 'complete') */ /** * @namespace Classes used by TableTools - allows the styles to be override easily. * Note that when TableTools initialises it will take a copy of the classes object * and will use its internal copy for the remainder of its run time. */ TableTools.classes = { "container": "DTTT_container", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" }, "collection": { "container": "DTTT_collection", "background": "DTTT_collection_background", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" } }, "select": { "table": "DTTT_selectable", "row": "DTTT_selected" }, "print": { "body": "DTTT_Print", "info": "DTTT_print_info", "message": "DTTT_PrintMessage" } }; /** * @namespace ThemeRoller classes - built in for compatibility with DataTables' * bJQueryUI option. */ TableTools.classes_themeroller = { "container": "DTTT_container ui-buttonset ui-buttonset-multi", "buttons": { "normal": "DTTT_button ui-button ui-state-default" }, "collection": { "container": "DTTT_collection ui-buttonset ui-buttonset-multi" } }; /** * @namespace TableTools default settings for initialisation */ TableTools.DEFAULTS = { "sSwfPath": "media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "none", "sSelectedClass": null, "fnPreRowSelect": null, "fnRowSelected": null, "fnRowDeselected": null, "aButtons": [ "copy", "csv", "xls", "pdf", "print" ], "oTags": { "container": "div", "button": "a", // We really want to use buttons here, but Firefox and IE ignore the // click on the Flash element in the button (but not mouse[in|out]). "liner": "span", "collection": { "container": "div", "button": "a", "liner": "span" } } }; /** * Name of this class * @constant CLASS * @type String * @default TableTools */ TableTools.prototype.CLASS = "TableTools"; /** * TableTools version * @constant VERSION * @type String * @default See code */ TableTools.VERSION = "2.1.3"; TableTools.prototype.VERSION = TableTools.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ? oDTSettings.oInit.oTableTools : {}; var oTT = new TableTools( oDTSettings.oInstance, oOpts ); TableTools._aInstances.push( oTT ); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" } ); } else { alert( "Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.DataTable.TableTools = TableTools; })(jQuery, window, document);
JavaScript
// Simple Set Clipboard System // Author: Joseph Huckaby var ZeroClipboard_TableTools = { version: "1.0.4-TableTools2", clients: {}, // registered upload clients on page, indexed by id moviePath: '', // URL to movie nextId: 1, // ID of next movie $: function(thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function() { this.style.display = 'none'; }; thingy.show = function() { this.style.display = ''; }; thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function(name) { this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, ''); }; thingy.hasClass = function(name) { return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); } } return thingy; }, setMoviePath: function(path) { // set path to ZeroClipboard.swf this.moviePath = path; }, dispatch: function(id, eventName, args) { // receive event from flash movie, send to client var client = this.clients[id]; if (client) { client.receiveEvent(eventName, args); } }, register: function(id, client) { // register new client to receive events this.clients[id] = client; }, getDOMObjectPosition: function(obj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: obj.width ? obj.width : obj.offsetWidth, height: obj.height ? obj.height : obj.offsetHeight }; if ( obj.style.width != "" ) info.width = obj.style.width.replace("px",""); if ( obj.style.height != "" ) info.height = obj.style.height.replace("px",""); while (obj) { info.left += obj.offsetLeft; info.top += obj.offsetTop; obj = obj.offsetParent; } return info; }, Client: function(elem) { // constructor for new simple upload client this.handlers = {}; // unique ID this.id = ZeroClipboard_TableTools.nextId++; this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id; // register client with singleton to receive flash events ZeroClipboard_TableTools.register(this.id, this); // create movie if (elem) this.glue(elem); } }; ZeroClipboard_TableTools.Client.prototype = { id: 0, // unique ID for us ready: false, // whether movie is ready to receive events or not movie: null, // reference to movie object clipText: '', // text to copy to clipboard fileName: '', // default file save name action: 'copy', // action to perform handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor cssEffects: true, // enable CSS mouse effects on dom container handlers: null, // user event handlers sized: false, glue: function(elem, title) { // glue to DOM element // elem can be ID or actual DOM element object this.domElement = ZeroClipboard_TableTools.$(elem); // float just above object, or zIndex 99 if dom element isn't set var zIndex = 99; if (this.domElement.style.zIndex) { zIndex = parseInt(this.domElement.style.zIndex) + 1; } // find X/Y position of domElement var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); // create floating DIV above element this.div = document.createElement('div'); var style = this.div.style; style.position = 'absolute'; style.left = '0px'; style.top = '0px'; style.width = (box.width) + 'px'; style.height = box.height + 'px'; style.zIndex = zIndex; if ( typeof title != "undefined" && title != "" ) { this.div.title = title; } if ( box.width != 0 && box.height != 0 ) { this.sized = true; } // style.backgroundColor = '#f00'; // debug if ( this.domElement ) { this.domElement.appendChild(this.div); this.div.innerHTML = this.getHTML( box.width, box.height ); } }, positionElement: function() { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.position = 'absolute'; //style.left = (this.domElement.offsetLeft)+'px'; //style.top = this.domElement.offsetTop+'px'; style.width = box.width + 'px'; style.height = box.height + 'px'; if ( box.width != 0 && box.height != 0 ) { this.sized = true; } else { return; } var flash = this.div.childNodes[0]; flash.width = box.width; flash.height = box.height; }, getHTML: function(width, height) { // return HTML for movie var html = ''; var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard_TableTools.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>'; } else { // all other browsers get an EMBED tag html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard_TableTools.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />'; } return html; }, hide: function() { // temporarily hide floater offscreen if (this.div) { this.div.style.left = '-2000px'; } }, show: function() { // show ourselves after a call to hide() this.reposition(); }, destroy: function() { // destroy control and floater if (this.domElement && this.div) { this.hide(); this.div.innerHTML = ''; var body = document.getElementsByTagName('body')[0]; try { body.removeChild( this.div ); } catch(e) {;} this.domElement = null; this.div = null; } }, reposition: function(elem) { // reposition our floating div, optionally to new container // warning: container CANNOT change size, only position if (elem) { this.domElement = ZeroClipboard_TableTools.$(elem); if (!this.domElement) this.hide(); } if (this.domElement && this.div) { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; } }, clearText: function() { // clear the text to be copy / saved this.clipText = ''; if (this.ready) this.movie.clearText(); }, appendText: function(newText) { // append text to that which is to be copied / saved this.clipText += newText; if (this.ready) { this.movie.appendText(newText) ;} }, setText: function(newText) { // set text to be copied to be copied / saved this.clipText = newText; if (this.ready) { this.movie.setText(newText) ;} }, setCharSet: function(charSet) { // set the character set (UTF16LE or UTF8) this.charSet = charSet; if (this.ready) { this.movie.setCharSet(charSet) ;} }, setBomInc: function(bomInc) { // set if the BOM should be included or not this.incBom = bomInc; if (this.ready) { this.movie.setBomInc(bomInc) ;} }, setFileName: function(newText) { // set the file name this.fileName = newText; if (this.ready) this.movie.setFileName(newText); }, setAction: function(newText) { // set action (save or copy) this.action = newText; if (this.ready) this.movie.setAction(newText); }, addEventListener: function(eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel eventName = eventName.toString().toLowerCase().replace(/^on/, ''); if (!this.handlers[eventName]) this.handlers[eventName] = []; this.handlers[eventName].push(func); }, setHandCursor: function(enabled) { // enable hand cursor (true), or default arrow cursor (false) this.handCursorEnabled = enabled; if (this.ready) this.movie.setHandCursor(enabled); }, setCSSEffects: function(enabled) { // enable or disable CSS effects on DOM container this.cssEffects = !!enabled; }, receiveEvent: function(eventName, args) { // receive event from flash eventName = eventName.toString().toLowerCase().replace(/^on/, ''); // special behavior for certain events switch (eventName) { case 'load': // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 1 ); return; } // firefox on pc needs a "kick" in order to set these in certain cases if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 100 ); this.ready = true; return; } this.ready = true; this.movie.clearText(); this.movie.appendText( this.clipText ); this.movie.setFileName( this.fileName ); this.movie.setAction( this.action ); this.movie.setCharSet( this.charSet ); this.movie.setBomInc( this.incBom ); this.movie.setHandCursor( this.handCursorEnabled ); break; case 'mouseover': if (this.domElement && this.cssEffects) { //this.domElement.addClass('hover'); if (this.recoverActive) this.domElement.addClass('active'); } break; case 'mouseout': if (this.domElement && this.cssEffects) { this.recoverActive = false; if (this.domElement.hasClass('active')) { this.domElement.removeClass('active'); this.recoverActive = true; } //this.domElement.removeClass('hover'); } break; case 'mousedown': if (this.domElement && this.cssEffects) { this.domElement.addClass('active'); } break; case 'mouseup': if (this.domElement && this.cssEffects) { this.domElement.removeClass('active'); this.recoverActive = false; } break; } // switch eventName if (this.handlers[eventName]) { for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; if (typeof(func) == 'function') { // actual function reference func(this, args); } else if ((typeof(func) == 'object') && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][ func[1] ](this, args); } else if (typeof(func) == 'string') { // name of function window[func](this, args); } } // foreach event handler defined } // user defined handler for event } };
JavaScript
/* * File: ColVis.js * Version: 1.0.8 * CVS: $Id$ * Description: Controls for column visiblity in DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Created: Wed Sep 15 18:23:29 BST 2010 * Modified: $Date$ by $Author$ * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: Just a little bit of fun :-) * Contact: www.sprymedia.co.uk/contact * * Copyright 2010-2011 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd */ (function($) { /** * ColVis provides column visiblity control for DataTables * @class ColVis * @constructor * @param {object} DataTables settings object */ ColVis = function( oDTSettings, oInit ) { /* Santiy check that we are a new instance */ if ( !this.CLASS || this.CLASS != "ColVis" ) { alert( "Warning: ColVis must be initialised with the keyword 'new'" ); } if ( typeof oInit == 'undefined' ) { oInit = {}; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for ColVis instance */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Customisation object * @property oInit * @type Object * @default passed in */ "oInit": oInit, /** * Callback function to tell the user when the state has changed * @property fnStateChange * @type function * @default null */ "fnStateChange": null, /** * Mode of activation. Can be 'click' or 'mouseover' * @property activate * @type String * @default click */ "activate": "click", /** * Position of the collection menu when shown - align "left" or "right" * @property sAlign * @type String * @default right */ "sAlign": "left", /** * Text used for the button * @property buttonText * @type String * @default Show / hide columns */ "buttonText": "Show / hide columns", /** * Flag to say if the collection is hidden * @property hidden * @type boolean * @default true */ "hidden": true, /** * List of columns (integers) which should be excluded from the list * @property aiExclude * @type Array * @default [] */ "aiExclude": [], /** * Store the original viisbility settings so they could be restored * @property abOriginal * @type Array * @default [] */ "abOriginal": [], /** * Show Show-All button * @property bShowAll * @type Array * @default [] */ "bShowAll": false, /** * Show All button text * @property sShowAll * @type String * @default Restore original */ "sShowAll": "Show All", /** * Show restore button * @property bRestore * @type Array * @default [] */ "bRestore": false, /** * Restore button text * @property sRestore * @type String * @default Restore original */ "sRestore": "Restore original", /** * Overlay animation duration in mS * @property iOverlayFade * @type Integer * @default 500 */ "iOverlayFade": 500, /** * Label callback for column names. Takes three parameters: 1. the column index, 2. the column * title detected by DataTables and 3. the TH node for the column * @property fnLabel * @type Function * @default null */ "fnLabel": null, /** * Indicate if ColVis should automatically calculate the size of buttons or not. The default * is for it to do so. Set to "css" to disable the automatic sizing * @property sSize * @type String * @default auto */ "sSize": "auto", /** * Indicate if the column list should be positioned by Javascript, visually below the button * or allow CSS to do the positioning * @property bCssPosition * @type boolean * @default false */ "bCssPosition": false }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Wrapper for the button - given back to DataTables as the node to insert * @property wrapper * @type Node * @default null */ "wrapper": null, /** * Activation button * @property button * @type Node * @default null */ "button": null, /** * Collection list node * @property collection * @type Node * @default null */ "collection": null, /** * Background node used for shading the display and event capturing * @property background * @type Node * @default null */ "background": null, /** * Element to position over the activation button to catch mouse events when using mouseover * @property catcher * @type Node * @default null */ "catcher": null, /** * List of button elements * @property buttons * @type Array * @default [] */ "buttons": [], /** * Restore button * @property restore * @type Node * @default null */ "restore": null }; /* Store global reference */ ColVis.aInstances.push( this ); /* Constructor logic */ this.s.dt = oDTSettings; this._fnConstruct(); return this; }; ColVis.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Rebuild the list of buttons for this instance (i.e. if there is a column header update) * @method fnRebuild * @returns void */ "fnRebuild": function () { /* Remove the old buttons */ for ( var i=this.dom.buttons.length-1 ; i>=0 ; i-- ) { if ( this.dom.buttons[i] !== null ) { this.dom.collection.removeChild( this.dom.buttons[i] ); } } this.dom.buttons.splice( 0, this.dom.buttons.length ); if ( this.dom.restore ) { this.dom.restore.parentNode( this.dom.restore ); } /* Re-add them (this is not the optimal way of doing this, it is fast and effective) */ this._fnAddButtons(); /* Update the checkboxes */ this._fnDrawCallback(); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @returns void * @private */ "_fnConstruct": function () { this._fnApplyCustomisation(); var that = this; var i, iLen; this.dom.wrapper = document.createElement('div'); this.dom.wrapper.className = "ColVis TableTools"; this.dom.button = this._fnDomBaseButton( this.s.buttonText ); this.dom.button.className += " ColVis_MasterButton"; this.dom.wrapper.appendChild( this.dom.button ); this.dom.catcher = this._fnDomCatcher(); this.dom.collection = this._fnDomCollection(); this.dom.background = this._fnDomBackground(); this._fnAddButtons(); /* Store the original visbility information */ for ( i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ ) { this.s.abOriginal.push( this.s.dt.aoColumns[i].bVisible ); } /* Update on each draw */ this.s.dt.aoDrawCallback.push( { "fn": function () { that._fnDrawCallback.call( that ); }, "sName": "ColVis" } ); /* If columns are reordered, then we need to update our exclude list and * rebuild the displayed list */ $(this.s.dt.oInstance).bind( 'column-reorder', function ( e, oSettings, oReorder ) { for ( i=0, iLen=that.s.aiExclude.length ; i<iLen ; i++ ) { that.s.aiExclude[i] = oReorder.aiInvertMapping[ that.s.aiExclude[i] ]; } var mStore = that.s.abOriginal.splice( oReorder.iFrom, 1 )[0]; that.s.abOriginal.splice( oReorder.iTo, 0, mStore ); that.fnRebuild(); } ); }, /** * Apply any customisation to the settings from the DataTables initialisation * @method _fnApplyCustomisation * @returns void * @private */ "_fnApplyCustomisation": function () { var oConfig = this.s.oInit; if ( typeof oConfig.activate != 'undefined' ) { this.s.activate = oConfig.activate; } if ( typeof oConfig.buttonText != 'undefined' ) { this.s.buttonText = oConfig.buttonText; } if ( typeof oConfig.aiExclude != 'undefined' ) { this.s.aiExclude = oConfig.aiExclude; } if ( typeof oConfig.bRestore != 'undefined' ) { this.s.bRestore = oConfig.bRestore; } if ( typeof oConfig.sRestore != 'undefined' ) { this.s.sRestore = oConfig.sRestore; } if ( typeof oConfig.bShowAll != 'undefined' ) { this.s.bShowAll = oConfig.bShowAll; } if ( typeof oConfig.sShowAll != 'undefined' ) { this.s.sShowAll = oConfig.sShowAll; } if ( typeof oConfig.sAlign != 'undefined' ) { this.s.sAlign = oConfig.sAlign; } if ( typeof oConfig.fnStateChange != 'undefined' ) { this.s.fnStateChange = oConfig.fnStateChange; } if ( typeof oConfig.iOverlayFade != 'undefined' ) { this.s.iOverlayFade = oConfig.iOverlayFade; } if ( typeof oConfig.fnLabel != 'undefined' ) { this.s.fnLabel = oConfig.fnLabel; } if ( typeof oConfig.sSize != 'undefined' ) { this.s.sSize = oConfig.sSize; } if ( typeof oConfig.bCssPosition != 'undefined' ) { this.s.bCssPosition = oConfig.bCssPosition; } }, /** * On each table draw, check the visibility checkboxes as needed. This allows any process to * update the table's column visibility and ColVis will still be accurate. * @method _fnDrawCallback * @returns void * @private */ "_fnDrawCallback": function () { var aoColumns = this.s.dt.aoColumns; for ( var i=0, iLen=aoColumns.length ; i<iLen ; i++ ) { if ( this.dom.buttons[i] !== null ) { if ( aoColumns[i].bVisible ) { $('input', this.dom.buttons[i]).attr('checked','checked'); } else { $('input', this.dom.buttons[i]).removeAttr('checked'); } } } }, /** * Loop through the columns in the table and as a new button for each one. * @method _fnAddButtons * @returns void * @private */ "_fnAddButtons": function () { var nButton, sExclude = ","+this.s.aiExclude.join(',')+","; for ( var i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ ) { if ( sExclude.indexOf( ","+i+"," ) == -1 ) { nButton = this._fnDomColumnButton( i ); this.dom.buttons.push( nButton ); this.dom.collection.appendChild( nButton ); } else { this.dom.buttons.push( null ); } } if ( this.s.bRestore ) { nButton = this._fnDomRestoreButton(); nButton.className += " ColVis_Restore"; this.dom.buttons.push( nButton ); this.dom.collection.appendChild( nButton ); } if ( this.s.bShowAll ) { nButton = this._fnDomShowAllButton(); nButton.className += " ColVis_ShowAll"; this.dom.buttons.push( nButton ); this.dom.collection.appendChild( nButton ); } }, /** * Create a button which allows a "restore" action * @method _fnDomRestoreButton * @returns {Node} Created button * @private */ "_fnDomRestoreButton": function () { var that = this, nButton = document.createElement('button'), nSpan = document.createElement('span'); nButton.className = !this.s.dt.bJUI ? "ColVis_Button TableTools_Button" : "ColVis_Button TableTools_Button ui-button ui-state-default"; nButton.appendChild( nSpan ); $(nSpan).html( '<span class="ColVis_title">'+this.s.sRestore+'</span>' ); $(nButton).click( function (e) { for ( var i=0, iLen=that.s.abOriginal.length ; i<iLen ; i++ ) { that.s.dt.oInstance.fnSetColumnVis( i, that.s.abOriginal[i], false ); } that._fnAdjustOpenRows(); that.s.dt.oInstance.fnAdjustColumnSizing( false ); that.s.dt.oInstance.fnDraw( false ); } ); return nButton; }, /** * Create a button which allows a "show all" action * @method _fnDomShowAllButton * @returns {Node} Created button * @private */ "_fnDomShowAllButton": function () { var that = this, nButton = document.createElement('button'), nSpan = document.createElement('span'); nButton.className = !this.s.dt.bJUI ? "ColVis_Button TableTools_Button" : "ColVis_Button TableTools_Button ui-button ui-state-default"; nButton.appendChild( nSpan ); $(nSpan).html( '<span class="ColVis_title">'+this.s.sShowAll+'</span>' ); $(nButton).click( function (e) { for ( var i=0, iLen=that.s.abOriginal.length ; i<iLen ; i++ ) { if (that.s.aiExclude.indexOf(i) === -1) { that.s.dt.oInstance.fnSetColumnVis( i, true, false ); } } that._fnAdjustOpenRows(); that.s.dt.oInstance.fnAdjustColumnSizing( false ); that.s.dt.oInstance.fnDraw( false ); } ); return nButton; }, /** * Create the DOM for a show / hide button * @method _fnDomColumnButton * @param {int} i Column in question * @returns {Node} Created button * @private */ "_fnDomColumnButton": function ( i ) { var that = this, oColumn = this.s.dt.aoColumns[i], nButton = document.createElement('button'), nSpan = document.createElement('span'), dt = this.s.dt; nButton.className = !dt.bJUI ? "ColVis_Button TableTools_Button" : "ColVis_Button TableTools_Button ui-button ui-state-default"; nButton.appendChild( nSpan ); var sTitle = this.s.fnLabel===null ? oColumn.sTitle : this.s.fnLabel( i, oColumn.sTitle, oColumn.nTh ); $(nSpan).html( '<span class="ColVis_radio"><input type="checkbox"/></span>'+ '<span class="ColVis_title">'+sTitle+'</span>' ); $(nButton).click( function (e) { var showHide = !$('input', this).is(":checked"); if ( e.target.nodeName.toLowerCase() == "input" ) { showHide = $('input', this).is(":checked"); } /* Need to consider the case where the initialiser created more than one table - change the * API index that DataTables is using */ var oldIndex = $.fn.dataTableExt.iApiIndex; $.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that); // Optimisation for server-side processing when scrolling - don't do a full redraw if ( dt.oFeatures.bServerSide && (dt.oScroll.sX !== "" || dt.oScroll.sY !== "" ) ) { that.s.dt.oInstance.fnSetColumnVis( i, showHide, false ); that.s.dt.oInstance.fnAdjustColumnSizing( false ); that.s.dt.oInstance.oApi._fnScrollDraw( that.s.dt ); that._fnDrawCallback(); } else { that.s.dt.oInstance.fnSetColumnVis( i, showHide ); } $.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */ if ( that.s.fnStateChange !== null ) { that.s.fnStateChange.call( that, i, showHide ); } } ); return nButton; }, /** * Get the position in the DataTables instance array of the table for this instance of ColVis * @method _fnDataTablesApiIndex * @returns {int} Index * @private */ "_fnDataTablesApiIndex": function () { for ( var i=0, iLen=this.s.dt.oInstance.length ; i<iLen ; i++ ) { if ( this.s.dt.oInstance[i] == this.s.dt.nTable ) { return i; } } return 0; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnDomBaseButton * @param {String} text Button text * @returns {Node} DIV element for the button * @private */ "_fnDomBaseButton": function ( text ) { var that = this, nButton = document.createElement('button'), nSpan = document.createElement('span'), sEvent = this.s.activate=="mouseover" ? "mouseover" : "click"; nButton.className = !this.s.dt.bJUI ? "ColVis_Button TableTools_Button" : "ColVis_Button TableTools_Button ui-button ui-state-default"; nButton.appendChild( nSpan ); nSpan.innerHTML = text; $(nButton).bind( sEvent, function (e) { that._fnCollectionShow(); e.preventDefault(); } ); return nButton; }, /** * Create the element used to contain list the columns (it is shown and hidden as needed) * @method _fnDomCollection * @returns {Node} div container for the collection * @private */ "_fnDomCollection": function () { var that = this; var nHidden = document.createElement('div'); nHidden.style.display = "none"; nHidden.className = !this.s.dt.bJUI ? "ColVis_collection TableTools_collection" : "ColVis_collection TableTools_collection ui-buttonset ui-buttonset-multi"; if ( !this.s.bCssPosition ) { nHidden.style.position = "absolute"; } $(nHidden).css('opacity', 0); return nHidden; }, /** * An element to be placed on top of the activate button to catch events * @method _fnDomCatcher * @returns {Node} div container for the collection * @private */ "_fnDomCatcher": function () { var that = this, nCatcher = document.createElement('div'); nCatcher.className = "ColVis_catcher TableTools_catcher"; $(nCatcher).click( function () { that._fnCollectionHide.call( that, null, null ); } ); return nCatcher; }, /** * Create the element used to shade the background, and capture hide events (it is shown and * hidden as needed) * @method _fnDomBackground * @returns {Node} div container for the background * @private */ "_fnDomBackground": function () { var that = this; var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.className = "ColVis_collectionBackground TableTools_collectionBackground"; $(nBackground).css('opacity', 0); $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); /* When considering a mouse over action for the activation, we also consider a mouse out * which is the same as a mouse over the background - without all the messing around of * bubbling events. Use the catcher element to avoid messing around with bubbling */ if ( this.s.activate == "mouseover" ) { $(nBackground).mouseover( function () { that.s.overcollection = false; that._fnCollectionHide.call( that, null, null ); } ); } return nBackground; }, /** * Show the show / hide list and the background * @method _fnCollectionShow * @returns void * @private */ "_fnCollectionShow": function () { var that = this, i, iLen; var oPos = $(this.dom.button).offset(); var nHidden = this.dom.collection; var nBackground = this.dom.background; var iDivX = parseInt(oPos.left, 10); var iDivY = parseInt(oPos.top + $(this.dom.button).outerHeight(), 10); if ( !this.s.bCssPosition ) { nHidden.style.top = iDivY+"px"; nHidden.style.left = iDivX+"px"; } nHidden.style.display = "block"; $(nHidden).css('opacity',0); var iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth<iDocWidth)? iWinWidth : iDocWidth) +"px"; var oStyle = this.dom.catcher.style; oStyle.height = $(this.dom.button).outerHeight()+"px"; oStyle.width = $(this.dom.button).outerWidth()+"px"; oStyle.top = oPos.top+"px"; oStyle.left = iDivX+"px"; document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); document.body.appendChild( this.dom.catcher ); /* Resize the buttons */ if ( this.s.sSize == "auto" ) { var aiSizes = []; this.dom.collection.style.width = "auto"; for ( i=0, iLen=this.dom.buttons.length ; i<iLen ; i++ ) { if ( this.dom.buttons[i] !== null ) { this.dom.buttons[i].style.width = "auto"; aiSizes.push( $(this.dom.buttons[i]).outerWidth() ); } } iMax = Math.max.apply(window, aiSizes); for ( i=0, iLen=this.dom.buttons.length ; i<iLen ; i++ ) { if ( this.dom.buttons[i] !== null ) { this.dom.buttons[i].style.width = iMax+"px"; } } this.dom.collection.style.width = iMax+"px"; } /* Visual corrections to try and keep the collection visible */ if ( !this.s.bCssPosition ) { nHidden.style.left = this.s.sAlign=="left" ? iDivX+"px" : (iDivX-$(nHidden).outerWidth()+$(this.dom.button).outerWidth())+"px"; var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } } /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, that.s.iOverlayFade); $(nBackground).animate({"opacity": 0.1}, that.s.iOverlayFade, 'linear', function () { /* In IE6 if you set the checked attribute of a hidden checkbox, then this is not visually * reflected. As such, we need to do it here, once it is visible. Unbelievable. */ if ( jQuery.browser.msie && jQuery.browser.version == "6.0" ) { that._fnDrawCallback(); } }); }, 10 ); this.s.hidden = false; }, /** * Hide the show / hide list and the background * @method _fnCollectionHide * @returns void * @private */ "_fnCollectionHide": function ( ) { var that = this; if ( !this.s.hidden && this.dom.collection !== null ) { this.s.hidden = true; $(this.dom.collection).animate({"opacity": 0}, that.s.iOverlayFade, function (e) { this.style.display = "none"; } ); $(this.dom.background).animate({"opacity": 0}, that.s.iOverlayFade, function (e) { document.body.removeChild( that.dom.background ); document.body.removeChild( that.dom.catcher ); } ); } }, /** * Alter the colspan on any fnOpen rows */ "_fnAdjustOpenRows": function () { var aoOpen = this.s.dt.aoOpenRows; var iVisible = this.s.dt.oApi._fnVisbleColumns( this.s.dt ); for ( var i=0, iLen=aoOpen.length ; i<iLen ; i++ ) { aoOpen[i].nTr.getElementsByTagName('td')[0].colSpan = iVisible; } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static object methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Rebuild the collection for a given table, or all tables if no parameter given * @method ColVis.fnRebuild * @static * @param object oTable DataTable instance to consider - optional * @returns void */ ColVis.fnRebuild = function ( oTable ) { var nTable = null; if ( typeof oTable != 'undefined' ) { nTable = oTable.fnSettings().nTable; } for ( var i=0, iLen=ColVis.aInstances.length ; i<iLen ; i++ ) { if ( typeof oTable == 'undefined' || nTable == ColVis.aInstances[i].s.dt.nTable ) { ColVis.aInstances[i].fnRebuild(); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static object properties * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Collection of all ColVis instances * @property ColVis.aInstances * @static * @type Array * @default [] */ ColVis.aInstances = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Name of this class * @constant CLASS * @type String * @default ColVis */ ColVis.prototype.CLASS = "ColVis"; /** * ColVis version * @constant VERSION * @type String * @default See code */ ColVis.VERSION = "1.0.8"; ColVis.prototype.VERSION = ColVis.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.7.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var init = (typeof oDTSettings.oInit.oColVis == 'undefined') ? {} : oDTSettings.oInit.oColVis; var oColvis = new ColVis( oDTSettings, init ); return oColvis.dom.wrapper; }, "cFeature": "C", "sFeature": "ColVis" } ); } else { alert( "Warning: ColVis requires DataTables 1.7 or greater - www.datatables.net/download"); } })(jQuery);
JavaScript
WebInspector = {}; WebInspector.UIString = function(s) { return s; }; WebInspector.HeapSnapshotArraySlice = function(array, start, end) { this._array = array; this._start = start; this.length = end - start; } WebInspector.HeapSnapshotArraySlice.prototype = { item: function(index) { return this._array[this._start + index]; }, slice: function(start, end) { if (typeof end === "undefined") end = this.length; return this._array.subarray(this._start + start, this._start + end); } } WebInspector.HeapSnapshotEdge = function(snapshot, edges, edgeIndex) { this._snapshot = snapshot; this._edges = edges; this.edgeIndex = edgeIndex || 0; } WebInspector.HeapSnapshotEdge.prototype = { clone: function() { return new WebInspector.HeapSnapshotEdge(this._snapshot, this._edges, this.edgeIndex); }, hasStringName: function() { if (!this.isShortcut()) return this._hasStringName(); return isNaN(parseInt(this._name(), 10)); }, isElement: function() { return this._type() === this._snapshot._edgeElementType; }, isHidden: function() { return this._type() === this._snapshot._edgeHiddenType; }, isWeak: function() { return this._type() === this._snapshot._edgeWeakType; }, isInternal: function() { return this._type() === this._snapshot._edgeInternalType; }, isInvisible: function() { return this._type() === this._snapshot._edgeInvisibleType; }, isShortcut: function() { return this._type() === this._snapshot._edgeShortcutType; }, name: function() { if (!this.isShortcut()) return this._name(); var numName = parseInt(this._name(), 10); return isNaN(numName) ? this._name() : numName; }, node: function() { return new WebInspector.HeapSnapshotNode(this._snapshot, this.nodeIndex()); }, nodeIndex: function() { return this._edges.item(this.edgeIndex + this._snapshot._edgeToNodeOffset); }, rawEdges: function() { return this._edges; }, toString: function() { var name = this.name(); switch (this.type()) { case "context": return "->" + name; case "element": return "[" + name + "]"; case "weak": return "[[" + name + "]]"; case "property": return name.indexOf(" ") === -1 ? "." + name : "[\"" + name + "\"]"; case "shortcut": if (typeof name === "string") return name.indexOf(" ") === -1 ? "." + name : "[\"" + name + "\"]"; else return "[" + name + "]"; case "internal": case "hidden": case "invisible": return "{" + name + "}"; }; return "?" + name + "?"; }, type: function() { return this._snapshot._edgeTypes[this._type()]; }, _hasStringName: function() { return !this.isElement() && !this.isHidden() && !this.isWeak(); }, _name: function() { return this._hasStringName() ? this._snapshot._strings[this._nameOrIndex()] : this._nameOrIndex(); }, _nameOrIndex: function() { return this._edges.item(this.edgeIndex + this._snapshot._edgeNameOffset); }, _type: function() { return this._edges.item(this.edgeIndex + this._snapshot._edgeTypeOffset); } }; WebInspector.HeapSnapshotEdgeIterator = function(edge) { this.edge = edge; } WebInspector.HeapSnapshotEdgeIterator.prototype = { first: function() { this.edge.edgeIndex = 0; }, hasNext: function() { return this.edge.edgeIndex < this.edge._edges.length; }, index: function() { return this.edge.edgeIndex; }, setIndex: function(newIndex) { this.edge.edgeIndex = newIndex; }, item: function() { return this.edge; }, next: function() { this.edge.edgeIndex += this.edge._snapshot._edgeFieldsCount; } }; WebInspector.HeapSnapshotRetainerEdge = function(snapshot, retainedNodeIndex, retainerIndex) { this._snapshot = snapshot; this._retainedNodeIndex = retainedNodeIndex; var retainedNodeOrdinal = retainedNodeIndex / snapshot._nodeFieldCount; this._firstRetainer = snapshot._firstRetainerIndex[retainedNodeOrdinal]; this._retainersCount = snapshot._firstRetainerIndex[retainedNodeOrdinal + 1] - this._firstRetainer; this.setRetainerIndex(retainerIndex); } WebInspector.HeapSnapshotRetainerEdge.prototype = { clone: function() { return new WebInspector.HeapSnapshotRetainerEdge(this._snapshot, this._retainedNodeIndex, this.retainerIndex()); }, hasStringName: function() { return this._edge().hasStringName(); }, isElement: function() { return this._edge().isElement(); }, isHidden: function() { return this._edge().isHidden(); }, isInternal: function() { return this._edge().isInternal(); }, isInvisible: function() { return this._edge().isInvisible(); }, isShortcut: function() { return this._edge().isShortcut(); }, isWeak: function() { return this._edge().isWeak(); }, name: function() { return this._edge().name(); }, node: function() { return this._node(); }, nodeIndex: function() { return this._nodeIndex; }, retainerIndex: function() { return this._retainerIndex; }, setRetainerIndex: function(newIndex) { if (newIndex !== this._retainerIndex) { this._retainerIndex = newIndex; this.edgeIndex = newIndex; } }, set edgeIndex(edgeIndex) { var retainerIndex = this._firstRetainer + edgeIndex; this._globalEdgeIndex = this._snapshot._retainingEdges[retainerIndex]; this._nodeIndex = this._snapshot._retainingNodes[retainerIndex]; delete this._edgeInstance; delete this._nodeInstance; }, _node: function() { if (!this._nodeInstance) this._nodeInstance = new WebInspector.HeapSnapshotNode(this._snapshot, this._nodeIndex); return this._nodeInstance; }, _edge: function() { if (!this._edgeInstance) { var edgeIndex = this._globalEdgeIndex - this._node()._edgeIndexesStart(); this._edgeInstance = new WebInspector.HeapSnapshotEdge(this._snapshot, this._node().rawEdges(), edgeIndex); } return this._edgeInstance; }, toString: function() { return this._edge().toString(); }, type: function() { return this._edge().type(); } } WebInspector.HeapSnapshotRetainerEdgeIterator = function(retainer) { this.retainer = retainer; } WebInspector.HeapSnapshotRetainerEdgeIterator.prototype = { first: function() { this.retainer.setRetainerIndex(0); }, hasNext: function() { return this.retainer.retainerIndex() < this.retainer._retainersCount; }, index: function() { return this.retainer.retainerIndex(); }, setIndex: function(newIndex) { this.retainer.setRetainerIndex(newIndex); }, item: function() { return this.retainer; }, next: function() { this.retainer.setRetainerIndex(this.retainer.retainerIndex() + 1); } }; WebInspector.HeapSnapshotNode = function(snapshot, nodeIndex) { this._snapshot = snapshot; this._firstNodeIndex = nodeIndex; this.nodeIndex = nodeIndex; } WebInspector.HeapSnapshotNode.prototype = { canBeQueried: function() { var flags = this._snapshot._flagsOfNode(this); return !!(flags & this._snapshot._nodeFlags.canBeQueried); }, isPageObject: function() { var flags = this._snapshot._flagsOfNode(this); return !!(flags & this._snapshot._nodeFlags.pageObject); }, distanceToWindow: function() { return this._snapshot._distancesToWindow[this.nodeIndex / this._snapshot._nodeFieldCount]; }, className: function() { var type = this.type(); switch (type) { case "hidden": return WebInspector.UIString("(system)"); case "object": case "native": return this.name(); case "code": return WebInspector.UIString("(compiled code)"); default: return "(" + type + ")"; } }, classIndex: function() { var snapshot = this._snapshot; var nodes = snapshot._nodes; var type = nodes[this.nodeIndex + snapshot._nodeTypeOffset];; if (type === snapshot._nodeObjectType || type === snapshot._nodeNativeType) return nodes[this.nodeIndex + snapshot._nodeNameOffset]; return -1 - type; }, dominatorIndex: function() { var nodeFieldCount = this._snapshot._nodeFieldCount; return this._snapshot._dominatorsTree[this.nodeIndex / this._snapshot._nodeFieldCount] * nodeFieldCount; }, edges: function() { return new WebInspector.HeapSnapshotEdgeIterator(new WebInspector.HeapSnapshotEdge(this._snapshot, this.rawEdges())); }, edgesCount: function() { return (this._edgeIndexesEnd() - this._edgeIndexesStart()) / this._snapshot._edgeFieldsCount; }, flags: function() { return this._snapshot._flagsOfNode(this); }, id: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeIdOffset]; }, isHidden: function() { return this._type() === this._snapshot._nodeHiddenType; }, isNative: function() { return this._type() === this._snapshot._nodeNativeType; }, isSynthetic: function() { return this._type() === this._snapshot._nodeSyntheticType; }, isWindow: function() { const windowRE = /^Window/; return windowRE.test(this.name()); }, isDetachedDOMTreesRoot: function() { return this.name() === "(Detached DOM trees)"; }, isDetachedDOMTree: function() { const detachedDOMTreeRE = /^Detached DOM tree/; return detachedDOMTreeRE.test(this.className()); }, isRoot: function() { return this.nodeIndex === this._snapshot._rootNodeIndex; }, name: function() { return this._snapshot._strings[this._name()]; }, rawEdges: function() { return new WebInspector.HeapSnapshotArraySlice(this._snapshot._containmentEdges, this._edgeIndexesStart(), this._edgeIndexesEnd()); }, retainedSize: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeRetainedSizeOffset]; }, retainers: function() { return new WebInspector.HeapSnapshotRetainerEdgeIterator(new WebInspector.HeapSnapshotRetainerEdge(this._snapshot, this.nodeIndex, 0)); }, selfSize: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeSelfSizeOffset]; }, type: function() { return this._snapshot._nodeTypes[this._type()]; }, _name: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeNameOffset]; }, _edgeIndexesStart: function() { return this._snapshot._firstEdgeIndexes[this._ordinal()]; }, _edgeIndexesEnd: function() { return this._snapshot._firstEdgeIndexes[this._ordinal() + 1]; }, _ordinal: function() { return this.nodeIndex / this._snapshot._nodeFieldCount; }, _nextNodeIndex: function() { return this.nodeIndex + this._snapshot._nodeFieldCount; }, _type: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeTypeOffset]; } }; WebInspector.HeapSnapshotNodeIterator = function(node) { this.node = node; this._nodesLength = node._snapshot._nodes.length; } WebInspector.HeapSnapshotNodeIterator.prototype = { first: function() { this.node.nodeIndex = this.node._firstNodeIndex; }, hasNext: function() { return this.node.nodeIndex < this._nodesLength; }, index: function() { return this.node.nodeIndex; }, setIndex: function(newIndex) { this.node.nodeIndex = newIndex; }, item: function() { return this.node; }, next: function() { this.node.nodeIndex = this.node._nextNodeIndex(); } } WebInspector.HeapSnapshot = function(profile) { this.uid = profile.snapshot.uid; this._nodes = profile.nodes; this._containmentEdges = profile.edges; this._metaNode = profile.snapshot.meta; this._strings = profile.strings; this._snapshotDiffs = {}; this._aggregatesForDiff = null; this._init(); } function HeapSnapshotMetainfo() { this.node_fields = []; this.node_types = []; this.edge_fields = []; this.edge_types = []; this.fields = []; this.types = []; } function HeapSnapshotHeader() { this.title = ""; this.uid = 0; this.meta = new HeapSnapshotMetainfo(); this.node_count = 0; this.edge_count = 0; } WebInspector.HeapSnapshot.prototype = { _init: function() { var meta = this._metaNode; this._rootNodeIndex = 0; this._nodeTypeOffset = meta.node_fields.indexOf("type"); this._nodeNameOffset = meta.node_fields.indexOf("name"); this._nodeIdOffset = meta.node_fields.indexOf("id"); this._nodeSelfSizeOffset = meta.node_fields.indexOf("self_size"); this._nodeEdgeCountOffset = meta.node_fields.indexOf("edge_count"); this._nodeFieldCount = meta.node_fields.length; this._nodeTypes = meta.node_types[this._nodeTypeOffset]; this._nodeHiddenType = this._nodeTypes.indexOf("hidden"); this._nodeObjectType = this._nodeTypes.indexOf("object"); this._nodeNativeType = this._nodeTypes.indexOf("native"); this._nodeCodeType = this._nodeTypes.indexOf("code"); this._nodeSyntheticType = this._nodeTypes.indexOf("synthetic"); this._edgeFieldsCount = meta.edge_fields.length; this._edgeTypeOffset = meta.edge_fields.indexOf("type"); this._edgeNameOffset = meta.edge_fields.indexOf("name_or_index"); this._edgeToNodeOffset = meta.edge_fields.indexOf("to_node"); this._edgeTypes = meta.edge_types[this._edgeTypeOffset]; this._edgeTypes.push("invisible"); this._edgeElementType = this._edgeTypes.indexOf("element"); this._edgeHiddenType = this._edgeTypes.indexOf("hidden"); this._edgeInternalType = this._edgeTypes.indexOf("internal"); this._edgeShortcutType = this._edgeTypes.indexOf("shortcut"); this._edgeWeakType = this._edgeTypes.indexOf("weak"); this._edgeInvisibleType = this._edgeTypes.indexOf("invisible"); this._nodeFlags = { canBeQueried: 1, detachedDOMTreeNode: 2, pageObject: 4, visitedMarkerMask: 0x0ffff, visitedMarker: 0x10000 }; this.nodeCount = this._nodes.length / this._nodeFieldCount; this._edgeCount = this._containmentEdges.length / this._edgeFieldsCount; this._buildEdgeIndexes(); this._markInvisibleEdges(); this._buildRetainers(); this._calculateFlags(); this._calculateObjectToWindowDistance(); var result = this._buildPostOrderIndex(); this._dominatorsTree = this._buildDominatorTree(result.postOrderIndex2NodeOrdinal, result.nodeOrdinal2PostOrderIndex); this._calculateRetainedSizes(result.postOrderIndex2NodeOrdinal); this._buildDominatedNodes(); }, _buildEdgeIndexes: function() { if (this._nodeEdgeCountOffset === -1) { var nodes = this._nodes; var nodeCount = this.nodeCount; var firstEdgeIndexes = this._firstEdgeIndexes = new Uint32Array(nodeCount + 1); var nodeFieldCount = this._nodeFieldCount; var nodeEdgesIndexOffset = this._metaNode.node_fields.indexOf("edges_index"); firstEdgeIndexes[nodeCount] = this._containmentEdges.length; for (var nodeOrdinal = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) { firstEdgeIndexes[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeEdgesIndexOffset]; } return; } var nodes = this._nodes; var nodeCount = this.nodeCount; var firstEdgeIndexes = this._firstEdgeIndexes = new Uint32Array(nodeCount + 1); var nodeFieldCount = this._nodeFieldCount; var edgeFieldsCount = this._edgeFieldsCount; var nodeEdgeCountOffset = this._nodeEdgeCountOffset; firstEdgeIndexes[nodeCount] = this._containmentEdges.length; for (var nodeOrdinal = 0, edgeIndex = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) { firstEdgeIndexes[nodeOrdinal] = edgeIndex; edgeIndex += nodes[nodeOrdinal * nodeFieldCount + nodeEdgeCountOffset] * edgeFieldsCount; } }, _buildRetainers: function() { var retainingNodes = this._retainingNodes = new Uint32Array(this._edgeCount); var retainingEdges = this._retainingEdges = new Uint32Array(this._edgeCount); var firstRetainerIndex = this._firstRetainerIndex = new Uint32Array(this.nodeCount + 1); var containmentEdges = this._containmentEdges; var edgeFieldsCount = this._edgeFieldsCount; var nodeFieldCount = this._nodeFieldCount; var edgeToNodeOffset = this._edgeToNodeOffset; var nodes = this._nodes; var firstEdgeIndexes = this._firstEdgeIndexes; var nodeCount = this.nodeCount; for (var toNodeFieldIndex = edgeToNodeOffset, l = containmentEdges.length; toNodeFieldIndex < l; toNodeFieldIndex += edgeFieldsCount) { var toNodeIndex = containmentEdges[toNodeFieldIndex]; if (toNodeIndex % nodeFieldCount) throw new Error("Invalid toNodeIndex " + toNodeIndex); ++firstRetainerIndex[toNodeIndex / nodeFieldCount]; } for (var i = 0, firstUnusedRetainerSlot = 0; i < nodeCount; i++) { var retainersCount = firstRetainerIndex[i]; firstRetainerIndex[i] = firstUnusedRetainerSlot; retainingNodes[firstUnusedRetainerSlot] = retainersCount; firstUnusedRetainerSlot += retainersCount; } firstRetainerIndex[nodeCount] = retainingNodes.length; var nextNodeFirstEdgeIndex = firstEdgeIndexes[0]; for (var srcNodeOrdinal = 0; srcNodeOrdinal < nodeCount; ++srcNodeOrdinal) { var firstEdgeIndex = nextNodeFirstEdgeIndex; nextNodeFirstEdgeIndex = firstEdgeIndexes[srcNodeOrdinal + 1]; var srcNodeIndex = srcNodeOrdinal * nodeFieldCount; for (var edgeIndex = firstEdgeIndex; edgeIndex < nextNodeFirstEdgeIndex; edgeIndex += edgeFieldsCount) { var toNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; if (toNodeIndex % nodeFieldCount) throw new Error("Invalid toNodeIndex " + toNodeIndex); var firstRetainerSlotIndex = firstRetainerIndex[toNodeIndex / nodeFieldCount]; var nextUnusedRetainerSlotIndex = firstRetainerSlotIndex + (--retainingNodes[firstRetainerSlotIndex]); retainingNodes[nextUnusedRetainerSlotIndex] = srcNodeIndex; retainingEdges[nextUnusedRetainerSlotIndex] = edgeIndex; } } }, dispose: function() { delete this._nodes; delete this._strings; delete this._retainingEdges; delete this._retainingNodes; delete this._firstRetainerIndex; if (this._aggregates) { delete this._aggregates; delete this._aggregatesSortedFlags; } delete this._dominatedNodes; delete this._firstDominatedNodeIndex; delete this._flags; delete this._distancesToWindow; delete this._dominatorsTree; }, _allNodes: function() { return new WebInspector.HeapSnapshotNodeIterator(this.rootNode()); }, rootNode: function() { return new WebInspector.HeapSnapshotNode(this, this._rootNodeIndex); }, get rootNodeIndex() { return this._rootNodeIndex; }, get totalSize() { return this.rootNode().retainedSize(); }, _getDominatedIndex: function(nodeIndex) { if (nodeIndex % this._nodeFieldCount) throw new Error("Invalid nodeIndex: " + nodeIndex); return this._firstDominatedNodeIndex[nodeIndex / this._nodeFieldCount]; }, _dominatedNodesOfNode: function(node) { var dominatedIndexFrom = this._getDominatedIndex(node.nodeIndex); var dominatedIndexTo = this._getDominatedIndex(node._nextNodeIndex()); return new WebInspector.HeapSnapshotArraySlice(this._dominatedNodes, dominatedIndexFrom, dominatedIndexTo); }, _flagsOfNode: function(node) { return this._flags[node.nodeIndex / this._nodeFieldCount]; }, aggregates: function(sortedIndexes, key, filterString) { if (!this._aggregates) { this._aggregates = {}; this._aggregatesSortedFlags = {}; } var aggregatesByClassName = this._aggregates[key]; if (aggregatesByClassName) { if (sortedIndexes && !this._aggregatesSortedFlags[key]) { this._sortAggregateIndexes(aggregatesByClassName); this._aggregatesSortedFlags[key] = sortedIndexes; } return aggregatesByClassName; } var filter; if (filterString) filter = this._parseFilter(filterString); var aggregates = this._buildAggregates(filter); this._calculateClassesRetainedSize(aggregates.aggregatesByClassIndex, filter); aggregatesByClassName = aggregates.aggregatesByClassName; if (sortedIndexes) this._sortAggregateIndexes(aggregatesByClassName); this._aggregatesSortedFlags[key] = sortedIndexes; this._aggregates[key] = aggregatesByClassName; return aggregatesByClassName; }, aggregatesForDiff: function() { if (this._aggregatesForDiff) return this._aggregatesForDiff; var aggregatesByClassName = this.aggregates(true, "allObjects"); this._aggregatesForDiff = {}; var node = new WebInspector.HeapSnapshotNode(this); for (var className in aggregatesByClassName) { var aggregate = aggregatesByClassName[className]; var indexes = aggregate.idxs; var ids = new Array(indexes.length); var selfSizes = new Array(indexes.length); for (var i = 0; i < indexes.length; i++) { node.nodeIndex = indexes[i]; ids[i] = node.id(); selfSizes[i] = node.selfSize(); } this._aggregatesForDiff[className] = { indexes: indexes, ids: ids, selfSizes: selfSizes }; } return this._aggregatesForDiff; }, _calculateObjectToWindowDistance: function() { var nodeFieldCount = this._nodeFieldCount; var distances = new Uint32Array(this.nodeCount); var nodesToVisit = new Uint32Array(this.nodeCount); var nodesToVisitLength = 0; for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { var node = iter.edge.node(); if (node.isWindow()) { nodesToVisit[nodesToVisitLength++] = node.nodeIndex; distances[node.nodeIndex / nodeFieldCount] = 1; } } this._bfs(nodesToVisit, nodesToVisitLength, distances); nodesToVisitLength = 0; nodesToVisit[nodesToVisitLength++] = this._rootNodeIndex; distances[this._rootNodeIndex / nodeFieldCount] = 1; this._bfs(nodesToVisit, nodesToVisitLength, distances); this._distancesToWindow = distances; }, _bfs: function(nodesToVisit, nodesToVisitLength, distances) { var edgeFieldsCount = this._edgeFieldsCount; var nodeFieldCount = this._nodeFieldCount; var containmentEdges = this._containmentEdges; var firstEdgeIndexes = this._firstEdgeIndexes; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeTypeOffset = this._edgeTypeOffset; var nodes = this._nodes; var nodeCount = this.nodeCount; var containmentEdgesLength = containmentEdges.length; var edgeWeakType = this._edgeWeakType; var edgeShortcutType = this._edgeShortcutType; var index = 0; while (index < nodesToVisitLength) { var nodeIndex = nodesToVisit[index++]; var nodeOrdinal = nodeIndex / nodeFieldCount; var distance = distances[nodeOrdinal] + 1; var firstEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var edgesEnd = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = firstEdgeIndex; edgeIndex < edgesEnd; edgeIndex += edgeFieldsCount) { var edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; if (edgeType == edgeWeakType) continue; var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; if (distances[childNodeOrdinal]) continue; distances[childNodeOrdinal] = distance; nodesToVisit[nodesToVisitLength++] = childNodeIndex; } } if (nodesToVisitLength > nodeCount) throw new Error("BFS failed. Nodes to visit (" + nodesToVisitLength + ") is more than nodes count (" + nodeCount + ")"); }, _buildAggregates: function(filter) { var aggregates = {}; var aggregatesByClassName = {}; var classIndexes = []; var nodes = this._nodes; var flags = this._flags; var nodesLength = nodes.length; var nodeNativeType = this._nodeNativeType; var nodeFieldCount = this._nodeFieldCount; var selfSizeOffset = this._nodeSelfSizeOffset; var nodeTypeOffset = this._nodeTypeOffset; var pageObjectFlag = this._nodeFlags.pageObject; var node = new WebInspector.HeapSnapshotNode(this, this._rootNodeIndex); var distancesToWindow = this._distancesToWindow; for (var nodeIndex = this._rootNodeIndex; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { var nodeOrdinal = nodeIndex / nodeFieldCount; if (!(flags[nodeOrdinal] & pageObjectFlag)) continue; node.nodeIndex = nodeIndex; if (filter && !filter(node)) continue; var selfSize = nodes[nodeIndex + selfSizeOffset]; if (!selfSize && nodes[nodeIndex + nodeTypeOffset] !== nodeNativeType) continue; var classIndex = node.classIndex(); if (!(classIndex in aggregates)) { var nodeType = node.type(); var nameMatters = nodeType === "object" || nodeType === "native"; var value = { count: 1, distanceToWindow: distancesToWindow[nodeOrdinal], self: selfSize, maxRet: 0, type: nodeType, name: nameMatters ? node.name() : null, idxs: [nodeIndex] }; aggregates[classIndex] = value; classIndexes.push(classIndex); aggregatesByClassName[node.className()] = value; } else { var clss = aggregates[classIndex]; clss.distanceToWindow = Math.min(clss.distanceToWindow, distancesToWindow[nodeOrdinal]); ++clss.count; clss.self += selfSize; clss.idxs.push(nodeIndex); } } for (var i = 0, l = classIndexes.length; i < l; ++i) { var classIndex = classIndexes[i]; aggregates[classIndex].idxs = aggregates[classIndex].idxs.slice(); } return {aggregatesByClassName: aggregatesByClassName, aggregatesByClassIndex: aggregates}; }, _calculateClassesRetainedSize: function(aggregates, filter) { var rootNodeIndex = this._rootNodeIndex; var node = new WebInspector.HeapSnapshotNode(this, rootNodeIndex); var list = [rootNodeIndex]; var sizes = [-1]; var classes = []; var seenClassNameIndexes = {}; var nodeFieldCount = this._nodeFieldCount; var nodeTypeOffset = this._nodeTypeOffset; var nodeNativeType = this._nodeNativeType; var dominatedNodes = this._dominatedNodes; var nodes = this._nodes; var flags = this._flags; var pageObjectFlag = this._nodeFlags.pageObject; var firstDominatedNodeIndex = this._firstDominatedNodeIndex; while (list.length) { var nodeIndex = list.pop(); node.nodeIndex = nodeIndex; var classIndex = node.classIndex(); var seen = !!seenClassNameIndexes[classIndex]; var nodeOrdinal = nodeIndex / nodeFieldCount; var dominatedIndexFrom = firstDominatedNodeIndex[nodeOrdinal]; var dominatedIndexTo = firstDominatedNodeIndex[nodeOrdinal + 1]; if (!seen && (flags[nodeOrdinal] & pageObjectFlag) && (!filter || filter(node)) && (node.selfSize() || nodes[nodeIndex + nodeTypeOffset] === nodeNativeType) ) { aggregates[classIndex].maxRet += node.retainedSize(); if (dominatedIndexFrom !== dominatedIndexTo) { seenClassNameIndexes[classIndex] = true; sizes.push(list.length); classes.push(classIndex); } } for (var i = dominatedIndexFrom; i < dominatedIndexTo; i++) list.push(dominatedNodes[i]); var l = list.length; while (sizes[sizes.length - 1] === l) { sizes.pop(); classIndex = classes.pop(); seenClassNameIndexes[classIndex] = false; } } }, _sortAggregateIndexes: function(aggregates) { var nodeA = new WebInspector.HeapSnapshotNode(this); var nodeB = new WebInspector.HeapSnapshotNode(this); for (var clss in aggregates) aggregates[clss].idxs.sort( function(idxA, idxB) { nodeA.nodeIndex = idxA; nodeB.nodeIndex = idxB; return nodeA.id() < nodeB.id() ? -1 : 1; }); }, _buildPostOrderIndex: function() { var nodeFieldCount = this._nodeFieldCount; var nodes = this._nodes; var nodeCount = this.nodeCount; var rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; var edgeFieldsCount = this._edgeFieldsCount; var edgeTypeOffset = this._edgeTypeOffset; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeShortcutType = this._edgeShortcutType; var firstEdgeIndexes = this._firstEdgeIndexes; var containmentEdges = this._containmentEdges; var containmentEdgesLength = this._containmentEdges.length; var flags = this._flags; var flag = this._nodeFlags.pageObject; var nodesToVisit = new Uint32Array(nodeCount); var postOrderIndex2NodeOrdinal = new Uint32Array(nodeCount); var nodeOrdinal2PostOrderIndex = new Uint32Array(nodeCount); var painted = new Uint8Array(nodeCount); var nodesToVisitLength = 0; var postOrderIndex = 0; var grey = 1; var black = 2; nodesToVisit[nodesToVisitLength++] = rootNodeOrdinal; painted[rootNodeOrdinal] = grey; while (nodesToVisitLength) { var nodeOrdinal = nodesToVisit[nodesToVisitLength - 1]; if (painted[nodeOrdinal] === grey) { painted[nodeOrdinal] = black; var nodeFlag = flags[nodeOrdinal] & flag; var beginEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { if (nodeOrdinal !== rootNodeOrdinal && containmentEdges[edgeIndex + edgeTypeOffset] === edgeShortcutType) continue; var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; var childNodeFlag = flags[childNodeOrdinal] & flag; if (nodeOrdinal !== rootNodeOrdinal && childNodeFlag && !nodeFlag) continue; if (!painted[childNodeOrdinal]) { painted[childNodeOrdinal] = grey; nodesToVisit[nodesToVisitLength++] = childNodeOrdinal; } } } else { nodeOrdinal2PostOrderIndex[nodeOrdinal] = postOrderIndex; postOrderIndex2NodeOrdinal[postOrderIndex++] = nodeOrdinal; --nodesToVisitLength; } } if (postOrderIndex !== nodeCount) throw new Error("Postordering failed. " + (nodeCount - postOrderIndex) + " hanging nodes"); return {postOrderIndex2NodeOrdinal: postOrderIndex2NodeOrdinal, nodeOrdinal2PostOrderIndex: nodeOrdinal2PostOrderIndex}; }, _buildDominatorTree: function(postOrderIndex2NodeOrdinal, nodeOrdinal2PostOrderIndex) { var nodeFieldCount = this._nodeFieldCount; var nodes = this._nodes; var firstRetainerIndex = this._firstRetainerIndex; var retainingNodes = this._retainingNodes; var retainingEdges = this._retainingEdges; var edgeFieldsCount = this._edgeFieldsCount; var edgeTypeOffset = this._edgeTypeOffset; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeShortcutType = this._edgeShortcutType; var firstEdgeIndexes = this._firstEdgeIndexes; var containmentEdges = this._containmentEdges; var containmentEdgesLength = this._containmentEdges.length; var rootNodeIndex = this._rootNodeIndex; var flags = this._flags; var flag = this._nodeFlags.pageObject; var nodesCount = postOrderIndex2NodeOrdinal.length; var rootPostOrderedIndex = nodesCount - 1; var noEntry = nodesCount; var dominators = new Uint32Array(nodesCount); for (var i = 0; i < rootPostOrderedIndex; ++i) dominators[i] = noEntry; dominators[rootPostOrderedIndex] = rootPostOrderedIndex; var affected = new Uint8Array(nodesCount); var nodeOrdinal; { nodeOrdinal = this._rootNodeIndex / nodeFieldCount; var beginEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal] + edgeToNodeOffset; var endEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var toNodeFieldIndex = beginEdgeToNodeFieldIndex; toNodeFieldIndex < endEdgeToNodeFieldIndex; toNodeFieldIndex += edgeFieldsCount) { var childNodeOrdinal = containmentEdges[toNodeFieldIndex] / nodeFieldCount; affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]] = 1; } } var changed = true; while (changed) { changed = false; for (var postOrderIndex = rootPostOrderedIndex - 1; postOrderIndex >= 0; --postOrderIndex) { if (affected[postOrderIndex] === 0) continue; affected[postOrderIndex] = 0; if (dominators[postOrderIndex] === rootPostOrderedIndex) continue; nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; var nodeFlag = !!(flags[nodeOrdinal] & flag); var newDominatorIndex = noEntry; var beginRetainerIndex = firstRetainerIndex[nodeOrdinal]; var endRetainerIndex = firstRetainerIndex[nodeOrdinal + 1]; for (var retainerIndex = beginRetainerIndex; retainerIndex < endRetainerIndex; ++retainerIndex) { var retainerEdgeIndex = retainingEdges[retainerIndex]; var retainerEdgeType = containmentEdges[retainerEdgeIndex + edgeTypeOffset]; var retainerNodeIndex = retainingNodes[retainerIndex]; if (retainerNodeIndex !== rootNodeIndex && retainerEdgeType === edgeShortcutType) continue; var retainerNodeOrdinal = retainerNodeIndex / nodeFieldCount; var retainerNodeFlag = !!(flags[retainerNodeOrdinal] & flag); if (retainerNodeIndex !== rootNodeIndex && nodeFlag && !retainerNodeFlag) continue; var retanerPostOrderIndex = nodeOrdinal2PostOrderIndex[retainerNodeOrdinal]; if (dominators[retanerPostOrderIndex] !== noEntry) { if (newDominatorIndex === noEntry) newDominatorIndex = retanerPostOrderIndex; else { while (retanerPostOrderIndex !== newDominatorIndex) { while (retanerPostOrderIndex < newDominatorIndex) retanerPostOrderIndex = dominators[retanerPostOrderIndex]; while (newDominatorIndex < retanerPostOrderIndex) newDominatorIndex = dominators[newDominatorIndex]; } } if (newDominatorIndex === rootPostOrderedIndex) break; } } if (newDominatorIndex !== noEntry && dominators[postOrderIndex] !== newDominatorIndex) { dominators[postOrderIndex] = newDominatorIndex; changed = true; nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; beginEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal] + edgeToNodeOffset; endEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var toNodeFieldIndex = beginEdgeToNodeFieldIndex; toNodeFieldIndex < endEdgeToNodeFieldIndex; toNodeFieldIndex += edgeFieldsCount) { var childNodeOrdinal = containmentEdges[toNodeFieldIndex] / nodeFieldCount; affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]] = 1; } } } } var dominatorsTree = new Uint32Array(nodesCount); for (var postOrderIndex = 0, l = dominators.length; postOrderIndex < l; ++postOrderIndex) { nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; dominatorsTree[nodeOrdinal] = postOrderIndex2NodeOrdinal[dominators[postOrderIndex]]; } return dominatorsTree; }, _calculateRetainedSizes: function(postOrderIndex2NodeOrdinal) { var nodeCount = this.nodeCount; var nodes = this._nodes; var nodeSelfSizeOffset = this._nodeSelfSizeOffset; var nodeFieldCount = this._nodeFieldCount; var dominatorsTree = this._dominatorsTree; var nodeRetainedSizeOffset = this._nodeRetainedSizeOffset = this._nodeEdgeCountOffset; delete this._nodeEdgeCountOffset; for (var nodeIndex = 0, l = nodes.length; nodeIndex < l; nodeIndex += nodeFieldCount) nodes[nodeIndex + nodeRetainedSizeOffset] = nodes[nodeIndex + nodeSelfSizeOffset]; for (var postOrderIndex = 0; postOrderIndex < nodeCount - 1; ++postOrderIndex) { var nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; var nodeIndex = nodeOrdinal * nodeFieldCount; var dominatorIndex = dominatorsTree[nodeOrdinal] * nodeFieldCount; nodes[dominatorIndex + nodeRetainedSizeOffset] += nodes[nodeIndex + nodeRetainedSizeOffset]; } }, _buildDominatedNodes: function() { var indexArray = this._firstDominatedNodeIndex = new Uint32Array(this.nodeCount + 1); var dominatedNodes = this._dominatedNodes = new Uint32Array(this.nodeCount - 1); var nodeFieldCount = this._nodeFieldCount; var dominatorsTree = this._dominatorsTree; for (var nodeOrdinal = 1, l = this.nodeCount; nodeOrdinal < l; ++nodeOrdinal) ++indexArray[dominatorsTree[nodeOrdinal]]; var firstDominatedNodeIndex = 0; for (var i = 0, l = this.nodeCount; i < l; ++i) { var dominatedCount = dominatedNodes[firstDominatedNodeIndex] = indexArray[i]; indexArray[i] = firstDominatedNodeIndex; firstDominatedNodeIndex += dominatedCount; } indexArray[this.nodeCount] = dominatedNodes.length; for (var nodeOrdinal = 1, l = this.nodeCount; nodeOrdinal < l; ++nodeOrdinal) { var dominatorOrdinal = dominatorsTree[nodeOrdinal]; var dominatedRefIndex = indexArray[dominatorOrdinal]; dominatedRefIndex += (--dominatedNodes[dominatedRefIndex]); dominatedNodes[dominatedRefIndex] = nodeOrdinal * nodeFieldCount; } }, _markInvisibleEdges: function() { for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { var edge = iter.edge; if (!edge.isShortcut()) continue; var node = edge.node(); var propNames = {}; for (var innerIter = node.edges(); innerIter.hasNext(); innerIter.next()) { var globalObjEdge = innerIter.edge; if (globalObjEdge.isShortcut()) propNames[globalObjEdge._nameOrIndex()] = true; } for (innerIter.first(); innerIter.hasNext(); innerIter.next()) { var globalObjEdge = innerIter.edge; if (!globalObjEdge.isShortcut() && globalObjEdge.node().isHidden() && globalObjEdge._hasStringName() && (globalObjEdge._nameOrIndex() in propNames)) this._containmentEdges[globalObjEdge._edges._start + globalObjEdge.edgeIndex + this._edgeTypeOffset] = this._edgeInvisibleType; } } }, _numbersComparator: function(a, b) { return a < b ? -1 : (a > b ? 1 : 0); }, _markDetachedDOMTreeNodes: function() { var flag = this._nodeFlags.detachedDOMTreeNode; var detachedDOMTreesRoot; for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { var node = iter.edge.node(); if (node.isDetachedDOMTreesRoot()) { detachedDOMTreesRoot = node; break; } } if (!detachedDOMTreesRoot) return; for (var iter = detachedDOMTreesRoot.edges(); iter.hasNext(); iter.next()) { var node = iter.edge.node(); if (node.isDetachedDOMTree()) { for (var edgesIter = node.edges(); edgesIter.hasNext(); edgesIter.next()) this._flags[edgesIter.edge.node().nodeIndex / this._nodeFieldCount] |= flag; } } }, _markPageOwnedNodes: function() { var edgeShortcutType = this._edgeShortcutType; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeTypeOffset = this._edgeTypeOffset; var edgeFieldsCount = this._edgeFieldsCount; var edgeWeakType = this._edgeWeakType; var firstEdgeIndexes = this._firstEdgeIndexes; var containmentEdges = this._containmentEdges; var containmentEdgesLength = containmentEdges.length; var nodes = this._nodes; var nodeFieldCount = this._nodeFieldCount; var nodesCount = this.nodeCount; var flags = this._flags; var flag = this._nodeFlags.pageObject; var visitedMarker = this._nodeFlags.visitedMarker; var visitedMarkerMask = this._nodeFlags.visitedMarkerMask; var markerAndFlag = visitedMarker | flag; var nodesToVisit = new Uint32Array(nodesCount); var nodesToVisitLength = 0; var rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; for (var edgeIndex = firstEdgeIndexes[rootNodeOrdinal], endEdgeIndex = firstEdgeIndexes[rootNodeOrdinal + 1]; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { if (containmentEdges[edgeIndex + edgeTypeOffset] === edgeShortcutType) { var nodeOrdinal = containmentEdges[edgeIndex + edgeToNodeOffset] / nodeFieldCount; nodesToVisit[nodesToVisitLength++] = nodeOrdinal; flags[nodeOrdinal] |= visitedMarker; } } while (nodesToVisitLength) { var nodeOrdinal = nodesToVisit[--nodesToVisitLength]; flags[nodeOrdinal] |= flag; flags[nodeOrdinal] &= visitedMarkerMask; var beginEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; if (flags[childNodeOrdinal] & markerAndFlag) continue; var type = containmentEdges[edgeIndex + edgeTypeOffset]; if (type === edgeWeakType) continue; nodesToVisit[nodesToVisitLength++] = childNodeOrdinal; flags[childNodeOrdinal] |= visitedMarker; } } }, _markQueriableHeapObjects: function() { var flag = this._nodeFlags.canBeQueried; var hiddenEdgeType = this._edgeHiddenType; var internalEdgeType = this._edgeInternalType; var invisibleEdgeType = this._edgeInvisibleType; var weakEdgeType = this._edgeWeakType; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeTypeOffset = this._edgeTypeOffset; var edgeFieldsCount = this._edgeFieldsCount; var containmentEdges = this._containmentEdges; var nodes = this._nodes; var nodeCount = this.nodeCount; var nodeFieldCount = this._nodeFieldCount; var firstEdgeIndexes = this._firstEdgeIndexes; var flags = this._flags; var list = []; for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { if (iter.edge.node().isWindow()) list.push(iter.edge.node().nodeIndex / nodeFieldCount); } while (list.length) { var nodeOrdinal = list.pop(); if (flags[nodeOrdinal] & flag) continue; flags[nodeOrdinal] |= flag; var beginEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; if (flags[childNodeOrdinal] & flag) continue; var type = containmentEdges[edgeIndex + edgeTypeOffset]; if (type === hiddenEdgeType || type === invisibleEdgeType || type === internalEdgeType || type === weakEdgeType) continue; list.push(childNodeOrdinal); } } }, _calculateFlags: function() { this._flags = new Uint32Array(this.nodeCount); this._markDetachedDOMTreeNodes(); this._markQueriableHeapObjects(); this._markPageOwnedNodes(); }, calculateSnapshotDiff: function(baseSnapshotId, baseSnapshotAggregates) { var snapshotDiff = this._snapshotDiffs[baseSnapshotId]; if (snapshotDiff) return snapshotDiff; snapshotDiff = {}; var aggregates = this.aggregates(true, "allObjects"); for (var className in baseSnapshotAggregates) { var baseAggregate = baseSnapshotAggregates[className]; var diff = this._calculateDiffForClass(baseAggregate, aggregates[className]); if (diff) snapshotDiff[className] = diff; } var emptyBaseAggregate = { ids: [], indexes: [], selfSizes: [] }; for (var className in aggregates) { if (className in baseSnapshotAggregates) continue; snapshotDiff[className] = this._calculateDiffForClass(emptyBaseAggregate, aggregates[className]); } this._snapshotDiffs[baseSnapshotId] = snapshotDiff; return snapshotDiff; }, _calculateDiffForClass: function(baseAggregate, aggregate) { var baseIds = baseAggregate.ids; var baseIndexes = baseAggregate.indexes; var baseSelfSizes = baseAggregate.selfSizes; var indexes = aggregate ? aggregate.idxs : []; var i = 0, l = baseIds.length; var j = 0, m = indexes.length; var diff = { addedCount: 0, removedCount: 0, addedSize: 0, removedSize: 0, deletedIndexes: [], addedIndexes: [] }; var nodeB = new WebInspector.HeapSnapshotNode(this, indexes[j]); while (i < l && j < m) { var nodeAId = baseIds[i]; if (nodeAId < nodeB.id()) { diff.deletedIndexes.push(baseIndexes[i]); diff.removedCount++; diff.removedSize += baseSelfSizes[i]; ++i; } else if (nodeAId > nodeB.id()) { diff.addedIndexes.push(indexes[j]); diff.addedCount++; diff.addedSize += nodeB.selfSize(); nodeB.nodeIndex = indexes[++j]; } else { ++i; nodeB.nodeIndex = indexes[++j]; } } while (i < l) { diff.deletedIndexes.push(baseIndexes[i]); diff.removedCount++; diff.removedSize += baseSelfSizes[i]; ++i; } while (j < m) { diff.addedIndexes.push(indexes[j]); diff.addedCount++; diff.addedSize += nodeB.selfSize(); nodeB.nodeIndex = indexes[++j]; } diff.countDelta = diff.addedCount - diff.removedCount; diff.sizeDelta = diff.addedSize - diff.removedSize; if (!diff.addedCount && !diff.removedCount) return null; return diff; }, _nodeForSnapshotObjectId: function(snapshotObjectId) { for (var it = this._allNodes(); it.hasNext(); it.next()) { if (it.node.id() === snapshotObjectId) return it.node; } return null; }, nodeClassName: function(snapshotObjectId) { var node = this._nodeForSnapshotObjectId(snapshotObjectId); if (node) return node.className(); return null; }, dominatorIdsForNode: function(snapshotObjectId) { var node = this._nodeForSnapshotObjectId(snapshotObjectId); if (!node) return null; var result = []; while (!node.isRoot()) { result.push(node.id()); node.nodeIndex = node.dominatorIndex(); } return result; }, _parseFilter: function(filter) { if (!filter) return null; var parsedFilter = eval("(function(){return " + filter + "})()"); return parsedFilter.bind(this); }, createEdgesProvider: function(nodeIndex, filter) { var node = new WebInspector.HeapSnapshotNode(this, nodeIndex); return new WebInspector.HeapSnapshotEdgesProvider(this, this._parseFilter(filter), node.edges()); }, createRetainingEdgesProvider: function(nodeIndex, filter) { var node = new WebInspector.HeapSnapshotNode(this, nodeIndex); return new WebInspector.HeapSnapshotEdgesProvider(this, this._parseFilter(filter), node.retainers()); }, createAddedNodesProvider: function(baseSnapshotId, className) { var snapshotDiff = this._snapshotDiffs[baseSnapshotId]; var diffForClass = snapshotDiff[className]; return new WebInspector.HeapSnapshotNodesProvider(this, null, diffForClass.addedIndexes); }, createDeletedNodesProvider: function(nodeIndexes) { return new WebInspector.HeapSnapshotNodesProvider(this, null, nodeIndexes); }, createNodesProviderForClass: function(className, aggregatesKey) { function filter(node) { return node.isPageObject(); } return new WebInspector.HeapSnapshotNodesProvider(this, filter, this.aggregates(false, aggregatesKey)[className].idxs); }, createNodesProviderForDominator: function(nodeIndex) { var node = new WebInspector.HeapSnapshotNode(this, nodeIndex); return new WebInspector.HeapSnapshotNodesProvider(this, null, this._dominatedNodesOfNode(node)); }, updateStaticData: function() { return {nodeCount: this.nodeCount, rootNodeIndex: this._rootNodeIndex, totalSize: this.totalSize, uid: this.uid, nodeFlags: this._nodeFlags}; } }; WebInspector.HeapSnapshotFilteredOrderedIterator = function(iterator, filter, unfilteredIterationOrder) { this._filter = filter; this._iterator = iterator; this._unfilteredIterationOrder = unfilteredIterationOrder; this._iterationOrder = null; this._position = 0; this._currentComparator = null; this._sortedPrefixLength = 0; } WebInspector.HeapSnapshotFilteredOrderedIterator.prototype = { _createIterationOrder: function() { if (this._iterationOrder) return; if (this._unfilteredIterationOrder && !this._filter) { this._iterationOrder = this._unfilteredIterationOrder.slice(0); this._unfilteredIterationOrder = null; return; } this._iterationOrder = []; var iterator = this._iterator; if (!this._unfilteredIterationOrder && !this._filter) { for (iterator.first(); iterator.hasNext(); iterator.next()) this._iterationOrder.push(iterator.index()); } else if (!this._unfilteredIterationOrder) { for (iterator.first(); iterator.hasNext(); iterator.next()) { if (this._filter(iterator.item())) this._iterationOrder.push(iterator.index()); } } else { var order = this._unfilteredIterationOrder.constructor === Array ? this._unfilteredIterationOrder : this._unfilteredIterationOrder.slice(0); for (var i = 0, l = order.length; i < l; ++i) { iterator.setIndex(order[i]); if (this._filter(iterator.item())) this._iterationOrder.push(iterator.index()); } this._unfilteredIterationOrder = null; } }, first: function() { this._position = 0; }, hasNext: function() { return this._position < this._iterationOrder.length; }, isEmpty: function() { if (this._iterationOrder) return !this._iterationOrder.length; if (this._unfilteredIterationOrder && !this._filter) return !this._unfilteredIterationOrder.length; var iterator = this._iterator; if (!this._unfilteredIterationOrder && !this._filter) { iterator.first(); return !iterator.hasNext(); } else if (!this._unfilteredIterationOrder) { for (iterator.first(); iterator.hasNext(); iterator.next()) if (this._filter(iterator.item())) return false; } else { var order = this._unfilteredIterationOrder.constructor === Array ? this._unfilteredIterationOrder : this._unfilteredIterationOrder.slice(0); for (var i = 0, l = order.length; i < l; ++i) { iterator.setIndex(order[i]); if (this._filter(iterator.item())) return false; } } return true; }, item: function() { this._iterator.setIndex(this._iterationOrder[this._position]); return this._iterator.item(); }, get length() { this._createIterationOrder(); return this._iterationOrder.length; }, next: function() { ++this._position; }, serializeItemsRange: function(begin, end) { this._createIterationOrder(); if (begin > end) throw new Error("Start position > end position: " + begin + " > " + end); if (end >= this._iterationOrder.length) end = this._iterationOrder.length; if (this._sortedPrefixLength < end) { this.sort(this._currentComparator, this._sortedPrefixLength, this._iterationOrder.length - 1, end - this._sortedPrefixLength); this._sortedPrefixLength = end; } this._position = begin; var startPosition = this._position; var count = end - begin; var result = new Array(count); for (var i = 0 ; i < count && this.hasNext(); ++i, this.next()) result[i] = this.serializeItem(this.item()); result.length = i; result.totalLength = this._iterationOrder.length; result.startPosition = startPosition; result.endPosition = this._position; return result; }, sortAll: function() { this._createIterationOrder(); if (this._sortedPrefixLength === this._iterationOrder.length) return; this.sort(this._currentComparator, this._sortedPrefixLength, this._iterationOrder.length - 1, this._iterationOrder.length); this._sortedPrefixLength = this._iterationOrder.length; }, sortAndRewind: function(comparator) { this._currentComparator = comparator; this._sortedPrefixLength = 0; this.first(); } } WebInspector.HeapSnapshotFilteredOrderedIterator.prototype.createComparator = function(fieldNames) { return {fieldName1:fieldNames[0], ascending1:fieldNames[1], fieldName2:fieldNames[2], ascending2:fieldNames[3]}; } WebInspector.HeapSnapshotEdgesProvider = function(snapshot, filter, edgesIter) { this.snapshot = snapshot; WebInspector.HeapSnapshotFilteredOrderedIterator.call(this, edgesIter, filter); } WebInspector.HeapSnapshotEdgesProvider.prototype = { serializeItem: function(edge) { return { name: edge.name(), propertyAccessor: edge.toString(), node: WebInspector.HeapSnapshotNodesProvider.prototype.serializeItem(edge.node()), nodeIndex: edge.nodeIndex(), type: edge.type(), distanceToWindow: edge.node().distanceToWindow() }; }, sort: function(comparator, leftBound, rightBound, count) { var fieldName1 = comparator.fieldName1; var fieldName2 = comparator.fieldName2; var ascending1 = comparator.ascending1; var ascending2 = comparator.ascending2; var edgeA = this._iterator.item().clone(); var edgeB = edgeA.clone(); var nodeA = new WebInspector.HeapSnapshotNode(this.snapshot); var nodeB = new WebInspector.HeapSnapshotNode(this.snapshot); function compareEdgeFieldName(ascending, indexA, indexB) { edgeA.edgeIndex = indexA; edgeB.edgeIndex = indexB; if (edgeB.name() === "__proto__") return -1; if (edgeA.name() === "__proto__") return 1; var result = edgeA.hasStringName() === edgeB.hasStringName() ? (edgeA.name() < edgeB.name() ? -1 : (edgeA.name() > edgeB.name() ? 1 : 0)) : (edgeA.hasStringName() ? -1 : 1); return ascending ? result : -result; } function compareNodeField(fieldName, ascending, indexA, indexB) { edgeA.edgeIndex = indexA; nodeA.nodeIndex = edgeA.nodeIndex(); var valueA = nodeA[fieldName](); edgeB.edgeIndex = indexB; nodeB.nodeIndex = edgeB.nodeIndex(); var valueB = nodeB[fieldName](); var result = valueA < valueB ? -1 : (valueA > valueB ? 1 : 0); return ascending ? result : -result; } function compareEdgeAndNode(indexA, indexB) { var result = compareEdgeFieldName(ascending1, indexA, indexB); if (result === 0) result = compareNodeField(fieldName2, ascending2, indexA, indexB); return result; } function compareNodeAndEdge(indexA, indexB) { var result = compareNodeField(fieldName1, ascending1, indexA, indexB); if (result === 0) result = compareEdgeFieldName(ascending2, indexA, indexB); return result; } function compareNodeAndNode(indexA, indexB) { var result = compareNodeField(fieldName1, ascending1, indexA, indexB); if (result === 0) result = compareNodeField(fieldName2, ascending2, indexA, indexB); return result; } if (fieldName1 === "!edgeName") this._iterationOrder.sortRange(compareEdgeAndNode, leftBound, rightBound, count); else if (fieldName2 === "!edgeName") this._iterationOrder.sortRange(compareNodeAndEdge, leftBound, rightBound, count); else this._iterationOrder.sortRange(compareNodeAndNode, leftBound, rightBound, count); }, __proto__: WebInspector.HeapSnapshotFilteredOrderedIterator.prototype } WebInspector.HeapSnapshotNodesProvider = function(snapshot, filter, nodeIndexes) { this.snapshot = snapshot; WebInspector.HeapSnapshotFilteredOrderedIterator.call(this, snapshot._allNodes(), filter, nodeIndexes); } WebInspector.HeapSnapshotNodesProvider.prototype = { nodePosition: function(snapshotObjectId) { this._createIterationOrder(); if (this.isEmpty()) return -1; this.sortAll(); var node = new WebInspector.HeapSnapshotNode(this.snapshot); for (var i = 0; i < this._iterationOrder.length; i++) { node.nodeIndex = this._iterationOrder[i]; if (node.id() === snapshotObjectId) return i; } return -1; }, serializeItem: function(node) { return { id: node.id(), name: node.name(), distanceToWindow: node.distanceToWindow(), nodeIndex: node.nodeIndex, retainedSize: node.retainedSize(), selfSize: node.selfSize(), type: node.type(), flags: node.flags() }; }, sort: function(comparator, leftBound, rightBound, count) { var fieldName1 = comparator.fieldName1; var fieldName2 = comparator.fieldName2; var ascending1 = comparator.ascending1; var ascending2 = comparator.ascending2; var nodeA = new WebInspector.HeapSnapshotNode(this.snapshot); var nodeB = new WebInspector.HeapSnapshotNode(this.snapshot); function sortByNodeField(fieldName, ascending) { var valueOrFunctionA = nodeA[fieldName]; var valueA = typeof valueOrFunctionA !== "function" ? valueOrFunctionA : valueOrFunctionA.call(nodeA); var valueOrFunctionB = nodeB[fieldName]; var valueB = typeof valueOrFunctionB !== "function" ? valueOrFunctionB : valueOrFunctionB.call(nodeB); var result = valueA < valueB ? -1 : (valueA > valueB ? 1 : 0); return ascending ? result : -result; } function sortByComparator(indexA, indexB) { nodeA.nodeIndex = indexA; nodeB.nodeIndex = indexB; var result = sortByNodeField(fieldName1, ascending1); if (result === 0) result = sortByNodeField(fieldName2, ascending2); return result; } this._iterationOrder.sortRange(sortByComparator, leftBound, rightBound, count); }, __proto__: WebInspector.HeapSnapshotFilteredOrderedIterator.prototype } ; WebInspector.HeapSnapshotLoader = function() { this._reset(); } WebInspector.HeapSnapshotLoader.prototype = { dispose: function() { this._reset(); }, _reset: function() { this._json = ""; this._state = "find-snapshot-info"; this._snapshot = {}; }, close: function() { if (this._json) this._parseStringsArray(); }, buildSnapshot: function() { var result = new WebInspector.HeapSnapshot(this._snapshot); this._reset(); return result; }, _parseUintArray: function() { var index = 0; var char0 = "0".charCodeAt(0), char9 = "9".charCodeAt(0), closingBracket = "]".charCodeAt(0); var length = this._json.length; while (true) { while (index < length) { var code = this._json.charCodeAt(index); if (char0 <= code && code <= char9) break; else if (code === closingBracket) { this._json = this._json.slice(index + 1); return false; } ++index; } if (index === length) { this._json = ""; return true; } var nextNumber = 0; var startIndex = index; while (index < length) { var code = this._json.charCodeAt(index); if (char0 > code || code > char9) break; nextNumber *= 10; nextNumber += (code - char0); ++index; } if (index === length) { this._json = this._json.slice(startIndex); return true; } this._array[this._arrayIndex++] = nextNumber; } }, _parseStringsArray: function() { var closingBracketIndex = this._json.lastIndexOf("]"); if (closingBracketIndex === -1) throw new Error("Incomplete JSON"); this._json = this._json.slice(0, closingBracketIndex + 1); this._snapshot.strings = JSON.parse(this._json); }, write: function(chunk) { this._json += chunk; switch (this._state) { case "find-snapshot-info": { var snapshotToken = "\"snapshot\""; var snapshotTokenIndex = this._json.indexOf(snapshotToken); if (snapshotTokenIndex === -1) throw new Error("Snapshot token not found"); this._json = this._json.slice(snapshotTokenIndex + snapshotToken.length + 1); this._state = "parse-snapshot-info"; } case "parse-snapshot-info": { var closingBracketIndex = WebInspector.findBalancedCurlyBrackets(this._json); if (closingBracketIndex === -1) return; this._snapshot.snapshot = (JSON.parse(this._json.slice(0, closingBracketIndex))); this._json = this._json.slice(closingBracketIndex); this._state = "find-nodes"; } case "find-nodes": { var nodesToken = "\"nodes\""; var nodesTokenIndex = this._json.indexOf(nodesToken); if (nodesTokenIndex === -1) return; var bracketIndex = this._json.indexOf("[", nodesTokenIndex); if (bracketIndex === -1) return; this._json = this._json.slice(bracketIndex + 1); var node_fields_count = this._snapshot.snapshot.meta.node_fields.length; var nodes_length = this._snapshot.snapshot.node_count * node_fields_count; this._array = new Uint32Array(nodes_length); this._arrayIndex = 0; this._state = "parse-nodes"; } case "parse-nodes": { if (this._parseUintArray()) return; this._snapshot.nodes = this._array; this._state = "find-edges"; this._array = null; } case "find-edges": { var edgesToken = "\"edges\""; var edgesTokenIndex = this._json.indexOf(edgesToken); if (edgesTokenIndex === -1) return; var bracketIndex = this._json.indexOf("[", edgesTokenIndex); if (bracketIndex === -1) return; this._json = this._json.slice(bracketIndex + 1); var edge_fields_count = this._snapshot.snapshot.meta.edge_fields.length; var edges_length = this._snapshot.snapshot.edge_count * edge_fields_count; this._array = new Uint32Array(edges_length); this._arrayIndex = 0; this._state = "parse-edges"; } case "parse-edges": { if (this._parseUintArray()) return; this._snapshot.edges = this._array; this._array = null; this._state = "find-strings"; } case "find-strings": { var stringsToken = "\"strings\""; var stringsTokenIndex = this._json.indexOf(stringsToken); if (stringsTokenIndex === -1) return; var bracketIndex = this._json.indexOf("[", stringsTokenIndex); if (bracketIndex === -1) return; this._json = this._json.slice(bracketIndex); this._state = "accumulate-strings"; break; } case "accumulate-strings": break; } } }; ; WebInspector.HeapSnapshotWorkerDispatcher = function(globalObject, postMessage) { this._objects = []; this._global = globalObject; this._postMessage = postMessage; } WebInspector.HeapSnapshotWorkerDispatcher.prototype = { _findFunction: function(name) { var path = name.split("."); var result = this._global; for (var i = 0; i < path.length; ++i) result = result[path[i]]; return result; }, dispatchMessage: function(event) { var data = event.data; var response = {callId: data.callId}; try { switch (data.disposition) { case "create": { var constructorFunction = this._findFunction(data.methodName); this._objects[data.objectId] = new constructorFunction(); break; } case "dispose": { delete this._objects[data.objectId]; break; } case "getter": { var object = this._objects[data.objectId]; var result = object[data.methodName]; response.result = result; break; } case "factory": { var object = this._objects[data.objectId]; var result = object[data.methodName].apply(object, data.methodArguments); if (result) this._objects[data.newObjectId] = result; response.result = !!result; break; } case "method": { var object = this._objects[data.objectId]; response.result = object[data.methodName].apply(object, data.methodArguments); break; } } } catch (e) { response.error = e.toString(); response.errorCallStack = e.stack; if (data.methodName) response.errorMethodName = data.methodName; } this._postMessage(response); } }; ; WebInspector.OutputStreamDelegate = function() { } WebInspector.OutputStreamDelegate.prototype = { onTransferStarted: function() { }, onTransferFinished: function() { }, onChunkTransferred: function(reader) { }, onError: function(reader, event) { }, } WebInspector.OutputStream = function() { } WebInspector.OutputStream.prototype = { write: function(data, callback) { }, close: function() { } } WebInspector.ChunkedReader = function() { } WebInspector.ChunkedReader.prototype = { fileSize: function() { }, loadedSize: function() { }, fileName: function() { }, cancel: function() { } } WebInspector.ChunkedFileReader = function(file, chunkSize, delegate) { this._file = file; this._fileSize = file.size; this._loadedSize = 0; this._chunkSize = chunkSize; this._delegate = delegate; this._isCanceled = false; } WebInspector.ChunkedFileReader.prototype = { start: function(output) { this._output = output; this._reader = new FileReader(); this._reader.onload = this._onChunkLoaded.bind(this); this._reader.onerror = this._delegate.onError.bind(this._delegate, this); this._delegate.onTransferStarted(); this._loadChunk(); }, cancel: function() { this._isCanceled = true; }, loadedSize: function() { return this._loadedSize; }, fileSize: function() { return this._fileSize; }, fileName: function() { return this._file.name; }, _onChunkLoaded: function(event) { if (this._isCanceled) return; if (event.target.readyState !== FileReader.DONE) return; var data = event.target.result; this._loadedSize += data.length; this._output.write(data); if (this._isCanceled) return; this._delegate.onChunkTransferred(this); if (this._loadedSize === this._fileSize) { this._file = null; this._reader = null; this._output.close(); this._delegate.onTransferFinished(); return; } this._loadChunk(); }, _loadChunk: function() { var chunkStart = this._loadedSize; var chunkEnd = Math.min(this._fileSize, chunkStart + this._chunkSize) var nextPart = this._file.slice(chunkStart, chunkEnd); this._reader.readAsText(nextPart); } } WebInspector.ChunkedXHRReader = function(url, delegate) { this._url = url; this._delegate = delegate; this._fileSize = 0; this._loadedSize = 0; this._isCanceled = false; } WebInspector.ChunkedXHRReader.prototype = { start: function(output) { this._output = output; this._xhr = new XMLHttpRequest(); this._xhr.open("GET", this._url, true); this._xhr.onload = this._onLoad.bind(this); this._xhr.onprogress = this._onProgress.bind(this); this._xhr.onerror = this._delegate.onError.bind(this._delegate, this); this._xhr.send(null); this._delegate.onTransferStarted(); }, cancel: function() { this._isCanceled = true; this._xhr.abort(); }, loadedSize: function() { return this._loadedSize; }, fileSize: function() { return this._fileSize; }, fileName: function() { return this._url; }, _onProgress: function(event) { if (this._isCanceled) return; if (event.lengthComputable) this._fileSize = event.total; var data = this._xhr.responseText.substring(this._loadedSize); if (!data.length) return; this._loadedSize += data.length; this._output.write(data); if (this._isCanceled) return; this._delegate.onChunkTransferred(this); }, _onLoad: function(event) { this._onProgress(event); if (this._isCanceled) return; this._output.close(); this._delegate.onTransferFinished(); } } WebInspector.createFileSelectorElement = function(callback) { var fileSelectorElement = document.createElement("input"); fileSelectorElement.type = "file"; fileSelectorElement.style.zIndex = -1; fileSelectorElement.style.position = "absolute"; fileSelectorElement.onchange = function(event) { callback(fileSelectorElement.files[0]); }; return fileSelectorElement; } WebInspector.findBalancedCurlyBrackets = function(source, startIndex, lastIndex) { lastIndex = lastIndex || source.length; startIndex = startIndex || 0; var counter = 0; var inString = false; for (var index = startIndex; index < lastIndex; ++index) { var character = source[index]; if (inString) { if (character === "\\") ++index; else if (character === "\"") inString = false; } else { if (character === "\"") inString = true; else if (character === "{") ++counter; else if (character === "}") { if (--counter === 0) return index + 1; } } } return -1; } WebInspector.FileOutputStream = function() { } WebInspector.FileOutputStream.prototype = { open: function(fileName, callback) { this._closed = false; this._writeCallbacks = []; this._fileName = fileName; function callbackWrapper() { WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.SavedURL, callbackWrapper, this); WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); callback(this); } WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, callbackWrapper, this); WebInspector.fileManager.save(this._fileName, "", true); }, write: function(data, callback) { this._writeCallbacks.push(callback); WebInspector.fileManager.append(this._fileName, data); }, close: function() { this._closed = true; if (this._writeCallbacks.length) return; WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); WebInspector.fileManager.close(this._fileName); }, _onAppendDone: function(event) { if (event.data !== this._fileName) return; if (!this._writeCallbacks.length) { if (this._closed) { WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); WebInspector.fileManager.close(this._fileName); } return; } var callback = this._writeCallbacks.shift(); if (callback) callback(this); } } ; Object.isEmpty = function(obj) { for (var i in obj) return false; return true; } Object.values = function(obj) { var keys = Object.keys(obj); var result = []; for (var i = 0; i < keys.length; ++i) result.push(obj[keys[i]]); return result; } String.prototype.hasSubstring = function(string, caseInsensitive) { if (!caseInsensitive) return this.indexOf(string) !== -1; return this.match(new RegExp(string.escapeForRegExp(), "i")); } String.prototype.findAll = function(string) { var matches = []; var i = this.indexOf(string); while (i !== -1) { matches.push(i); i = this.indexOf(string, i + string.length); } return matches; } String.prototype.lineEndings = function() { if (!this._lineEndings) { this._lineEndings = this.findAll("\n"); this._lineEndings.push(this.length); } return this._lineEndings; } String.prototype.escapeCharacters = function(chars) { var foundChar = false; for (var i = 0; i < chars.length; ++i) { if (this.indexOf(chars.charAt(i)) !== -1) { foundChar = true; break; } } if (!foundChar) return this; var result = ""; for (var i = 0; i < this.length; ++i) { if (chars.indexOf(this.charAt(i)) !== -1) result += "\\"; result += this.charAt(i); } return result; } String.prototype.escapeForRegExp = function() { return this.escapeCharacters("^[]{}()\\.$*+?|"); } String.prototype.escapeHTML = function() { return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); } String.prototype.collapseWhitespace = function() { return this.replace(/[\s\xA0]+/g, " "); } String.prototype.trimMiddle = function(maxLength) { if (this.length <= maxLength) return this; var leftHalf = maxLength >> 1; var rightHalf = maxLength - leftHalf - 1; return this.substr(0, leftHalf) + "\u2026" + this.substr(this.length - rightHalf, rightHalf); } String.prototype.trimEnd = function(maxLength) { if (this.length <= maxLength) return this; return this.substr(0, maxLength - 1) + "\u2026"; } String.prototype.trimURL = function(baseURLDomain) { var result = this.replace(/^(https|http|file):\/\//i, ""); if (baseURLDomain) result = result.replace(new RegExp("^" + baseURLDomain.escapeForRegExp(), "i"), ""); return result; } function sanitizeHref(href) { return href && href.trim().toLowerCase().startsWith("javascript:") ? "" : href; } String.prototype.removeURLFragment = function() { var fragmentIndex = this.indexOf("#"); if (fragmentIndex == -1) fragmentIndex = this.length; return this.substring(0, fragmentIndex); } String.prototype.startsWith = function(substring) { return !this.lastIndexOf(substring, 0); } String.prototype.endsWith = function(substring) { return this.indexOf(substring, this.length - substring.length) !== -1; } Number.constrain = function(num, min, max) { if (num < min) num = min; else if (num > max) num = max; return num; } Date.prototype.toISO8601Compact = function() { function leadZero(x) { return x > 9 ? '' + x : '0' + x } return this.getFullYear() + leadZero(this.getMonth() + 1) + leadZero(this.getDate()) + 'T' + leadZero(this.getHours()) + leadZero(this.getMinutes()) + leadZero(this.getSeconds()); } Object.defineProperty(Array.prototype, "remove", { value: function(value, onlyFirst) { if (onlyFirst) { var index = this.indexOf(value); if (index !== -1) this.splice(index, 1); return; } var length = this.length; for (var i = 0; i < length; ++i) { if (this[i] === value) this.splice(i, 1); } } }); Object.defineProperty(Array.prototype, "keySet", { value: function() { var keys = {}; for (var i = 0; i < this.length; ++i) keys[this[i]] = true; return keys; } }); Object.defineProperty(Array.prototype, "upperBound", { value: function(value) { var first = 0; var count = this.length; while (count > 0) { var step = count >> 1; var middle = first + step; if (value >= this[middle]) { first = middle + 1; count -= step + 1; } else count = step; } return first; } }); Object.defineProperty(Array.prototype, "rotate", { value: function(index) { var result = []; for (var i = index; i < index + this.length; ++i) result.push(this[i % this.length]); return result; } }); Object.defineProperty(Uint32Array.prototype, "sort", { value: Array.prototype.sort }); (function() { var partition = { value: function(comparator, left, right, pivotIndex) { function swap(array, i1, i2) { var temp = array[i1]; array[i1] = array[i2]; array[i2] = temp; } var pivotValue = this[pivotIndex]; swap(this, right, pivotIndex); var storeIndex = left; for (var i = left; i < right; ++i) { if (comparator(this[i], pivotValue) < 0) { swap(this, storeIndex, i); ++storeIndex; } } swap(this, right, storeIndex); return storeIndex; } }; Object.defineProperty(Array.prototype, "partition", partition); Object.defineProperty(Uint32Array.prototype, "partition", partition); var sortRange = { value: function(comparator, leftBound, rightBound, k) { function quickSortFirstK(array, comparator, left, right, k) { if (right <= left) return; var pivotIndex = Math.floor(Math.random() * (right - left)) + left; var pivotNewIndex = array.partition(comparator, left, right, pivotIndex); quickSortFirstK(array, comparator, left, pivotNewIndex - 1, k); if (pivotNewIndex < left + k - 1) quickSortFirstK(array, comparator, pivotNewIndex + 1, right, k); } if (leftBound === 0 && rightBound === (this.length - 1) && k === this.length) this.sort(comparator); else quickSortFirstK(this, comparator, leftBound, rightBound, k); return this; } } Object.defineProperty(Array.prototype, "sortRange", sortRange); Object.defineProperty(Uint32Array.prototype, "sortRange", sortRange); })(); Object.defineProperty(Array.prototype, "qselect", { value: function(k, comparator) { if (k < 0 || k >= this.length) return; if (!comparator) comparator = function(a, b) { return a - b; } var low = 0; var high = this.length - 1; for (;;) { var pivotPosition = this.partition(comparator, low, high, Math.floor((high + low) / 2)); if (pivotPosition === k) return this[k]; else if (pivotPosition > k) high = pivotPosition - 1; else low = pivotPosition + 1; } } }); function binarySearch(object, array, comparator) { var first = 0; var last = array.length - 1; while (first <= last) { var mid = (first + last) >> 1; var c = comparator(object, array[mid]); if (c > 0) first = mid + 1; else if (c < 0) last = mid - 1; else return mid; } return -(first + 1); } Object.defineProperty(Array.prototype, "binaryIndexOf", { value: function(value, comparator) { var result = binarySearch(value, this, comparator); return result >= 0 ? result : -1; } }); Object.defineProperty(Array.prototype, "select", { value: function(field) { var result = new Array(this.length); for (var i = 0; i < this.length; ++i) result[i] = this[i][field]; return result; } }); function insertionIndexForObjectInListSortedByFunction(anObject, aList, aFunction) { var index = binarySearch(anObject, aList, aFunction); if (index < 0) return -index - 1; else { while (index > 0 && aFunction(anObject, aList[index - 1]) === 0) index--; return index; } } String.sprintf = function(format, var_arg) { return String.vsprintf(format, Array.prototype.slice.call(arguments, 1)); } String.tokenizeFormatString = function(format, formatters) { var tokens = []; var substitutionIndex = 0; function addStringToken(str) { tokens.push({ type: "string", value: str }); } function addSpecifierToken(specifier, precision, substitutionIndex) { tokens.push({ type: "specifier", specifier: specifier, precision: precision, substitutionIndex: substitutionIndex }); } function isDigit(c) { return !!/[0-9]/.exec(c); } var index = 0; for (var precentIndex = format.indexOf("%", index); precentIndex !== -1; precentIndex = format.indexOf("%", index)) { addStringToken(format.substring(index, precentIndex)); index = precentIndex + 1; if (isDigit(format[index])) { var number = parseInt(format.substring(index), 10); while (isDigit(format[index])) ++index; if (number > 0 && format[index] === "$") { substitutionIndex = (number - 1); ++index; } } var precision = -1; if (format[index] === ".") { ++index; precision = parseInt(format.substring(index), 10); if (isNaN(precision)) precision = 0; while (isDigit(format[index])) ++index; } if (!(format[index] in formatters)) { addStringToken(format.substring(precentIndex, index + 1)); ++index; continue; } addSpecifierToken(format[index], precision, substitutionIndex); ++substitutionIndex; ++index; } addStringToken(format.substring(index)); return tokens; } String.standardFormatters = { d: function(substitution) { return !isNaN(substitution) ? substitution : 0; }, f: function(substitution, token) { if (substitution && token.precision > -1) substitution = substitution.toFixed(token.precision); return !isNaN(substitution) ? substitution : (token.precision > -1 ? Number(0).toFixed(token.precision) : 0); }, s: function(substitution) { return substitution; } } String.vsprintf = function(format, substitutions) { return String.format(format, substitutions, String.standardFormatters, "", function(a, b) { return a + b; }).formattedResult; } String.format = function(format, substitutions, formatters, initialValue, append) { if (!format || !substitutions || !substitutions.length) return { formattedResult: append(initialValue, format), unusedSubstitutions: substitutions }; function prettyFunctionName() { return "String.format(\"" + format + "\", \"" + substitutions.join("\", \"") + "\")"; } function warn(msg) { console.warn(prettyFunctionName() + ": " + msg); } function error(msg) { console.error(prettyFunctionName() + ": " + msg); } var result = initialValue; var tokens = String.tokenizeFormatString(format, formatters); var usedSubstitutionIndexes = {}; for (var i = 0; i < tokens.length; ++i) { var token = tokens[i]; if (token.type === "string") { result = append(result, token.value); continue; } if (token.type !== "specifier") { error("Unknown token type \"" + token.type + "\" found."); continue; } if (token.substitutionIndex >= substitutions.length) { error("not enough substitution arguments. Had " + substitutions.length + " but needed " + (token.substitutionIndex + 1) + ", so substitution was skipped."); result = append(result, "%" + (token.precision > -1 ? token.precision : "") + token.specifier); continue; } usedSubstitutionIndexes[token.substitutionIndex] = true; if (!(token.specifier in formatters)) { warn("unsupported format character \u201C" + token.specifier + "\u201D. Treating as a string."); result = append(result, substitutions[token.substitutionIndex]); continue; } result = append(result, formatters[token.specifier](substitutions[token.substitutionIndex], token)); } var unusedSubstitutions = []; for (var i = 0; i < substitutions.length; ++i) { if (i in usedSubstitutionIndexes) continue; unusedSubstitutions.push(substitutions[i]); } return { formattedResult: result, unusedSubstitutions: unusedSubstitutions }; } function createSearchRegex(query, caseSensitive, isRegex) { var regexFlags = caseSensitive ? "g" : "gi"; var regexObject; if (isRegex) { try { regexObject = new RegExp(query, regexFlags); } catch (e) { } } if (!regexObject) regexObject = createPlainTextSearchRegex(query, regexFlags); return regexObject; } function createPlainTextSearchRegex(query, flags) { var regexSpecialCharacters = "[](){}+-*.,?\\^$|"; var regex = ""; for (var i = 0; i < query.length; ++i) { var c = query.charAt(i); if (regexSpecialCharacters.indexOf(c) != -1) regex += "\\"; regex += c; } return new RegExp(regex, flags || ""); } function countRegexMatches(regex, content) { var text = content; var result = 0; var match; while (text && (match = regex.exec(text))) { if (match[0].length > 0) ++result; text = text.substring(match.index + 1); } return result; } function numberToStringWithSpacesPadding(value, symbolsCount) { var numberString = value.toString(); var paddingLength = Math.max(0, symbolsCount - numberString.length); var paddingString = Array(paddingLength + 1).join("\u00a0"); return paddingString + numberString; } var Map = function() { this._map = {}; this._size = 0; } Map._lastObjectIdentifier = 0; Map.prototype = { put: function(key, value) { var objectIdentifier = key.__identifier; if (!objectIdentifier) { objectIdentifier = ++Map._lastObjectIdentifier; key.__identifier = objectIdentifier; } if (!this._map[objectIdentifier]) ++this._size; this._map[objectIdentifier] = [key, value]; }, remove: function(key) { var result = this._map[key.__identifier]; delete this._map[key.__identifier]; --this._size; return result ? result[1] : undefined; }, keys: function() { return this._list(0); }, values: function() { return this._list(1); }, _list: function(index) { var result = new Array(this._size); var i = 0; for (var objectIdentifier in this._map) result[i++] = this._map[objectIdentifier][index]; return result; }, get: function(key) { var entry = this._map[key.__identifier]; return entry ? entry[1] : undefined; }, size: function() { return this._size; }, clear: function() { this._map = {}; this._size = 0; } } function loadXHR(url, async, callback) { function onReadyStateChanged() { if (xhr.readyState !== XMLHttpRequest.DONE) return; if (xhr.status === 200) { callback(xhr.responseText); return; } callback(null); } var xhr = new XMLHttpRequest(); xhr.open("GET", url, async); if (async) xhr.onreadystatechange = onReadyStateChanged; xhr.send(null); if (!async) { if (xhr.status === 200) return xhr.responseText; return null; } return null; } function StringPool() { this.reset(); } StringPool.prototype = { intern: function(string) { if (string === "__proto__") return "__proto__"; var result = this._strings[string]; if (result === undefined) { this._strings[string] = string; result = string; } return result; }, reset: function() { this._strings = Object.create(null); }, internObjectStrings: function(obj, depthLimit) { if (typeof depthLimit !== "number") depthLimit = 100; else if (--depthLimit < 0) throw "recursion depth limit reached in StringPool.deepIntern(), perhaps attempting to traverse cyclical references?"; for (var field in obj) { switch (typeof obj[field]) { case "string": obj[field] = this.intern(obj[field]); break; case "object": this.internObjectStrings(obj[field], depthLimit); break; } } } } var _importedScripts = {}; function importScript(scriptName) { if (_importedScripts[scriptName]) return; _importedScripts[scriptName] = true; var xhr = new XMLHttpRequest(); xhr.open("GET", scriptName, false); xhr.send(null); var sourceURL = WebInspector.ParsedURL.completeURL(window.location.href, scriptName); window.eval(xhr.responseText + "\n//@ sourceURL=" + sourceURL); } ; function postMessageWrapper(message) { postMessage(message); } WebInspector.WorkerConsole = function() { } WebInspector.WorkerConsole.prototype = { log: function(var_args) { this._postMessage("log", Array.prototype.slice.call(arguments)); }, error: function(var_args) { this._postMessage("error", Array.prototype.slice.call(arguments)); }, info: function(var_args) { this._postMessage("info", Array.prototype.slice.call(arguments)); }, trace: function() { this.log(new Error().stack); }, _postMessage: function(method, args) { var rawMessage = { object: "console", method: method, arguments: args }; postMessageWrapper(rawMessage); } }; var dispatcher = new WebInspector.HeapSnapshotWorkerDispatcher(this, postMessageWrapper); addEventListener("message", dispatcher.dispatchMessage.bind(dispatcher), false); console = new WebInspector.WorkerConsole();
JavaScript
onmessage = function(event) { if (!event.data.method) return; self[event.data.method](event.data.params); }; function format(params) { var indentString = params.indentString || " "; var result = {}; if (params.mimeType === "text/html") { var formatter = new HTMLScriptFormatter(indentString); result = formatter.format(params.content); } else { result.mapping = { original: [0], formatted: [0] }; result.content = formatScript(params.content, result.mapping, 0, 0, indentString); } postMessage(result); } function getChunkCount(totalLength, chunkSize) { if (totalLength <= chunkSize) return 1; var remainder = totalLength % chunkSize; var partialLength = totalLength - remainder; return (partialLength / chunkSize) + (remainder ? 1 : 0); } function outline(params) { const chunkSize = 100000; const totalLength = params.content.length; const lines = params.content.split("\n"); const chunkCount = getChunkCount(totalLength, chunkSize); var outlineChunk = []; var previousIdentifier = null; var previousToken = null; var previousTokenType = null; var currentChunk = 1; var processedChunkCharacters = 0; var addedFunction = false; var isReadingArguments = false; var argumentsText = ""; var currentFunction = null; var scriptTokenizer = new WebInspector.SourceJavaScriptTokenizer(); scriptTokenizer.condition = scriptTokenizer.createInitialCondition(); for (var i = 0; i < lines.length; ++i) { var line = lines[i]; var column = 0; scriptTokenizer.line = line; do { var newColumn = scriptTokenizer.nextToken(column); var tokenType = scriptTokenizer.tokenType; var tokenValue = line.substring(column, newColumn); if (tokenType === "javascript-ident") { previousIdentifier = tokenValue; if (tokenValue && previousToken === "function") { currentFunction = { line: i, name: tokenValue }; addedFunction = true; previousIdentifier = null; } } else if (tokenType === "javascript-keyword") { if (tokenValue === "function") { if (previousIdentifier && (previousToken === "=" || previousToken === ":")) { currentFunction = { line: i, name: previousIdentifier }; addedFunction = true; previousIdentifier = null; } } } else if (tokenValue === "." && previousTokenType === "javascript-ident") previousIdentifier += "."; else if (tokenValue === "(" && addedFunction) isReadingArguments = true; if (isReadingArguments && tokenValue) argumentsText += tokenValue; if (tokenValue === ")" && isReadingArguments) { addedFunction = false; isReadingArguments = false; currentFunction.arguments = argumentsText.replace(/,[\r\n\s]*/g, ", ").replace(/([^,])[\r\n\s]+/g, "$1"); argumentsText = ""; outlineChunk.push(currentFunction); } if (tokenValue.trim().length) { previousToken = tokenValue; previousTokenType = tokenType; } processedChunkCharacters += newColumn - column; column = newColumn; if (processedChunkCharacters >= chunkSize) { postMessage({ chunk: outlineChunk, total: chunkCount, index: currentChunk++ }); outlineChunk = []; processedChunkCharacters = 0; } } while (column < line.length); } postMessage({ chunk: outlineChunk, total: chunkCount, index: chunkCount }); } function formatScript(content, mapping, offset, formattedOffset, indentString) { var formattedContent; try { var tokenizer = new Tokenizer(content); var builder = new FormattedContentBuilder(tokenizer.content(), mapping, offset, formattedOffset, indentString); var formatter = new JavaScriptFormatter(tokenizer, builder); formatter.format(); formattedContent = builder.content(); } catch (e) { formattedContent = content; } return formattedContent; } WebInspector = {}; Array.prototype.keySet = function() { var keys = {}; for (var i = 0; i < this.length; ++i) keys[this[i]] = true; return keys; }; WebInspector.SourceTokenizer = function() { } WebInspector.SourceTokenizer.prototype = { set line(line) { this._line = line; }, set condition(condition) { this._condition = condition; }, get condition() { return this._condition; }, getLexCondition: function() { return this.condition.lexCondition; }, setLexCondition: function(lexCondition) { this.condition.lexCondition = lexCondition; }, _charAt: function(cursor) { return cursor < this._line.length ? this._line.charAt(cursor) : "\n"; }, createInitialCondition: function() { }, nextToken: function(cursor) { } } WebInspector.SourceTokenizer.Registry = function() { this._tokenizers = {}; this._tokenizerConstructors = { "text/css": "SourceCSSTokenizer", "text/html": "SourceHTMLTokenizer", "text/javascript": "SourceJavaScriptTokenizer", "text/x-scss": "SourceCSSTokenizer" }; } WebInspector.SourceTokenizer.Registry.getInstance = function() { if (!WebInspector.SourceTokenizer.Registry._instance) WebInspector.SourceTokenizer.Registry._instance = new WebInspector.SourceTokenizer.Registry(); return WebInspector.SourceTokenizer.Registry._instance; } WebInspector.SourceTokenizer.Registry.prototype = { getTokenizer: function(mimeType) { if (!this._tokenizerConstructors[mimeType]) return null; var tokenizerClass = this._tokenizerConstructors[mimeType]; var tokenizer = this._tokenizers[tokenizerClass]; if (!tokenizer) { tokenizer = new WebInspector[tokenizerClass](); this._tokenizers[tokenizerClass] = tokenizer; } return tokenizer; } } ; WebInspector.SourceHTMLTokenizer = function() { WebInspector.SourceTokenizer.call(this); this._lexConditions = { INITIAL: 0, COMMENT: 1, DOCTYPE: 2, TAG: 3, DSTRING: 4, SSTRING: 5 }; this.case_INITIAL = 1000; this.case_COMMENT = 1001; this.case_DOCTYPE = 1002; this.case_TAG = 1003; this.case_DSTRING = 1004; this.case_SSTRING = 1005; this._parseConditions = { INITIAL: 0, ATTRIBUTE: 1, ATTRIBUTE_VALUE: 2, LINKIFY: 4, A_NODE: 8, SCRIPT: 16, STYLE: 32 }; this.condition = this.createInitialCondition(); } WebInspector.SourceHTMLTokenizer.prototype = { createInitialCondition: function() { return { lexCondition: this._lexConditions.INITIAL, parseCondition: this._parseConditions.INITIAL }; }, set line(line) { if (this._condition.internalJavaScriptTokenizerCondition) { var match = /<\/script/i.exec(line); if (match) { this._internalJavaScriptTokenizer.line = line.substring(0, match.index); } else this._internalJavaScriptTokenizer.line = line; } else if (this._condition.internalCSSTokenizerCondition) { var match = /<\/style/i.exec(line); if (match) { this._internalCSSTokenizer.line = line.substring(0, match.index); } else this._internalCSSTokenizer.line = line; } this._line = line; }, _isExpectingAttribute: function() { return this._condition.parseCondition & this._parseConditions.ATTRIBUTE; }, _isExpectingAttributeValue: function() { return this._condition.parseCondition & this._parseConditions.ATTRIBUTE_VALUE; }, _setExpectingAttribute: function() { if (this._isExpectingAttributeValue()) this._condition.parseCondition ^= this._parseConditions.ATTRIBUTE_VALUE; this._condition.parseCondition |= this._parseConditions.ATTRIBUTE; }, _setExpectingAttributeValue: function() { if (this._isExpectingAttribute()) this._condition.parseCondition ^= this._parseConditions.ATTRIBUTE; this._condition.parseCondition |= this._parseConditions.ATTRIBUTE_VALUE; }, _stringToken: function(cursor, stringEnds) { if (!this._isExpectingAttributeValue()) { this.tokenType = null; return cursor; } this.tokenType = this._attrValueTokenType(); if (stringEnds) this._setExpectingAttribute(); return cursor; }, _attrValueTokenType: function() { if (this._condition.parseCondition & this._parseConditions.LINKIFY) { if (this._condition.parseCondition & this._parseConditions.A_NODE) return "html-external-link"; return "html-resource-link"; } return "html-attribute-value"; }, get _internalJavaScriptTokenizer() { return WebInspector.SourceTokenizer.Registry.getInstance().getTokenizer("text/javascript"); }, get _internalCSSTokenizer() { return WebInspector.SourceTokenizer.Registry.getInstance().getTokenizer("text/css"); }, scriptStarted: function(cursor) { this._condition.internalJavaScriptTokenizerCondition = this._internalJavaScriptTokenizer.createInitialCondition(); }, scriptEnded: function(cursor) { }, styleSheetStarted: function(cursor) { this._condition.internalCSSTokenizerCondition = this._internalCSSTokenizer.createInitialCondition(); }, styleSheetEnded: function(cursor) { }, nextToken: function(cursor) { if (this._condition.internalJavaScriptTokenizerCondition) { this.line = this._line; if (cursor !== this._internalJavaScriptTokenizer._line.length) { this._internalJavaScriptTokenizer.condition = this._condition.internalJavaScriptTokenizerCondition; var result = this._internalJavaScriptTokenizer.nextToken(cursor); this.tokenType = this._internalJavaScriptTokenizer.tokenType; this._condition.internalJavaScriptTokenizerCondition = this._internalJavaScriptTokenizer.condition; return result; } else if (cursor !== this._line.length) delete this._condition.internalJavaScriptTokenizerCondition; } else if (this._condition.internalCSSTokenizerCondition) { this.line = this._line; if (cursor !== this._internalCSSTokenizer._line.length) { this._internalCSSTokenizer.condition = this._condition.internalCSSTokenizerCondition; var result = this._internalCSSTokenizer.nextToken(cursor); this.tokenType = this._internalCSSTokenizer.tokenType; this._condition.internalCSSTokenizerCondition = this._internalCSSTokenizer.condition; return result; } else if (cursor !== this._line.length) delete this._condition.internalCSSTokenizerCondition; } var cursorOnEnter = cursor; var gotoCase = 1; var YYMARKER; while (1) { switch (gotoCase) { case 1: var yych; var yyaccept = 0; if (this.getLexCondition() < 3) { if (this.getLexCondition() < 1) { { gotoCase = this.case_INITIAL; continue; }; } else { if (this.getLexCondition() < 2) { { gotoCase = this.case_COMMENT; continue; }; } else { { gotoCase = this.case_DOCTYPE; continue; }; } } } else { if (this.getLexCondition() < 4) { { gotoCase = this.case_TAG; continue; }; } else { if (this.getLexCondition() < 5) { { gotoCase = this.case_DSTRING; continue; }; } else { { gotoCase = this.case_SSTRING; continue; }; } } } case this.case_COMMENT: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 4; continue; }; { gotoCase = 3; continue; }; } else { if (yych <= '\r') { gotoCase = 4; continue; }; if (yych == '-') { gotoCase = 6; continue; }; { gotoCase = 3; continue; }; } case 2: { this.tokenType = "html-comment"; return cursor; } case 3: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 9; continue; }; case 4: ++cursor; case 5: { this.tokenType = null; return cursor; } case 6: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych != '-') { gotoCase = 5; continue; }; case 7: ++cursor; yych = this._charAt(cursor); if (yych == '>') { gotoCase = 10; continue; }; case 8: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 9: if (yych <= '\f') { if (yych == '\n') { gotoCase = 2; continue; }; { gotoCase = 8; continue; }; } else { if (yych <= '\r') { gotoCase = 2; continue; }; if (yych == '-') { gotoCase = 12; continue; }; { gotoCase = 8; continue; }; } case 10: ++cursor; this.setLexCondition(this._lexConditions.INITIAL); { this.tokenType = "html-comment"; return cursor; } case 12: ++cursor; yych = this._charAt(cursor); if (yych == '-') { gotoCase = 7; continue; }; cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 2; continue; }; } else { { gotoCase = 5; continue; }; } case this.case_DOCTYPE: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 18; continue; }; { gotoCase = 17; continue; }; } else { if (yych <= '\r') { gotoCase = 18; continue; }; if (yych == '>') { gotoCase = 20; continue; }; { gotoCase = 17; continue; }; } case 16: { this.tokenType = "html-doctype"; return cursor; } case 17: yych = this._charAt(++cursor); { gotoCase = 23; continue; }; case 18: ++cursor; { this.tokenType = null; return cursor; } case 20: ++cursor; this.setLexCondition(this._lexConditions.INITIAL); { this.tokenType = "html-doctype"; return cursor; } case 22: ++cursor; yych = this._charAt(cursor); case 23: if (yych <= '\f') { if (yych == '\n') { gotoCase = 16; continue; }; { gotoCase = 22; continue; }; } else { if (yych <= '\r') { gotoCase = 16; continue; }; if (yych == '>') { gotoCase = 16; continue; }; { gotoCase = 22; continue; }; } case this.case_DSTRING: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 28; continue; }; { gotoCase = 27; continue; }; } else { if (yych <= '\r') { gotoCase = 28; continue; }; if (yych == '"') { gotoCase = 30; continue; }; { gotoCase = 27; continue; }; } case 26: { return this._stringToken(cursor); } case 27: yych = this._charAt(++cursor); { gotoCase = 34; continue; }; case 28: ++cursor; { this.tokenType = null; return cursor; } case 30: ++cursor; case 31: this.setLexCondition(this._lexConditions.TAG); { return this._stringToken(cursor, true); } case 32: yych = this._charAt(++cursor); { gotoCase = 31; continue; }; case 33: ++cursor; yych = this._charAt(cursor); case 34: if (yych <= '\f') { if (yych == '\n') { gotoCase = 26; continue; }; { gotoCase = 33; continue; }; } else { if (yych <= '\r') { gotoCase = 26; continue; }; if (yych == '"') { gotoCase = 32; continue; }; { gotoCase = 33; continue; }; } case this.case_INITIAL: yych = this._charAt(cursor); if (yych == '<') { gotoCase = 39; continue; }; ++cursor; { this.tokenType = null; return cursor; } case 39: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '/') { if (yych == '!') { gotoCase = 44; continue; }; if (yych >= '/') { gotoCase = 41; continue; }; } else { if (yych <= 'S') { if (yych >= 'S') { gotoCase = 42; continue; }; } else { if (yych == 's') { gotoCase = 42; continue; }; } } case 40: this.setLexCondition(this._lexConditions.TAG); { if (this._condition.parseCondition & (this._parseConditions.SCRIPT | this._parseConditions.STYLE)) { this.setLexCondition(this._lexConditions.INITIAL); this.tokenType = null; return cursor; } this._condition.parseCondition = this._parseConditions.INITIAL; this.tokenType = "html-tag"; return cursor; } case 41: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == 'S') { gotoCase = 73; continue; }; if (yych == 's') { gotoCase = 73; continue; }; { gotoCase = 40; continue; }; case 42: yych = this._charAt(++cursor); if (yych <= 'T') { if (yych == 'C') { gotoCase = 62; continue; }; if (yych >= 'T') { gotoCase = 63; continue; }; } else { if (yych <= 'c') { if (yych >= 'c') { gotoCase = 62; continue; }; } else { if (yych == 't') { gotoCase = 63; continue; }; } } case 43: cursor = YYMARKER; { gotoCase = 40; continue; }; case 44: yych = this._charAt(++cursor); if (yych <= 'C') { if (yych != '-') { gotoCase = 43; continue; }; } else { if (yych <= 'D') { gotoCase = 46; continue; }; if (yych == 'd') { gotoCase = 46; continue; }; { gotoCase = 43; continue; }; } yych = this._charAt(++cursor); if (yych == '-') { gotoCase = 54; continue; }; { gotoCase = 43; continue; }; case 46: yych = this._charAt(++cursor); if (yych == 'O') { gotoCase = 47; continue; }; if (yych != 'o') { gotoCase = 43; continue; }; case 47: yych = this._charAt(++cursor); if (yych == 'C') { gotoCase = 48; continue; }; if (yych != 'c') { gotoCase = 43; continue; }; case 48: yych = this._charAt(++cursor); if (yych == 'T') { gotoCase = 49; continue; }; if (yych != 't') { gotoCase = 43; continue; }; case 49: yych = this._charAt(++cursor); if (yych == 'Y') { gotoCase = 50; continue; }; if (yych != 'y') { gotoCase = 43; continue; }; case 50: yych = this._charAt(++cursor); if (yych == 'P') { gotoCase = 51; continue; }; if (yych != 'p') { gotoCase = 43; continue; }; case 51: yych = this._charAt(++cursor); if (yych == 'E') { gotoCase = 52; continue; }; if (yych != 'e') { gotoCase = 43; continue; }; case 52: ++cursor; this.setLexCondition(this._lexConditions.DOCTYPE); { this.tokenType = "html-doctype"; return cursor; } case 54: ++cursor; yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 57; continue; }; { gotoCase = 54; continue; }; } else { if (yych <= '\r') { gotoCase = 57; continue; }; if (yych != '-') { gotoCase = 54; continue; }; } ++cursor; yych = this._charAt(cursor); if (yych == '-') { gotoCase = 59; continue; }; { gotoCase = 43; continue; }; case 57: ++cursor; this.setLexCondition(this._lexConditions.COMMENT); { this.tokenType = "html-comment"; return cursor; } case 59: ++cursor; yych = this._charAt(cursor); if (yych != '>') { gotoCase = 54; continue; }; ++cursor; { this.tokenType = "html-comment"; return cursor; } case 62: yych = this._charAt(++cursor); if (yych == 'R') { gotoCase = 68; continue; }; if (yych == 'r') { gotoCase = 68; continue; }; { gotoCase = 43; continue; }; case 63: yych = this._charAt(++cursor); if (yych == 'Y') { gotoCase = 64; continue; }; if (yych != 'y') { gotoCase = 43; continue; }; case 64: yych = this._charAt(++cursor); if (yych == 'L') { gotoCase = 65; continue; }; if (yych != 'l') { gotoCase = 43; continue; }; case 65: yych = this._charAt(++cursor); if (yych == 'E') { gotoCase = 66; continue; }; if (yych != 'e') { gotoCase = 43; continue; }; case 66: ++cursor; this.setLexCondition(this._lexConditions.TAG); { if (this._condition.parseCondition & this._parseConditions.STYLE) { this.setLexCondition(this._lexConditions.INITIAL); this.tokenType = null; return cursor; } this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.STYLE; this._setExpectingAttribute(); return cursor; } case 68: yych = this._charAt(++cursor); if (yych == 'I') { gotoCase = 69; continue; }; if (yych != 'i') { gotoCase = 43; continue; }; case 69: yych = this._charAt(++cursor); if (yych == 'P') { gotoCase = 70; continue; }; if (yych != 'p') { gotoCase = 43; continue; }; case 70: yych = this._charAt(++cursor); if (yych == 'T') { gotoCase = 71; continue; }; if (yych != 't') { gotoCase = 43; continue; }; case 71: ++cursor; this.setLexCondition(this._lexConditions.TAG); { if (this._condition.parseCondition & this._parseConditions.SCRIPT) { this.setLexCondition(this._lexConditions.INITIAL); this.tokenType = null; return cursor; } this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.SCRIPT; this._setExpectingAttribute(); return cursor; } case 73: yych = this._charAt(++cursor); if (yych <= 'T') { if (yych == 'C') { gotoCase = 75; continue; }; if (yych <= 'S') { gotoCase = 43; continue; }; } else { if (yych <= 'c') { if (yych <= 'b') { gotoCase = 43; continue; }; { gotoCase = 75; continue; }; } else { if (yych != 't') { gotoCase = 43; continue; }; } } yych = this._charAt(++cursor); if (yych == 'Y') { gotoCase = 81; continue; }; if (yych == 'y') { gotoCase = 81; continue; }; { gotoCase = 43; continue; }; case 75: yych = this._charAt(++cursor); if (yych == 'R') { gotoCase = 76; continue; }; if (yych != 'r') { gotoCase = 43; continue; }; case 76: yych = this._charAt(++cursor); if (yych == 'I') { gotoCase = 77; continue; }; if (yych != 'i') { gotoCase = 43; continue; }; case 77: yych = this._charAt(++cursor); if (yych == 'P') { gotoCase = 78; continue; }; if (yych != 'p') { gotoCase = 43; continue; }; case 78: yych = this._charAt(++cursor); if (yych == 'T') { gotoCase = 79; continue; }; if (yych != 't') { gotoCase = 43; continue; }; case 79: ++cursor; this.setLexCondition(this._lexConditions.TAG); { this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.INITIAL; this.scriptEnded(cursor - 8); return cursor; } case 81: yych = this._charAt(++cursor); if (yych == 'L') { gotoCase = 82; continue; }; if (yych != 'l') { gotoCase = 43; continue; }; case 82: yych = this._charAt(++cursor); if (yych == 'E') { gotoCase = 83; continue; }; if (yych != 'e') { gotoCase = 43; continue; }; case 83: ++cursor; this.setLexCondition(this._lexConditions.TAG); { this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.INITIAL; this.styleSheetEnded(cursor - 7); return cursor; } case this.case_SSTRING: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 89; continue; }; { gotoCase = 88; continue; }; } else { if (yych <= '\r') { gotoCase = 89; continue; }; if (yych == '\'') { gotoCase = 91; continue; }; { gotoCase = 88; continue; }; } case 87: { return this._stringToken(cursor); } case 88: yych = this._charAt(++cursor); { gotoCase = 95; continue; }; case 89: ++cursor; { this.tokenType = null; return cursor; } case 91: ++cursor; case 92: this.setLexCondition(this._lexConditions.TAG); { return this._stringToken(cursor, true); } case 93: yych = this._charAt(++cursor); { gotoCase = 92; continue; }; case 94: ++cursor; yych = this._charAt(cursor); case 95: if (yych <= '\f') { if (yych == '\n') { gotoCase = 87; continue; }; { gotoCase = 94; continue; }; } else { if (yych <= '\r') { gotoCase = 87; continue; }; if (yych == '\'') { gotoCase = 93; continue; }; { gotoCase = 94; continue; }; } case this.case_TAG: yych = this._charAt(cursor); if (yych <= '&') { if (yych <= '\r') { if (yych == '\n') { gotoCase = 100; continue; }; if (yych >= '\r') { gotoCase = 100; continue; }; } else { if (yych <= ' ') { if (yych >= ' ') { gotoCase = 100; continue; }; } else { if (yych == '"') { gotoCase = 102; continue; }; } } } else { if (yych <= '>') { if (yych <= ';') { if (yych <= '\'') { gotoCase = 103; continue; }; } else { if (yych <= '<') { gotoCase = 100; continue; }; if (yych <= '=') { gotoCase = 104; continue; }; { gotoCase = 106; continue; }; } } else { if (yych <= '[') { if (yych >= '[') { gotoCase = 100; continue; }; } else { if (yych == ']') { gotoCase = 100; continue; }; } } } ++cursor; yych = this._charAt(cursor); { gotoCase = 119; continue; }; case 99: { if (this._condition.parseCondition === this._parseConditions.SCRIPT || this._condition.parseCondition === this._parseConditions.STYLE) { this.tokenType = null; return cursor; } if (this._condition.parseCondition === this._parseConditions.INITIAL) { this.tokenType = "html-tag"; this._setExpectingAttribute(); var token = this._line.substring(cursorOnEnter, cursor); if (token === "a") this._condition.parseCondition |= this._parseConditions.A_NODE; else if (this._condition.parseCondition & this._parseConditions.A_NODE) this._condition.parseCondition ^= this._parseConditions.A_NODE; } else if (this._isExpectingAttribute()) { var token = this._line.substring(cursorOnEnter, cursor); if (token === "href" || token === "src") this._condition.parseCondition |= this._parseConditions.LINKIFY; else if (this._condition.parseCondition |= this._parseConditions.LINKIFY) this._condition.parseCondition ^= this._parseConditions.LINKIFY; this.tokenType = "html-attribute-name"; } else if (this._isExpectingAttributeValue()) this.tokenType = this._attrValueTokenType(); else this.tokenType = null; return cursor; } case 100: ++cursor; { this.tokenType = null; return cursor; } case 102: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 115; continue; }; case 103: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 109; continue; }; case 104: ++cursor; { if (this._isExpectingAttribute()) this._setExpectingAttributeValue(); this.tokenType = null; return cursor; } case 106: ++cursor; this.setLexCondition(this._lexConditions.INITIAL); { this.tokenType = "html-tag"; if (this._condition.parseCondition & this._parseConditions.SCRIPT) { this.scriptStarted(cursor); return cursor; } if (this._condition.parseCondition & this._parseConditions.STYLE) { this.styleSheetStarted(cursor); return cursor; } this._condition.parseCondition = this._parseConditions.INITIAL; return cursor; } case 108: ++cursor; yych = this._charAt(cursor); case 109: if (yych <= '\f') { if (yych != '\n') { gotoCase = 108; continue; }; } else { if (yych <= '\r') { gotoCase = 110; continue; }; if (yych == '\'') { gotoCase = 112; continue; }; { gotoCase = 108; continue; }; } case 110: ++cursor; this.setLexCondition(this._lexConditions.SSTRING); { return this._stringToken(cursor); } case 112: ++cursor; { return this._stringToken(cursor, true); } case 114: ++cursor; yych = this._charAt(cursor); case 115: if (yych <= '\f') { if (yych != '\n') { gotoCase = 114; continue; }; } else { if (yych <= '\r') { gotoCase = 116; continue; }; if (yych == '"') { gotoCase = 112; continue; }; { gotoCase = 114; continue; }; } case 116: ++cursor; this.setLexCondition(this._lexConditions.DSTRING); { return this._stringToken(cursor); } case 118: ++cursor; yych = this._charAt(cursor); case 119: if (yych <= '"') { if (yych <= '\r') { if (yych == '\n') { gotoCase = 99; continue; }; if (yych <= '\f') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } else { if (yych == ' ') { gotoCase = 99; continue; }; if (yych <= '!') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } } else { if (yych <= '>') { if (yych == '\'') { gotoCase = 99; continue; }; if (yych <= ';') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } else { if (yych <= '[') { if (yych <= 'Z') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } else { if (yych == ']') { gotoCase = 99; continue; }; { gotoCase = 118; continue; }; } } } } } }, __proto__: WebInspector.SourceTokenizer.prototype } ; WebInspector.SourceJavaScriptTokenizer = function() { WebInspector.SourceTokenizer.call(this); this._lexConditions = { DIV: 0, NODIV: 1, COMMENT: 2, DSTRING: 3, SSTRING: 4, REGEX: 5 }; this.case_DIV = 1000; this.case_NODIV = 1001; this.case_COMMENT = 1002; this.case_DSTRING = 1003; this.case_SSTRING = 1004; this.case_REGEX = 1005; this.condition = this.createInitialCondition(); } WebInspector.SourceJavaScriptTokenizer.Keywords = [ "null", "true", "false", "break", "case", "catch", "const", "default", "finally", "for", "instanceof", "new", "var", "continue", "function", "return", "void", "delete", "if", "this", "do", "while", "else", "in", "switch", "throw", "try", "typeof", "debugger", "class", "enum", "export", "extends", "import", "super", "get", "set", "with" ].keySet(); WebInspector.SourceJavaScriptTokenizer.prototype = { createInitialCondition: function() { return { lexCondition: this._lexConditions.NODIV }; }, nextToken: function(cursor) { var cursorOnEnter = cursor; var gotoCase = 1; var YYMARKER; while (1) { switch (gotoCase) { case 1: var yych; var yyaccept = 0; if (this.getLexCondition() < 3) { if (this.getLexCondition() < 1) { { gotoCase = this.case_DIV; continue; }; } else { if (this.getLexCondition() < 2) { { gotoCase = this.case_NODIV; continue; }; } else { { gotoCase = this.case_COMMENT; continue; }; } } } else { if (this.getLexCondition() < 4) { { gotoCase = this.case_DSTRING; continue; }; } else { if (this.getLexCondition() < 5) { { gotoCase = this.case_SSTRING; continue; }; } else { { gotoCase = this.case_REGEX; continue; }; } } } case this.case_COMMENT: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 4; continue; }; { gotoCase = 3; continue; }; } else { if (yych <= '\r') { gotoCase = 4; continue; }; if (yych == '*') { gotoCase = 6; continue; }; { gotoCase = 3; continue; }; } case 2: { this.tokenType = "javascript-comment"; return cursor; } case 3: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 12; continue; }; case 4: ++cursor; { this.tokenType = null; return cursor; } case 6: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych == '*') { gotoCase = 9; continue; }; if (yych != '/') { gotoCase = 11; continue; }; case 7: ++cursor; this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-comment"; return cursor; } case 9: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 9; continue; }; if (yych == '/') { gotoCase = 7; continue; }; case 11: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 12: if (yych <= '\f') { if (yych == '\n') { gotoCase = 2; continue; }; { gotoCase = 11; continue; }; } else { if (yych <= '\r') { gotoCase = 2; continue; }; if (yych == '*') { gotoCase = 9; continue; }; { gotoCase = 11; continue; }; } case this.case_DIV: yych = this._charAt(cursor); if (yych <= '9') { if (yych <= '(') { if (yych <= '#') { if (yych <= ' ') { gotoCase = 15; continue; }; if (yych <= '!') { gotoCase = 17; continue; }; if (yych <= '"') { gotoCase = 19; continue; }; } else { if (yych <= '%') { if (yych <= '$') { gotoCase = 20; continue; }; { gotoCase = 22; continue; }; } else { if (yych <= '&') { gotoCase = 23; continue; }; if (yych <= '\'') { gotoCase = 24; continue; }; { gotoCase = 25; continue; }; } } } else { if (yych <= ',') { if (yych <= ')') { gotoCase = 26; continue; }; if (yych <= '*') { gotoCase = 28; continue; }; if (yych <= '+') { gotoCase = 29; continue; }; { gotoCase = 25; continue; }; } else { if (yych <= '.') { if (yych <= '-') { gotoCase = 30; continue; }; { gotoCase = 31; continue; }; } else { if (yych <= '/') { gotoCase = 32; continue; }; if (yych <= '0') { gotoCase = 34; continue; }; { gotoCase = 36; continue; }; } } } } else { if (yych <= '\\') { if (yych <= '>') { if (yych <= ';') { gotoCase = 25; continue; }; if (yych <= '<') { gotoCase = 37; continue; }; if (yych <= '=') { gotoCase = 38; continue; }; { gotoCase = 39; continue; }; } else { if (yych <= '@') { if (yych <= '?') { gotoCase = 25; continue; }; } else { if (yych <= 'Z') { gotoCase = 20; continue; }; if (yych <= '[') { gotoCase = 25; continue; }; { gotoCase = 40; continue; }; } } } else { if (yych <= 'z') { if (yych <= '^') { if (yych <= ']') { gotoCase = 25; continue; }; { gotoCase = 41; continue; }; } else { if (yych != '`') { gotoCase = 20; continue; }; } } else { if (yych <= '|') { if (yych <= '{') { gotoCase = 25; continue; }; { gotoCase = 42; continue; }; } else { if (yych <= '~') { gotoCase = 25; continue; }; if (yych >= 0x80) { gotoCase = 20; continue; }; } } } } case 15: ++cursor; case 16: { this.tokenType = null; return cursor; } case 17: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 115; continue; }; case 18: this.setLexCondition(this._lexConditions.NODIV); { var token = this._line.charAt(cursorOnEnter); if (token === "{") this.tokenType = "block-start"; else if (token === "}") this.tokenType = "block-end"; else this.tokenType = null; return cursor; } case 19: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 16; continue; }; if (yych == '\r') { gotoCase = 16; continue; }; { gotoCase = 107; continue; }; case 20: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 50; continue; }; case 21: { var token = this._line.substring(cursorOnEnter, cursor); if (WebInspector.SourceJavaScriptTokenizer.Keywords[token] === true && token !== "__proto__") this.tokenType = "javascript-keyword"; else this.tokenType = "javascript-ident"; return cursor; } case 22: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 23: yych = this._charAt(++cursor); if (yych == '&') { gotoCase = 43; continue; }; if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 24: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 16; continue; }; if (yych == '\r') { gotoCase = 16; continue; }; { gotoCase = 96; continue; }; case 25: yych = this._charAt(++cursor); { gotoCase = 18; continue; }; case 26: ++cursor; { this.tokenType = null; return cursor; } case 28: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 29: yych = this._charAt(++cursor); if (yych == '+') { gotoCase = 43; continue; }; if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 30: yych = this._charAt(++cursor); if (yych == '-') { gotoCase = 43; continue; }; if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 31: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 18; continue; }; if (yych <= '9') { gotoCase = 89; continue; }; { gotoCase = 18; continue; }; case 32: yyaccept = 2; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '.') { if (yych == '*') { gotoCase = 78; continue; }; } else { if (yych <= '/') { gotoCase = 80; continue; }; if (yych == '=') { gotoCase = 77; continue; }; } case 33: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = null; return cursor; } case 34: yyaccept = 3; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'E') { if (yych <= '/') { if (yych == '.') { gotoCase = 63; continue; }; } else { if (yych <= '7') { gotoCase = 72; continue; }; if (yych >= 'E') { gotoCase = 62; continue; }; } } else { if (yych <= 'd') { if (yych == 'X') { gotoCase = 74; continue; }; } else { if (yych <= 'e') { gotoCase = 62; continue; }; if (yych == 'x') { gotoCase = 74; continue; }; } } case 35: { this.tokenType = "javascript-number"; return cursor; } case 36: yyaccept = 3; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 63; continue; }; if (yych <= '/') { gotoCase = 35; continue; }; { gotoCase = 60; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 35; continue; }; { gotoCase = 62; continue; }; } else { if (yych == 'e') { gotoCase = 62; continue; }; { gotoCase = 35; continue; }; } } case 37: yych = this._charAt(++cursor); if (yych <= ';') { gotoCase = 18; continue; }; if (yych <= '<') { gotoCase = 59; continue; }; if (yych <= '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 38: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 58; continue; }; { gotoCase = 18; continue; }; case 39: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 18; continue; }; if (yych <= '=') { gotoCase = 43; continue; }; if (yych <= '>') { gotoCase = 56; continue; }; { gotoCase = 18; continue; }; case 40: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == 'u') { gotoCase = 44; continue; }; { gotoCase = 16; continue; }; case 41: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 42: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; if (yych != '|') { gotoCase = 18; continue; }; case 43: yych = this._charAt(++cursor); { gotoCase = 18; continue; }; case 44: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 46; continue; }; } else { if (yych <= 'F') { gotoCase = 46; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 46; continue; }; } case 45: cursor = YYMARKER; if (yyaccept <= 1) { if (yyaccept <= 0) { { gotoCase = 16; continue; }; } else { { gotoCase = 21; continue; }; } } else { if (yyaccept <= 2) { { gotoCase = 33; continue; }; } else { { gotoCase = 35; continue; }; } } case 46: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 47; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 47: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 48; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 48: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 49; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 49: yyaccept = 1; YYMARKER = ++cursor; yych = this._charAt(cursor); case 50: if (yych <= '[') { if (yych <= '/') { if (yych == '$') { gotoCase = 49; continue; }; { gotoCase = 21; continue; }; } else { if (yych <= '9') { gotoCase = 49; continue; }; if (yych <= '@') { gotoCase = 21; continue; }; if (yych <= 'Z') { gotoCase = 49; continue; }; { gotoCase = 21; continue; }; } } else { if (yych <= '_') { if (yych <= '\\') { gotoCase = 51; continue; }; if (yych <= '^') { gotoCase = 21; continue; }; { gotoCase = 49; continue; }; } else { if (yych <= '`') { gotoCase = 21; continue; }; if (yych <= 'z') { gotoCase = 49; continue; }; if (yych <= String.fromCharCode(0x7F)) { gotoCase = 21; continue; }; { gotoCase = 49; continue; }; } } case 51: ++cursor; yych = this._charAt(cursor); if (yych != 'u') { gotoCase = 45; continue; }; ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 53; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 53: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 54; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 54: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 55; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 55: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 49; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 49; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 49; continue; }; { gotoCase = 45; continue; }; } case 56: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 18; continue; }; if (yych <= '=') { gotoCase = 43; continue; }; if (yych >= '?') { gotoCase = 18; continue; }; yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 58: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 59: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 60: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 63; continue; }; if (yych <= '/') { gotoCase = 35; continue; }; { gotoCase = 60; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 35; continue; }; } else { if (yych != 'e') { gotoCase = 35; continue; }; } } case 62: yych = this._charAt(++cursor); if (yych <= ',') { if (yych == '+') { gotoCase = 69; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= '-') { gotoCase = 69; continue; }; if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 70; continue; }; { gotoCase = 45; continue; }; } case 63: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 63; continue; }; { gotoCase = 35; continue; }; } else { if (yych <= 'E') { gotoCase = 65; continue; }; if (yych != 'e') { gotoCase = 35; continue; }; } case 65: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 45; continue; }; } else { if (yych <= '-') { gotoCase = 66; continue; }; if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 67; continue; }; { gotoCase = 45; continue; }; } case 66: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; case 67: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 67; continue; }; { gotoCase = 35; continue; }; case 69: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; case 70: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 70; continue; }; { gotoCase = 35; continue; }; case 72: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '7') { gotoCase = 72; continue; }; { gotoCase = 35; continue; }; case 74: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 75; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 75: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 75; continue; }; { gotoCase = 35; continue; }; } else { if (yych <= 'F') { gotoCase = 75; continue; }; if (yych <= '`') { gotoCase = 35; continue; }; if (yych <= 'f') { gotoCase = 75; continue; }; { gotoCase = 35; continue; }; } case 77: yych = this._charAt(++cursor); { gotoCase = 33; continue; }; case 78: ++cursor; yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 85; continue; }; { gotoCase = 78; continue; }; } else { if (yych <= '\r') { gotoCase = 85; continue; }; if (yych == '*') { gotoCase = 83; continue; }; { gotoCase = 78; continue; }; } case 80: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 82; continue; }; if (yych != '\r') { gotoCase = 80; continue; }; case 82: { this.tokenType = "javascript-comment"; return cursor; } case 83: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 83; continue; }; if (yych == '/') { gotoCase = 87; continue; }; { gotoCase = 78; continue; }; case 85: ++cursor; this.setLexCondition(this._lexConditions.COMMENT); { this.tokenType = "javascript-comment"; return cursor; } case 87: ++cursor; { this.tokenType = "javascript-comment"; return cursor; } case 89: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 89; continue; }; { gotoCase = 35; continue; }; } else { if (yych <= 'E') { gotoCase = 91; continue; }; if (yych != 'e') { gotoCase = 35; continue; }; } case 91: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 45; continue; }; } else { if (yych <= '-') { gotoCase = 92; continue; }; if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 93; continue; }; { gotoCase = 45; continue; }; } case 92: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; case 93: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 93; continue; }; { gotoCase = 35; continue; }; case 95: ++cursor; yych = this._charAt(cursor); case 96: if (yych <= '\r') { if (yych == '\n') { gotoCase = 45; continue; }; if (yych <= '\f') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 95; continue; }; { gotoCase = 98; continue; }; } else { if (yych != '\\') { gotoCase = 95; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 45; continue; }; { gotoCase = 101; continue; }; } else { if (yych == '\r') { gotoCase = 101; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 95; continue; }; if (yych <= '&') { gotoCase = 45; continue; }; { gotoCase = 95; continue; }; } else { if (yych == '\\') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 95; continue; }; if (yych <= 'e') { gotoCase = 45; continue; }; { gotoCase = 95; continue; }; } else { if (yych == 'n') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 45; continue; }; { gotoCase = 95; continue; }; } else { if (yych <= 'u') { gotoCase = 100; continue; }; if (yych <= 'v') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } } } case 98: ++cursor; { this.tokenType = "javascript-string"; return cursor; } case 100: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 103; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 103; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 103; continue; }; { gotoCase = 45; continue; }; } case 101: ++cursor; this.setLexCondition(this._lexConditions.SSTRING); { this.tokenType = "javascript-string"; return cursor; } case 103: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 104; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 104: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 105; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 105: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 95; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } case 106: ++cursor; yych = this._charAt(cursor); case 107: if (yych <= '\r') { if (yych == '\n') { gotoCase = 45; continue; }; if (yych <= '\f') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 106; continue; }; { gotoCase = 98; continue; }; } else { if (yych != '\\') { gotoCase = 106; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 45; continue; }; { gotoCase = 110; continue; }; } else { if (yych == '\r') { gotoCase = 110; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 106; continue; }; if (yych <= '&') { gotoCase = 45; continue; }; { gotoCase = 106; continue; }; } else { if (yych == '\\') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 106; continue; }; if (yych <= 'e') { gotoCase = 45; continue; }; { gotoCase = 106; continue; }; } else { if (yych == 'n') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 45; continue; }; { gotoCase = 106; continue; }; } else { if (yych <= 'u') { gotoCase = 109; continue; }; if (yych <= 'v') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } } } case 109: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 112; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 112; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 112; continue; }; { gotoCase = 45; continue; }; } case 110: ++cursor; this.setLexCondition(this._lexConditions.DSTRING); { this.tokenType = "javascript-string"; return cursor; } case 112: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 113; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 113: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 114; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 114: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 106; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } case 115: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case this.case_DSTRING: yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 120; continue; }; if (yych <= '\f') { gotoCase = 119; continue; }; { gotoCase = 120; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 119; continue; }; { gotoCase = 122; continue; }; } else { if (yych == '\\') { gotoCase = 124; continue; }; { gotoCase = 119; continue; }; } } case 118: { this.tokenType = "javascript-string"; return cursor; } case 119: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 126; continue; }; case 120: ++cursor; case 121: { this.tokenType = null; return cursor; } case 122: ++cursor; case 123: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-string"; return cursor; } case 124: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 125; continue; }; if (yych <= '&') { gotoCase = 121; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 121; continue; }; } else { if (yych != 'b') { gotoCase = 121; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych >= 'g') { gotoCase = 121; continue; }; } else { if (yych <= 'n') { gotoCase = 125; continue; }; if (yych <= 'q') { gotoCase = 121; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 121; continue; }; } else { if (yych <= 'u') { gotoCase = 127; continue; }; if (yych >= 'w') { gotoCase = 121; continue; }; } } } case 125: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 126: if (yych <= '\r') { if (yych == '\n') { gotoCase = 118; continue; }; if (yych <= '\f') { gotoCase = 125; continue; }; { gotoCase = 118; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 125; continue; }; { gotoCase = 133; continue; }; } else { if (yych == '\\') { gotoCase = 132; continue; }; { gotoCase = 125; continue; }; } } case 127: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych <= '9') { gotoCase = 129; continue; }; } else { if (yych <= 'F') { gotoCase = 129; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych <= 'f') { gotoCase = 129; continue; }; } case 128: cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 118; continue; }; } else { { gotoCase = 121; continue; }; } case 129: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych >= ':') { gotoCase = 128; continue; }; } else { if (yych <= 'F') { gotoCase = 130; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych >= 'g') { gotoCase = 128; continue; }; } case 130: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych >= ':') { gotoCase = 128; continue; }; } else { if (yych <= 'F') { gotoCase = 131; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych >= 'g') { gotoCase = 128; continue; }; } case 131: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych <= '9') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } else { if (yych <= 'F') { gotoCase = 125; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych <= 'f') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } case 132: ++cursor; yych = this._charAt(cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 125; continue; }; if (yych <= '&') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } else { if (yych == 'b') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych <= 'f') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } else { if (yych <= 'n') { gotoCase = 125; continue; }; if (yych <= 'q') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } else { if (yych <= 'u') { gotoCase = 127; continue; }; if (yych <= 'v') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } } } case 133: ++cursor; yych = this._charAt(cursor); { gotoCase = 123; continue; }; case this.case_NODIV: yych = this._charAt(cursor); if (yych <= '9') { if (yych <= '(') { if (yych <= '#') { if (yych <= ' ') { gotoCase = 136; continue; }; if (yych <= '!') { gotoCase = 138; continue; }; if (yych <= '"') { gotoCase = 140; continue; }; } else { if (yych <= '%') { if (yych <= '$') { gotoCase = 141; continue; }; { gotoCase = 143; continue; }; } else { if (yych <= '&') { gotoCase = 144; continue; }; if (yych <= '\'') { gotoCase = 145; continue; }; { gotoCase = 146; continue; }; } } } else { if (yych <= ',') { if (yych <= ')') { gotoCase = 147; continue; }; if (yych <= '*') { gotoCase = 149; continue; }; if (yych <= '+') { gotoCase = 150; continue; }; { gotoCase = 146; continue; }; } else { if (yych <= '.') { if (yych <= '-') { gotoCase = 151; continue; }; { gotoCase = 152; continue; }; } else { if (yych <= '/') { gotoCase = 153; continue; }; if (yych <= '0') { gotoCase = 154; continue; }; { gotoCase = 156; continue; }; } } } } else { if (yych <= '\\') { if (yych <= '>') { if (yych <= ';') { gotoCase = 146; continue; }; if (yych <= '<') { gotoCase = 157; continue; }; if (yych <= '=') { gotoCase = 158; continue; }; { gotoCase = 159; continue; }; } else { if (yych <= '@') { if (yych <= '?') { gotoCase = 146; continue; }; } else { if (yych <= 'Z') { gotoCase = 141; continue; }; if (yych <= '[') { gotoCase = 146; continue; }; { gotoCase = 160; continue; }; } } } else { if (yych <= 'z') { if (yych <= '^') { if (yych <= ']') { gotoCase = 146; continue; }; { gotoCase = 161; continue; }; } else { if (yych != '`') { gotoCase = 141; continue; }; } } else { if (yych <= '|') { if (yych <= '{') { gotoCase = 146; continue; }; { gotoCase = 162; continue; }; } else { if (yych <= '~') { gotoCase = 146; continue; }; if (yych >= 0x80) { gotoCase = 141; continue; }; } } } } case 136: ++cursor; case 137: { this.tokenType = null; return cursor; } case 138: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 260; continue; }; case 139: { var token = this._line.charAt(cursorOnEnter); if (token === "{") this.tokenType = "block-start"; else if (token === "}") this.tokenType = "block-end"; else this.tokenType = null; return cursor; } case 140: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 137; continue; }; if (yych == '\r') { gotoCase = 137; continue; }; { gotoCase = 252; continue; }; case 141: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 170; continue; }; case 142: this.setLexCondition(this._lexConditions.DIV); { var token = this._line.substring(cursorOnEnter, cursor); if (WebInspector.SourceJavaScriptTokenizer.Keywords[token] === true && token !== "__proto__") this.tokenType = "javascript-keyword"; else this.tokenType = "javascript-ident"; return cursor; } case 143: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 144: yych = this._charAt(++cursor); if (yych == '&') { gotoCase = 163; continue; }; if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 145: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 137; continue; }; if (yych == '\r') { gotoCase = 137; continue; }; { gotoCase = 241; continue; }; case 146: yych = this._charAt(++cursor); { gotoCase = 139; continue; }; case 147: ++cursor; this.setLexCondition(this._lexConditions.DIV); { this.tokenType = null; return cursor; } case 149: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 150: yych = this._charAt(++cursor); if (yych == '+') { gotoCase = 163; continue; }; if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 151: yych = this._charAt(++cursor); if (yych == '-') { gotoCase = 163; continue; }; if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 152: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 139; continue; }; if (yych <= '9') { gotoCase = 234; continue; }; { gotoCase = 139; continue; }; case 153: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 137; continue; }; { gotoCase = 197; continue; }; } else { if (yych <= '\r') { gotoCase = 137; continue; }; if (yych <= ')') { gotoCase = 197; continue; }; { gotoCase = 202; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 204; continue; }; { gotoCase = 197; continue; }; } else { if (yych <= '[') { gotoCase = 200; continue; }; if (yych <= '\\') { gotoCase = 199; continue; }; if (yych <= ']') { gotoCase = 137; continue; }; { gotoCase = 197; continue; }; } } case 154: yyaccept = 2; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'E') { if (yych <= '/') { if (yych == '.') { gotoCase = 183; continue; }; } else { if (yych <= '7') { gotoCase = 192; continue; }; if (yych >= 'E') { gotoCase = 182; continue; }; } } else { if (yych <= 'd') { if (yych == 'X') { gotoCase = 194; continue; }; } else { if (yych <= 'e') { gotoCase = 182; continue; }; if (yych == 'x') { gotoCase = 194; continue; }; } } case 155: this.setLexCondition(this._lexConditions.DIV); { this.tokenType = "javascript-number"; return cursor; } case 156: yyaccept = 2; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 183; continue; }; if (yych <= '/') { gotoCase = 155; continue; }; { gotoCase = 180; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 155; continue; }; { gotoCase = 182; continue; }; } else { if (yych == 'e') { gotoCase = 182; continue; }; { gotoCase = 155; continue; }; } } case 157: yych = this._charAt(++cursor); if (yych <= ';') { gotoCase = 139; continue; }; if (yych <= '<') { gotoCase = 179; continue; }; if (yych <= '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 158: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 178; continue; }; { gotoCase = 139; continue; }; case 159: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 139; continue; }; if (yych <= '=') { gotoCase = 163; continue; }; if (yych <= '>') { gotoCase = 176; continue; }; { gotoCase = 139; continue; }; case 160: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == 'u') { gotoCase = 164; continue; }; { gotoCase = 137; continue; }; case 161: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 162: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; if (yych != '|') { gotoCase = 139; continue; }; case 163: yych = this._charAt(++cursor); { gotoCase = 139; continue; }; case 164: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 166; continue; }; } else { if (yych <= 'F') { gotoCase = 166; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 166; continue; }; } case 165: cursor = YYMARKER; if (yyaccept <= 1) { if (yyaccept <= 0) { { gotoCase = 137; continue; }; } else { { gotoCase = 142; continue; }; } } else { if (yyaccept <= 2) { { gotoCase = 155; continue; }; } else { { gotoCase = 217; continue; }; } } case 166: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 167; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 167: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 168; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 168: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 169; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 169: yyaccept = 1; YYMARKER = ++cursor; yych = this._charAt(cursor); case 170: if (yych <= '[') { if (yych <= '/') { if (yych == '$') { gotoCase = 169; continue; }; { gotoCase = 142; continue; }; } else { if (yych <= '9') { gotoCase = 169; continue; }; if (yych <= '@') { gotoCase = 142; continue; }; if (yych <= 'Z') { gotoCase = 169; continue; }; { gotoCase = 142; continue; }; } } else { if (yych <= '_') { if (yych <= '\\') { gotoCase = 171; continue; }; if (yych <= '^') { gotoCase = 142; continue; }; { gotoCase = 169; continue; }; } else { if (yych <= '`') { gotoCase = 142; continue; }; if (yych <= 'z') { gotoCase = 169; continue; }; if (yych <= String.fromCharCode(0x7F)) { gotoCase = 142; continue; }; { gotoCase = 169; continue; }; } } case 171: ++cursor; yych = this._charAt(cursor); if (yych != 'u') { gotoCase = 165; continue; }; ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 173; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 173: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 174; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 174: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 175; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 175: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 169; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 169; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 169; continue; }; { gotoCase = 165; continue; }; } case 176: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 139; continue; }; if (yych <= '=') { gotoCase = 163; continue; }; if (yych >= '?') { gotoCase = 139; continue; }; yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 178: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 179: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 180: yyaccept = 2; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 183; continue; }; if (yych <= '/') { gotoCase = 155; continue; }; { gotoCase = 180; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 155; continue; }; } else { if (yych != 'e') { gotoCase = 155; continue; }; } } case 182: yych = this._charAt(++cursor); if (yych <= ',') { if (yych == '+') { gotoCase = 189; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= '-') { gotoCase = 189; continue; }; if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 190; continue; }; { gotoCase = 165; continue; }; } case 183: yyaccept = 2; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 183; continue; }; { gotoCase = 155; continue; }; } else { if (yych <= 'E') { gotoCase = 185; continue; }; if (yych != 'e') { gotoCase = 155; continue; }; } case 185: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 165; continue; }; } else { if (yych <= '-') { gotoCase = 186; continue; }; if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 187; continue; }; { gotoCase = 165; continue; }; } case 186: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; case 187: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 187; continue; }; { gotoCase = 155; continue; }; case 189: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; case 190: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 190; continue; }; { gotoCase = 155; continue; }; case 192: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '7') { gotoCase = 192; continue; }; { gotoCase = 155; continue; }; case 194: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 195; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 195: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 195; continue; }; { gotoCase = 155; continue; }; } else { if (yych <= 'F') { gotoCase = 195; continue; }; if (yych <= '`') { gotoCase = 155; continue; }; if (yych <= 'f') { gotoCase = 195; continue; }; { gotoCase = 155; continue; }; } case 197: ++cursor; yych = this._charAt(cursor); if (yych <= '.') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 197; continue; }; { gotoCase = 165; continue; }; } else { if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= '[') { if (yych <= '/') { gotoCase = 220; continue; }; if (yych <= 'Z') { gotoCase = 197; continue; }; { gotoCase = 228; continue; }; } else { if (yych <= '\\') { gotoCase = 227; continue; }; if (yych <= ']') { gotoCase = 165; continue; }; { gotoCase = 197; continue; }; } } case 199: yych = this._charAt(++cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 197; continue; }; case 200: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 200; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 200; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 165; continue; }; { gotoCase = 200; continue; }; } else { if (yych <= '\\') { gotoCase = 215; continue; }; if (yych <= ']') { gotoCase = 213; continue; }; { gotoCase = 200; continue; }; } } case 202: ++cursor; yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 209; continue; }; { gotoCase = 202; continue; }; } else { if (yych <= '\r') { gotoCase = 209; continue; }; if (yych == '*') { gotoCase = 207; continue; }; { gotoCase = 202; continue; }; } case 204: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 206; continue; }; if (yych != '\r') { gotoCase = 204; continue; }; case 206: { this.tokenType = "javascript-comment"; return cursor; } case 207: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 207; continue; }; if (yych == '/') { gotoCase = 211; continue; }; { gotoCase = 202; continue; }; case 209: ++cursor; this.setLexCondition(this._lexConditions.COMMENT); { this.tokenType = "javascript-comment"; return cursor; } case 211: ++cursor; { this.tokenType = "javascript-comment"; return cursor; } case 213: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 213; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 213; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 220; continue; }; { gotoCase = 213; continue; }; } else { if (yych <= '[') { gotoCase = 218; continue; }; if (yych <= '\\') { gotoCase = 216; continue; }; { gotoCase = 213; continue; }; } } case 215: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 200; continue; }; case 216: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych != '\r') { gotoCase = 213; continue; }; case 217: this.setLexCondition(this._lexConditions.REGEX); { this.tokenType = "javascript-regexp"; return cursor; } case 218: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 218; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 218; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 165; continue; }; { gotoCase = 218; continue; }; } else { if (yych <= '\\') { gotoCase = 225; continue; }; if (yych <= ']') { gotoCase = 223; continue; }; { gotoCase = 218; continue; }; } } case 220: ++cursor; yych = this._charAt(cursor); if (yych <= 'h') { if (yych == 'g') { gotoCase = 220; continue; }; } else { if (yych <= 'i') { gotoCase = 220; continue; }; if (yych == 'm') { gotoCase = 220; continue; }; } { this.tokenType = "javascript-regexp"; return cursor; } case 223: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 223; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 223; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 220; continue; }; { gotoCase = 223; continue; }; } else { if (yych <= '[') { gotoCase = 218; continue; }; if (yych <= '\\') { gotoCase = 226; continue; }; { gotoCase = 223; continue; }; } } case 225: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 218; continue; }; case 226: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych == '\r') { gotoCase = 217; continue; }; { gotoCase = 223; continue; }; case 227: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych == '\r') { gotoCase = 217; continue; }; { gotoCase = 197; continue; }; case 228: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 228; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 228; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 165; continue; }; { gotoCase = 228; continue; }; } else { if (yych <= '\\') { gotoCase = 232; continue; }; if (yych >= '^') { gotoCase = 228; continue; }; } } case 230: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 230; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 230; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 220; continue; }; { gotoCase = 230; continue; }; } else { if (yych <= '[') { gotoCase = 228; continue; }; if (yych <= '\\') { gotoCase = 233; continue; }; { gotoCase = 230; continue; }; } } case 232: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 228; continue; }; case 233: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych == '\r') { gotoCase = 217; continue; }; { gotoCase = 230; continue; }; case 234: yyaccept = 2; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 234; continue; }; { gotoCase = 155; continue; }; } else { if (yych <= 'E') { gotoCase = 236; continue; }; if (yych != 'e') { gotoCase = 155; continue; }; } case 236: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 165; continue; }; } else { if (yych <= '-') { gotoCase = 237; continue; }; if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 238; continue; }; { gotoCase = 165; continue; }; } case 237: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; case 238: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 238; continue; }; { gotoCase = 155; continue; }; case 240: ++cursor; yych = this._charAt(cursor); case 241: if (yych <= '\r') { if (yych == '\n') { gotoCase = 165; continue; }; if (yych <= '\f') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 240; continue; }; { gotoCase = 243; continue; }; } else { if (yych != '\\') { gotoCase = 240; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 165; continue; }; { gotoCase = 246; continue; }; } else { if (yych == '\r') { gotoCase = 246; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 240; continue; }; if (yych <= '&') { gotoCase = 165; continue; }; { gotoCase = 240; continue; }; } else { if (yych == '\\') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 240; continue; }; if (yych <= 'e') { gotoCase = 165; continue; }; { gotoCase = 240; continue; }; } else { if (yych == 'n') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 165; continue; }; { gotoCase = 240; continue; }; } else { if (yych <= 'u') { gotoCase = 245; continue; }; if (yych <= 'v') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } } } case 243: ++cursor; { this.tokenType = "javascript-string"; return cursor; } case 245: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 248; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 248; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 248; continue; }; { gotoCase = 165; continue; }; } case 246: ++cursor; this.setLexCondition(this._lexConditions.SSTRING); { this.tokenType = "javascript-string"; return cursor; } case 248: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 249; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 249: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 250; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 250: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 240; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } case 251: ++cursor; yych = this._charAt(cursor); case 252: if (yych <= '\r') { if (yych == '\n') { gotoCase = 165; continue; }; if (yych <= '\f') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 251; continue; }; { gotoCase = 243; continue; }; } else { if (yych != '\\') { gotoCase = 251; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 165; continue; }; { gotoCase = 255; continue; }; } else { if (yych == '\r') { gotoCase = 255; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 251; continue; }; if (yych <= '&') { gotoCase = 165; continue; }; { gotoCase = 251; continue; }; } else { if (yych == '\\') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 251; continue; }; if (yych <= 'e') { gotoCase = 165; continue; }; { gotoCase = 251; continue; }; } else { if (yych == 'n') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 165; continue; }; { gotoCase = 251; continue; }; } else { if (yych <= 'u') { gotoCase = 254; continue; }; if (yych <= 'v') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } } } case 254: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 257; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 257; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 257; continue; }; { gotoCase = 165; continue; }; } case 255: ++cursor; this.setLexCondition(this._lexConditions.DSTRING); { this.tokenType = "javascript-string"; return cursor; } case 257: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 258; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 258: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 259; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 259: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 251; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } case 260: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case this.case_REGEX: yych = this._charAt(cursor); if (yych <= '.') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 264; continue; }; { gotoCase = 265; continue; }; } else { if (yych == '\r') { gotoCase = 265; continue; }; { gotoCase = 264; continue; }; } } else { if (yych <= '[') { if (yych <= '/') { gotoCase = 267; continue; }; if (yych <= 'Z') { gotoCase = 264; continue; }; { gotoCase = 269; continue; }; } else { if (yych <= '\\') { gotoCase = 270; continue; }; if (yych <= ']') { gotoCase = 265; continue; }; { gotoCase = 264; continue; }; } } case 263: { this.tokenType = "javascript-regexp"; return cursor; } case 264: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 272; continue; }; case 265: ++cursor; case 266: { this.tokenType = null; return cursor; } case 267: ++cursor; yych = this._charAt(cursor); { gotoCase = 278; continue; }; case 268: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-regexp"; return cursor; } case 269: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 266; continue; }; if (yych <= '\f') { gotoCase = 276; continue; }; { gotoCase = 266; continue; }; } else { if (yych <= '*') { if (yych <= ')') { gotoCase = 276; continue; }; { gotoCase = 266; continue; }; } else { if (yych == '/') { gotoCase = 266; continue; }; { gotoCase = 276; continue; }; } } case 270: yych = this._charAt(++cursor); if (yych == '\n') { gotoCase = 266; continue; }; if (yych == '\r') { gotoCase = 266; continue; }; case 271: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 272: if (yych <= '.') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 271; continue; }; { gotoCase = 263; continue; }; } else { if (yych == '\r') { gotoCase = 263; continue; }; { gotoCase = 271; continue; }; } } else { if (yych <= '[') { if (yych <= '/') { gotoCase = 277; continue; }; if (yych <= 'Z') { gotoCase = 271; continue; }; { gotoCase = 275; continue; }; } else { if (yych <= '\\') { gotoCase = 273; continue; }; if (yych <= ']') { gotoCase = 263; continue; }; { gotoCase = 271; continue; }; } } case 273: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 274; continue; }; if (yych != '\r') { gotoCase = 271; continue; }; case 274: cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 263; continue; }; } else { { gotoCase = 266; continue; }; } case 275: ++cursor; yych = this._charAt(cursor); case 276: if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 274; continue; }; { gotoCase = 275; continue; }; } else { if (yych <= '\r') { gotoCase = 274; continue; }; if (yych <= ')') { gotoCase = 275; continue; }; { gotoCase = 274; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 274; continue; }; { gotoCase = 275; continue; }; } else { if (yych <= '\\') { gotoCase = 281; continue; }; if (yych <= ']') { gotoCase = 279; continue; }; { gotoCase = 275; continue; }; } } case 277: ++cursor; yych = this._charAt(cursor); case 278: if (yych <= 'h') { if (yych == 'g') { gotoCase = 277; continue; }; { gotoCase = 268; continue; }; } else { if (yych <= 'i') { gotoCase = 277; continue; }; if (yych == 'm') { gotoCase = 277; continue; }; { gotoCase = 268; continue; }; } case 279: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 263; continue; }; { gotoCase = 279; continue; }; } else { if (yych <= '\r') { gotoCase = 263; continue; }; if (yych <= ')') { gotoCase = 279; continue; }; { gotoCase = 271; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 277; continue; }; { gotoCase = 279; continue; }; } else { if (yych <= '[') { gotoCase = 275; continue; }; if (yych <= '\\') { gotoCase = 282; continue; }; { gotoCase = 279; continue; }; } } case 281: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 274; continue; }; if (yych == '\r') { gotoCase = 274; continue; }; { gotoCase = 275; continue; }; case 282: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 274; continue; }; if (yych == '\r') { gotoCase = 274; continue; }; { gotoCase = 279; continue; }; case this.case_SSTRING: yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 287; continue; }; if (yych <= '\f') { gotoCase = 286; continue; }; { gotoCase = 287; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 286; continue; }; { gotoCase = 289; continue; }; } else { if (yych == '\\') { gotoCase = 291; continue; }; { gotoCase = 286; continue; }; } } case 285: { this.tokenType = "javascript-string"; return cursor; } case 286: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 293; continue; }; case 287: ++cursor; case 288: { this.tokenType = null; return cursor; } case 289: ++cursor; case 290: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-string"; return cursor; } case 291: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 292; continue; }; if (yych <= '&') { gotoCase = 288; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 288; continue; }; } else { if (yych != 'b') { gotoCase = 288; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych >= 'g') { gotoCase = 288; continue; }; } else { if (yych <= 'n') { gotoCase = 292; continue; }; if (yych <= 'q') { gotoCase = 288; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 288; continue; }; } else { if (yych <= 'u') { gotoCase = 294; continue; }; if (yych >= 'w') { gotoCase = 288; continue; }; } } } case 292: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 293: if (yych <= '\r') { if (yych == '\n') { gotoCase = 285; continue; }; if (yych <= '\f') { gotoCase = 292; continue; }; { gotoCase = 285; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 292; continue; }; { gotoCase = 300; continue; }; } else { if (yych == '\\') { gotoCase = 299; continue; }; { gotoCase = 292; continue; }; } } case 294: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych <= '9') { gotoCase = 296; continue; }; } else { if (yych <= 'F') { gotoCase = 296; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych <= 'f') { gotoCase = 296; continue; }; } case 295: cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 285; continue; }; } else { { gotoCase = 288; continue; }; } case 296: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych >= ':') { gotoCase = 295; continue; }; } else { if (yych <= 'F') { gotoCase = 297; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych >= 'g') { gotoCase = 295; continue; }; } case 297: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych >= ':') { gotoCase = 295; continue; }; } else { if (yych <= 'F') { gotoCase = 298; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych >= 'g') { gotoCase = 295; continue; }; } case 298: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych <= '9') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } else { if (yych <= 'F') { gotoCase = 292; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych <= 'f') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } case 299: ++cursor; yych = this._charAt(cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 292; continue; }; if (yych <= '&') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } else { if (yych == 'b') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych <= 'f') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } else { if (yych <= 'n') { gotoCase = 292; continue; }; if (yych <= 'q') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } else { if (yych <= 'u') { gotoCase = 294; continue; }; if (yych <= 'v') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } } } case 300: ++cursor; yych = this._charAt(cursor); { gotoCase = 290; continue; }; } } }, __proto__: WebInspector.SourceTokenizer.prototype } ; HTMLScriptFormatter = function(indentString) { WebInspector.SourceHTMLTokenizer.call(this); this._indentString = indentString; } HTMLScriptFormatter.prototype = { format: function(content) { this.line = content; this._content = content; this._formattedContent = ""; this._mapping = { original: [0], formatted: [0] }; this._position = 0; var cursor = 0; while (cursor < this._content.length) cursor = this.nextToken(cursor); this._formattedContent += this._content.substring(this._position); return { content: this._formattedContent, mapping: this._mapping }; }, scriptStarted: function(cursor) { this._formattedContent += this._content.substring(this._position, cursor); this._formattedContent += "\n"; this._position = cursor; }, scriptEnded: function(cursor) { if (cursor === this._position) return; var scriptContent = this._content.substring(this._position, cursor); this._mapping.original.push(this._position); this._mapping.formatted.push(this._formattedContent.length); var formattedScriptContent = formatScript(scriptContent, this._mapping, this._position, this._formattedContent.length, this._indentString); this._formattedContent += formattedScriptContent; this._position = cursor; }, styleSheetStarted: function(cursor) { }, styleSheetEnded: function(cursor) { }, __proto__: WebInspector.SourceHTMLTokenizer.prototype } function require() { return parse; } var exports = {}; var KEYWORDS = array_to_hash([ "break", "case", "catch", "const", "continue", "default", "delete", "do", "else", "finally", "for", "function", "if", "in", "instanceof", "new", "return", "switch", "throw", "try", "typeof", "var", "void", "while", "with" ]); var RESERVED_WORDS = array_to_hash([ "abstract", "boolean", "byte", "char", "class", "debugger", "double", "enum", "export", "extends", "final", "float", "goto", "implements", "import", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "super", "synchronized", "throws", "transient", "volatile" ]); var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([ "return", "new", "delete", "throw", "else", "case" ]); var KEYWORDS_ATOM = array_to_hash([ "false", "null", "true", "undefined" ]); var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^")); var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; var RE_OCT_NUMBER = /^0[0-7]+$/; var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; var OPERATORS = array_to_hash([ "in", "instanceof", "typeof", "new", "void", "delete", "++", "--", "+", "-", "!", "~", "&", "|", "^", "*", "/", "%", ">>", "<<", ">>>", "<", ">", "<=", ">=", "==", "===", "!=", "!==", "?", "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "%=", "|=", "^=", "&=", "&&", "||" ]); var WHITESPACE_CHARS = array_to_hash(characters(" \n\r\t")); var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{}(,.;:")); var PUNC_CHARS = array_to_hash(characters("[]{}(),;:")); var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy")); function is_alphanumeric_char(ch) { ch = ch.charCodeAt(0); return (ch >= 48 && ch <= 57) || (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122); }; function is_identifier_char(ch) { return is_alphanumeric_char(ch) || ch == "$" || ch == "_"; }; function is_digit(ch) { ch = ch.charCodeAt(0); return ch >= 48 && ch <= 57; }; function parse_js_number(num) { if (RE_HEX_NUMBER.test(num)) { return parseInt(num.substr(2), 16); } else if (RE_OCT_NUMBER.test(num)) { return parseInt(num.substr(1), 8); } else if (RE_DEC_NUMBER.test(num)) { return parseFloat(num); } }; function JS_Parse_Error(message, line, col, pos) { this.message = message; this.line = line; this.col = col; this.pos = pos; try { ({})(); } catch(ex) { this.stack = ex.stack; }; }; JS_Parse_Error.prototype.toString = function() { return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack; }; function js_error(message, line, col, pos) { throw new JS_Parse_Error(message, line, col, pos); }; function is_token(token, type, val) { return token.type == type && (val == null || token.value == val); }; var EX_EOF = {}; function tokenizer($TEXT) { var S = { text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''), pos : 0, tokpos : 0, line : 0, tokline : 0, col : 0, tokcol : 0, newline_before : false, regex_allowed : false, comments_before : [] }; function peek() { return S.text.charAt(S.pos); }; function next(signal_eof) { var ch = S.text.charAt(S.pos++); if (signal_eof && !ch) throw EX_EOF; if (ch == "\n") { S.newline_before = true; ++S.line; S.col = 0; } else { ++S.col; } return ch; }; function eof() { return !S.peek(); }; function find(what, signal_eof) { var pos = S.text.indexOf(what, S.pos); if (signal_eof && pos == -1) throw EX_EOF; return pos; }; function start_token() { S.tokline = S.line; S.tokcol = S.col; S.tokpos = S.pos; }; function token(type, value, is_comment) { S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) || (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) || (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value))); var ret = { type : type, value : value, line : S.tokline, col : S.tokcol, pos : S.tokpos, nlb : S.newline_before }; if (!is_comment) { ret.comments_before = S.comments_before; S.comments_before = []; } S.newline_before = false; return ret; }; function skip_whitespace() { while (HOP(WHITESPACE_CHARS, peek())) next(); }; function read_while(pred) { var ret = "", ch = peek(), i = 0; while (ch && pred(ch, i++)) { ret += next(); ch = peek(); } return ret; }; function parse_error(err) { js_error(err, S.tokline, S.tokcol, S.tokpos); }; function read_num(prefix) { var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; var num = read_while(function(ch, i){ if (ch == "x" || ch == "X") { if (has_x) return false; return has_x = true; } if (!has_x && (ch == "E" || ch == "e")) { if (has_e) return false; return has_e = after_e = true; } if (ch == "-") { if (after_e || (i == 0 && !prefix)) return true; return false; } if (ch == "+") return after_e; after_e = false; if (ch == ".") { if (!has_dot) return has_dot = true; return false; } return is_alphanumeric_char(ch); }); if (prefix) num = prefix + num; var valid = parse_js_number(num); if (!isNaN(valid)) { return token("num", valid); } else { parse_error("Invalid syntax: " + num); } }; function read_escaped_char() { var ch = next(true); switch (ch) { case "n" : return "\n"; case "r" : return "\r"; case "t" : return "\t"; case "b" : return "\b"; case "v" : return "\v"; case "f" : return "\f"; case "0" : return "\0"; case "x" : return String.fromCharCode(hex_bytes(2)); case "u" : return String.fromCharCode(hex_bytes(4)); default : return ch; } }; function hex_bytes(n) { var num = 0; for (; n > 0; --n) { var digit = parseInt(next(true), 16); if (isNaN(digit)) parse_error("Invalid hex-character pattern in string"); num = (num << 4) | digit; } return num; }; function read_string() { return with_eof_error("Unterminated string constant", function(){ var quote = next(), ret = ""; for (;;) { var ch = next(true); if (ch == "\\") ch = read_escaped_char(); else if (ch == quote) break; ret += ch; } return token("string", ret); }); }; function read_line_comment() { next(); var i = find("\n"), ret; if (i == -1) { ret = S.text.substr(S.pos); S.pos = S.text.length; } else { ret = S.text.substring(S.pos, i); S.pos = i; } return token("comment1", ret, true); }; function read_multiline_comment() { next(); return with_eof_error("Unterminated multiline comment", function(){ var i = find("*/", true), text = S.text.substring(S.pos, i), tok = token("comment2", text, true); S.pos = i + 2; S.line += text.split("\n").length - 1; S.newline_before = text.indexOf("\n") >= 0; return tok; }); }; function read_regexp() { return with_eof_error("Unterminated regular expression", function(){ var prev_backslash = false, regexp = "", ch, in_class = false; while ((ch = next(true))) if (prev_backslash) { regexp += "\\" + ch; prev_backslash = false; } else if (ch == "[") { in_class = true; regexp += ch; } else if (ch == "]" && in_class) { in_class = false; regexp += ch; } else if (ch == "/" && !in_class) { break; } else if (ch == "\\") { prev_backslash = true; } else { regexp += ch; } var mods = read_while(function(ch){ return HOP(REGEXP_MODIFIERS, ch); }); return token("regexp", [ regexp, mods ]); }); }; function read_operator(prefix) { function grow(op) { if (!peek()) return op; var bigger = op + peek(); if (HOP(OPERATORS, bigger)) { next(); return grow(bigger); } else { return op; } }; return token("operator", grow(prefix || next())); }; function handle_slash() { next(); var regex_allowed = S.regex_allowed; switch (peek()) { case "/": S.comments_before.push(read_line_comment()); S.regex_allowed = regex_allowed; return next_token(); case "*": S.comments_before.push(read_multiline_comment()); S.regex_allowed = regex_allowed; return next_token(); } return S.regex_allowed ? read_regexp() : read_operator("/"); }; function handle_dot() { next(); return is_digit(peek()) ? read_num(".") : token("punc", "."); }; function read_word() { var word = read_while(is_identifier_char); return !HOP(KEYWORDS, word) ? token("name", word) : HOP(OPERATORS, word) ? token("operator", word) : HOP(KEYWORDS_ATOM, word) ? token("atom", word) : token("keyword", word); }; function with_eof_error(eof_error, cont) { try { return cont(); } catch(ex) { if (ex === EX_EOF) parse_error(eof_error); else throw ex; } }; function next_token(force_regexp) { if (force_regexp) return read_regexp(); skip_whitespace(); start_token(); var ch = peek(); if (!ch) return token("eof"); if (is_digit(ch)) return read_num(); if (ch == '"' || ch == "'") return read_string(); if (HOP(PUNC_CHARS, ch)) return token("punc", next()); if (ch == ".") return handle_dot(); if (ch == "/") return handle_slash(); if (HOP(OPERATOR_CHARS, ch)) return read_operator(); if (is_identifier_char(ch)) return read_word(); parse_error("Unexpected character '" + ch + "'"); }; next_token.context = function(nc) { if (nc) S = nc; return S; }; return next_token; }; var UNARY_PREFIX = array_to_hash([ "typeof", "void", "delete", "--", "++", "!", "~", "-", "+" ]); var UNARY_POSTFIX = array_to_hash([ "--", "++" ]); var ASSIGNMENT = (function(a, ret, i){ while (i < a.length) { ret[a[i]] = a[i].substr(0, a[i].length - 1); i++; } return ret; })( ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="], { "=": true }, 0 ); var PRECEDENCE = (function(a, ret){ for (var i = 0, n = 1; i < a.length; ++i, ++n) { var b = a[i]; for (var j = 0; j < b.length; ++j) { ret[b[j]] = n; } } return ret; })( [ ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ], {} ); var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); function NodeWithToken(str, start, end) { this.name = str; this.start = start; this.end = end; }; NodeWithToken.prototype.toString = function() { return this.name; }; function parse($TEXT, strict_mode, embed_tokens) { var S = { input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT, token : null, prev : null, peeked : null, in_function : 0, in_loop : 0, labels : [] }; S.token = next(); function is(type, value) { return is_token(S.token, type, value); }; function peek() { return S.peeked || (S.peeked = S.input()); }; function next() { S.prev = S.token; if (S.peeked) { S.token = S.peeked; S.peeked = null; } else { S.token = S.input(); } return S.token; }; function prev() { return S.prev; }; function croak(msg, line, col, pos) { var ctx = S.input.context(); js_error(msg, line != null ? line : ctx.tokline, col != null ? col : ctx.tokcol, pos != null ? pos : ctx.tokpos); }; function token_error(token, msg) { croak(msg, token.line, token.col); }; function unexpected(token) { if (token == null) token = S.token; token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); }; function expect_token(type, val) { if (is(type, val)) { return next(); } token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type); }; function expect(punc) { return expect_token("punc", punc); }; function can_insert_semicolon() { return !strict_mode && ( S.token.nlb || is("eof") || is("punc", "}") ); }; function semicolon() { if (is("punc", ";")) next(); else if (!can_insert_semicolon()) unexpected(); }; function as() { return slice(arguments); }; function parenthesised() { expect("("); var ex = expression(); expect(")"); return ex; }; function add_tokens(str, start, end) { return new NodeWithToken(str, start, end); }; var statement = embed_tokens ? function() { var start = S.token; var stmt = $statement(); stmt[0] = add_tokens(stmt[0], start, prev()); return stmt; } : $statement; function $statement() { if (is("operator", "/")) { S.peeked = null; S.token = S.input(true); } switch (S.token.type) { case "num": case "string": case "regexp": case "operator": case "atom": return simple_statement(); case "name": return is_token(peek(), "punc", ":") ? labeled_statement(prog1(S.token.value, next, next)) : simple_statement(); case "punc": switch (S.token.value) { case "{": return as("block", block_()); case "[": case "(": return simple_statement(); case ";": next(); return as("block"); default: unexpected(); } case "keyword": switch (prog1(S.token.value, next)) { case "break": return break_cont("break"); case "continue": return break_cont("continue"); case "debugger": semicolon(); return as("debugger"); case "do": return (function(body){ expect_token("keyword", "while"); return as("do", prog1(parenthesised, semicolon), body); })(in_loop(statement)); case "for": return for_(); case "function": return function_(true); case "if": return if_(); case "return": if (S.in_function == 0) croak("'return' outside of function"); return as("return", is("punc", ";") ? (next(), null) : can_insert_semicolon() ? null : prog1(expression, semicolon)); case "switch": return as("switch", parenthesised(), switch_block_()); case "throw": return as("throw", prog1(expression, semicolon)); case "try": return try_(); case "var": return prog1(var_, semicolon); case "const": return prog1(const_, semicolon); case "while": return as("while", parenthesised(), in_loop(statement)); case "with": return as("with", parenthesised(), statement()); default: unexpected(); } } }; function labeled_statement(label) { S.labels.push(label); var start = S.token, stat = statement(); if (strict_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0])) unexpected(start); S.labels.pop(); return as("label", label, stat); }; function simple_statement() { return as("stat", prog1(expression, semicolon)); }; function break_cont(type) { var name = is("name") ? S.token.value : null; if (name != null) { next(); if (!member(name, S.labels)) croak("Label " + name + " without matching loop or statement"); } else if (S.in_loop == 0) croak(type + " not inside a loop or switch"); semicolon(); return as(type, name); }; function for_() { expect("("); var has_var = is("keyword", "var"); if (has_var) next(); if (is("name") && is_token(peek(), "operator", "in")) { var name = S.token.value; next(); next(); var obj = expression(); expect(")"); return as("for-in", has_var, name, obj, in_loop(statement)); } else { var init = is("punc", ";") ? null : has_var ? var_() : expression(); expect(";"); var test = is("punc", ";") ? null : expression(); expect(";"); var step = is("punc", ")") ? null : expression(); expect(")"); return as("for", init, test, step, in_loop(statement)); } }; function function_(in_statement) { var name = is("name") ? prog1(S.token.value, next) : null; if (in_statement && !name) unexpected(); expect("("); return as(in_statement ? "defun" : "function", name, (function(first, a){ while (!is("punc", ")")) { if (first) first = false; else expect(","); if (!is("name")) unexpected(); a.push(S.token.value); next(); } next(); return a; })(true, []), (function(){ ++S.in_function; var loop = S.in_loop; S.in_loop = 0; var a = block_(); --S.in_function; S.in_loop = loop; return a; })()); }; function if_() { var cond = parenthesised(), body = statement(), belse; if (is("keyword", "else")) { next(); belse = statement(); } return as("if", cond, body, belse); }; function block_() { expect("{"); var a = []; while (!is("punc", "}")) { if (is("eof")) unexpected(); a.push(statement()); } next(); return a; }; var switch_block_ = curry(in_loop, function(){ expect("{"); var a = [], cur = null; while (!is("punc", "}")) { if (is("eof")) unexpected(); if (is("keyword", "case")) { next(); cur = []; a.push([ expression(), cur ]); expect(":"); } else if (is("keyword", "default")) { next(); expect(":"); cur = []; a.push([ null, cur ]); } else { if (!cur) unexpected(); cur.push(statement()); } } next(); return a; }); function try_() { var body = block_(), bcatch, bfinally; if (is("keyword", "catch")) { next(); expect("("); if (!is("name")) croak("Name expected"); var name = S.token.value; next(); expect(")"); bcatch = [ name, block_() ]; } if (is("keyword", "finally")) { next(); bfinally = block_(); } if (!bcatch && !bfinally) croak("Missing catch/finally blocks"); return as("try", body, bcatch, bfinally); }; function vardefs() { var a = []; for (;;) { if (!is("name")) unexpected(); var name = S.token.value; next(); if (is("operator", "=")) { next(); a.push([ name, expression(false) ]); } else { a.push([ name ]); } if (!is("punc", ",")) break; next(); } return a; }; function var_() { return as("var", vardefs()); }; function const_() { return as("const", vardefs()); }; function new_() { var newexp = expr_atom(false), args; if (is("punc", "(")) { next(); args = expr_list(")"); } else { args = []; } return subscripts(as("new", newexp, args), true); }; function expr_atom(allow_calls) { if (is("operator", "new")) { next(); return new_(); } if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) { return make_unary("unary-prefix", prog1(S.token.value, next), expr_atom(allow_calls)); } if (is("punc")) { switch (S.token.value) { case "(": next(); return subscripts(prog1(expression, curry(expect, ")")), allow_calls); case "[": next(); return subscripts(array_(), allow_calls); case "{": next(); return subscripts(object_(), allow_calls); } unexpected(); } if (is("keyword", "function")) { next(); return subscripts(function_(false), allow_calls); } if (HOP(ATOMIC_START_TOKEN, S.token.type)) { var atom = S.token.type == "regexp" ? as("regexp", S.token.value[0], S.token.value[1]) : as(S.token.type, S.token.value); return subscripts(prog1(atom, next), allow_calls); } unexpected(); }; function expr_list(closing, allow_trailing_comma, allow_empty) { var first = true, a = []; while (!is("punc", closing)) { if (first) first = false; else expect(","); if (allow_trailing_comma && is("punc", closing)) break; if (is("punc", ",") && allow_empty) { a.push([ "atom", "undefined" ]); } else { a.push(expression(false)); } } next(); return a; }; function array_() { return as("array", expr_list("]", !strict_mode, true)); }; function object_() { var first = true, a = []; while (!is("punc", "}")) { if (first) first = false; else expect(","); if (!strict_mode && is("punc", "}")) break; var type = S.token.type; var name = as_property_name(); if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) { a.push([ as_name(), function_(false), name ]); } else { expect(":"); a.push([ name, expression(false) ]); } } next(); return as("object", a); }; function as_property_name() { switch (S.token.type) { case "num": case "string": return prog1(S.token.value, next); } return as_name(); }; function as_name() { switch (S.token.type) { case "name": case "operator": case "keyword": case "atom": return prog1(S.token.value, next); default: unexpected(); } }; function subscripts(expr, allow_calls) { if (is("punc", ".")) { next(); return subscripts(as("dot", expr, as_name()), allow_calls); } if (is("punc", "[")) { next(); return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls); } if (allow_calls && is("punc", "(")) { next(); return subscripts(as("call", expr, expr_list(")")), true); } if (allow_calls && is("operator") && HOP(UNARY_POSTFIX, S.token.value)) { return prog1(curry(make_unary, "unary-postfix", S.token.value, expr), next); } return expr; }; function make_unary(tag, op, expr) { if ((op == "++" || op == "--") && !is_assignable(expr)) croak("Invalid use of " + op + " operator"); return as(tag, op, expr); }; function expr_op(left, min_prec) { var op = is("operator") ? S.token.value : null; var prec = op != null ? PRECEDENCE[op] : null; if (prec != null && prec > min_prec) { next(); var right = expr_op(expr_atom(true), prec); return expr_op(as("binary", op, left, right), min_prec); } return left; }; function expr_ops() { return expr_op(expr_atom(true), 0); }; function maybe_conditional() { var expr = expr_ops(); if (is("operator", "?")) { next(); var yes = expression(false); expect(":"); return as("conditional", expr, yes, expression(false)); } return expr; }; function is_assignable(expr) { switch (expr[0]) { case "dot": case "sub": return true; case "name": return expr[1] != "this"; } }; function maybe_assign() { var left = maybe_conditional(), val = S.token.value; if (is("operator") && HOP(ASSIGNMENT, val)) { if (is_assignable(left)) { next(); return as("assign", ASSIGNMENT[val], left, maybe_assign()); } croak("Invalid assignment"); } return left; }; function expression(commas) { if (arguments.length == 0) commas = true; var expr = maybe_assign(); if (commas && is("punc", ",")) { next(); return as("seq", expr, expression()); } return expr; }; function in_loop(cont) { try { ++S.in_loop; return cont(); } finally { --S.in_loop; } }; return as("toplevel", (function(a){ while (!is("eof")) a.push(statement()); return a; })([])); }; function curry(f) { var args = slice(arguments, 1); return function() { return f.apply(this, args.concat(slice(arguments))); }; }; function prog1(ret) { if (ret instanceof Function) ret = ret(); for (var i = 1, n = arguments.length; --n > 0; ++i) arguments[i](); return ret; }; function array_to_hash(a) { var ret = {}; for (var i = 0; i < a.length; ++i) ret[a[i]] = true; return ret; }; function slice(a, start) { return Array.prototype.slice.call(a, start == null ? 0 : start); }; function characters(str) { return str.split(""); }; function member(name, array) { for (var i = array.length; --i >= 0;) if (array[i] === name) return true; return false; }; function HOP(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; exports.tokenizer = tokenizer; exports.parse = parse; exports.slice = slice; exports.curry = curry; exports.member = member; exports.array_to_hash = array_to_hash; exports.PRECEDENCE = PRECEDENCE; exports.KEYWORDS_ATOM = KEYWORDS_ATOM; exports.RESERVED_WORDS = RESERVED_WORDS; exports.KEYWORDS = KEYWORDS; exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN; exports.OPERATORS = OPERATORS; exports.is_alphanumeric_char = is_alphanumeric_char; exports.is_identifier_char = is_identifier_char; ; var parse = exports; function FormattedContentBuilder(content, mapping, originalOffset, formattedOffset, indentString) { this._originalContent = content; this._originalOffset = originalOffset; this._lastOriginalPosition = 0; this._formattedContent = []; this._formattedContentLength = 0; this._formattedOffset = formattedOffset; this._lastFormattedPosition = 0; this._mapping = mapping; this._lineNumber = 0; this._nestingLevel = 0; this._indentString = indentString; this._cachedIndents = {}; } FormattedContentBuilder.prototype = { addToken: function(token) { for (var i = 0; i < token.comments_before.length; ++i) this._addComment(token.comments_before[i]); while (this._lineNumber < token.line) { this._addText("\n"); this._addIndent(); this._needNewLine = false; this._lineNumber += 1; } if (this._needNewLine) { this._addText("\n"); this._addIndent(); this._needNewLine = false; } this._addMappingIfNeeded(token.pos); this._addText(this._originalContent.substring(token.pos, token.endPos)); this._lineNumber = token.endLine; }, addSpace: function() { this._addText(" "); }, addNewLine: function() { this._needNewLine = true; }, increaseNestingLevel: function() { this._nestingLevel += 1; }, decreaseNestingLevel: function() { this._nestingLevel -= 1; }, content: function() { return this._formattedContent.join(""); }, mapping: function() { return { original: this._originalPositions, formatted: this._formattedPositions }; }, _addIndent: function() { if (this._cachedIndents[this._nestingLevel]) { this._addText(this._cachedIndents[this._nestingLevel]); return; } var fullIndent = ""; for (var i = 0; i < this._nestingLevel; ++i) fullIndent += this._indentString; this._addText(fullIndent); if (this._nestingLevel <= 20) this._cachedIndents[this._nestingLevel] = fullIndent; }, _addComment: function(comment) { if (this._lineNumber < comment.line) { for (var j = this._lineNumber; j < comment.line; ++j) this._addText("\n"); this._lineNumber = comment.line; this._needNewLine = false; this._addIndent(); } else this.addSpace(); this._addMappingIfNeeded(comment.pos); if (comment.type === "comment1") this._addText("//"); else this._addText("/*"); this._addText(comment.value); if (comment.type !== "comment1") { this._addText("*/"); var position; while ((position = comment.value.indexOf("\n", position + 1)) !== -1) this._lineNumber += 1; } }, _addText: function(text) { this._formattedContent.push(text); this._formattedContentLength += text.length; }, _addMappingIfNeeded: function(originalPosition) { if (originalPosition - this._lastOriginalPosition === this._formattedContentLength - this._lastFormattedPosition) return; this._mapping.original.push(this._originalOffset + originalPosition); this._lastOriginalPosition = originalPosition; this._mapping.formatted.push(this._formattedOffset + this._formattedContentLength); this._lastFormattedPosition = this._formattedContentLength; } } var tokens = [ ["EOS"], ["LPAREN", "("], ["RPAREN", ")"], ["LBRACK", "["], ["RBRACK", "]"], ["LBRACE", "{"], ["RBRACE", "}"], ["COLON", ":"], ["SEMICOLON", ";"], ["PERIOD", "."], ["CONDITIONAL", "?"], ["INC", "++"], ["DEC", "--"], ["ASSIGN", "="], ["ASSIGN_BIT_OR", "|="], ["ASSIGN_BIT_XOR", "^="], ["ASSIGN_BIT_AND", "&="], ["ASSIGN_SHL", "<<="], ["ASSIGN_SAR", ">>="], ["ASSIGN_SHR", ">>>="], ["ASSIGN_ADD", "+="], ["ASSIGN_SUB", "-="], ["ASSIGN_MUL", "*="], ["ASSIGN_DIV", "/="], ["ASSIGN_MOD", "%="], ["COMMA", ","], ["OR", "||"], ["AND", "&&"], ["BIT_OR", "|"], ["BIT_XOR", "^"], ["BIT_AND", "&"], ["SHL", "<<"], ["SAR", ">>"], ["SHR", ">>>"], ["ADD", "+"], ["SUB", "-"], ["MUL", "*"], ["DIV", "/"], ["MOD", "%"], ["EQ", "=="], ["NE", "!="], ["EQ_STRICT", "==="], ["NE_STRICT", "!=="], ["LT", "<"], ["GT", ">"], ["LTE", "<="], ["GTE", ">="], ["INSTANCEOF", "instanceof"], ["IN", "in"], ["NOT", "!"], ["BIT_NOT", "~"], ["DELETE", "delete"], ["TYPEOF", "typeof"], ["VOID", "void"], ["BREAK", "break"], ["CASE", "case"], ["CATCH", "catch"], ["CONTINUE", "continue"], ["DEBUGGER", "debugger"], ["DEFAULT", "default"], ["DO", "do"], ["ELSE", "else"], ["FINALLY", "finally"], ["FOR", "for"], ["FUNCTION", "function"], ["IF", "if"], ["NEW", "new"], ["RETURN", "return"], ["SWITCH", "switch"], ["THIS", "this"], ["THROW", "throw"], ["TRY", "try"], ["VAR", "var"], ["WHILE", "while"], ["WITH", "with"], ["NULL_LITERAL", "null"], ["TRUE_LITERAL", "true"], ["FALSE_LITERAL", "false"], ["NUMBER"], ["STRING"], ["IDENTIFIER"], ["CONST", "const"] ]; var Tokens = {}; for (var i = 0; i < tokens.length; ++i) Tokens[tokens[i][0]] = i; var TokensByValue = {}; for (var i = 0; i < tokens.length; ++i) { if (tokens[i][1]) TokensByValue[tokens[i][1]] = i; } var TokensByType = { "eof": Tokens.EOS, "name": Tokens.IDENTIFIER, "num": Tokens.NUMBER, "regexp": Tokens.DIV, "string": Tokens.STRING }; function Tokenizer(content) { this._readNextToken = parse.tokenizer(content); this._state = this._readNextToken.context(); } Tokenizer.prototype = { content: function() { return this._state.text; }, next: function(forceRegexp) { var uglifyToken = this._readNextToken(forceRegexp); uglifyToken.endPos = this._state.pos; uglifyToken.endLine = this._state.line; uglifyToken.token = this._convertUglifyToken(uglifyToken); return uglifyToken; }, _convertUglifyToken: function(uglifyToken) { var token = TokensByType[uglifyToken.type]; if (typeof token === "number") return token; token = TokensByValue[uglifyToken.value]; if (typeof token === "number") return token; throw "Unknown token type " + uglifyToken.type; } } function JavaScriptFormatter(tokenizer, builder) { this._tokenizer = tokenizer; this._builder = builder; this._token = null; this._nextToken = this._tokenizer.next(); } JavaScriptFormatter.prototype = { format: function() { this._parseSourceElements(Tokens.EOS); this._consume(Tokens.EOS); }, _peek: function() { return this._nextToken.token; }, _next: function() { if (this._token && this._token.token === Tokens.EOS) throw "Unexpected EOS token"; this._builder.addToken(this._nextToken); this._token = this._nextToken; this._nextToken = this._tokenizer.next(this._forceRegexp); this._forceRegexp = false; return this._token.token; }, _consume: function(token) { var next = this._next(); if (next !== token) throw "Unexpected token in consume: expected " + token + ", actual " + next; }, _expect: function(token) { var next = this._next(); if (next !== token) throw "Unexpected token: expected " + token + ", actual " + next; }, _expectSemicolon: function() { if (this._peek() === Tokens.SEMICOLON) this._consume(Tokens.SEMICOLON); }, _hasLineTerminatorBeforeNext: function() { return this._nextToken.nlb; }, _parseSourceElements: function(endToken) { while (this._peek() !== endToken) { this._parseStatement(); this._builder.addNewLine(); } }, _parseStatementOrBlock: function() { if (this._peek() === Tokens.LBRACE) { this._builder.addSpace(); this._parseBlock(); return true; } this._builder.addNewLine(); this._builder.increaseNestingLevel(); this._parseStatement(); this._builder.decreaseNestingLevel(); }, _parseStatement: function() { switch (this._peek()) { case Tokens.LBRACE: return this._parseBlock(); case Tokens.CONST: case Tokens.VAR: return this._parseVariableStatement(); case Tokens.SEMICOLON: return this._next(); case Tokens.IF: return this._parseIfStatement(); case Tokens.DO: return this._parseDoWhileStatement(); case Tokens.WHILE: return this._parseWhileStatement(); case Tokens.FOR: return this._parseForStatement(); case Tokens.CONTINUE: return this._parseContinueStatement(); case Tokens.BREAK: return this._parseBreakStatement(); case Tokens.RETURN: return this._parseReturnStatement(); case Tokens.WITH: return this._parseWithStatement(); case Tokens.SWITCH: return this._parseSwitchStatement(); case Tokens.THROW: return this._parseThrowStatement(); case Tokens.TRY: return this._parseTryStatement(); case Tokens.FUNCTION: return this._parseFunctionDeclaration(); case Tokens.DEBUGGER: return this._parseDebuggerStatement(); default: return this._parseExpressionOrLabelledStatement(); } }, _parseFunctionDeclaration: function() { this._expect(Tokens.FUNCTION); this._builder.addSpace(); this._expect(Tokens.IDENTIFIER); this._parseFunctionLiteral() }, _parseBlock: function() { this._expect(Tokens.LBRACE); this._builder.addNewLine(); this._builder.increaseNestingLevel(); while (this._peek() !== Tokens.RBRACE) { this._parseStatement(); this._builder.addNewLine(); } this._builder.decreaseNestingLevel(); this._expect(Tokens.RBRACE); }, _parseVariableStatement: function() { this._parseVariableDeclarations(); this._expectSemicolon(); }, _parseVariableDeclarations: function() { if (this._peek() === Tokens.VAR) this._consume(Tokens.VAR); else this._consume(Tokens.CONST) this._builder.addSpace(); var isFirstVariable = true; do { if (!isFirstVariable) { this._consume(Tokens.COMMA); this._builder.addSpace(); } isFirstVariable = false; this._expect(Tokens.IDENTIFIER); if (this._peek() === Tokens.ASSIGN) { this._builder.addSpace(); this._consume(Tokens.ASSIGN); this._builder.addSpace(); this._parseAssignmentExpression(); } } while (this._peek() === Tokens.COMMA); }, _parseExpressionOrLabelledStatement: function() { this._parseExpression(); if (this._peek() === Tokens.COLON) { this._expect(Tokens.COLON); this._builder.addSpace(); this._parseStatement(); } this._expectSemicolon(); }, _parseIfStatement: function() { this._expect(Tokens.IF); this._builder.addSpace(); this._expect(Tokens.LPAREN); this._parseExpression(); this._expect(Tokens.RPAREN); var isBlock = this._parseStatementOrBlock(); if (this._peek() === Tokens.ELSE) { if (isBlock) this._builder.addSpace(); else this._builder.addNewLine(); this._next(); if (this._peek() === Tokens.IF) { this._builder.addSpace(); this._parseStatement(); } else this._parseStatementOrBlock(); } }, _parseContinueStatement: function() { this._expect(Tokens.CONTINUE); var token = this._peek(); if (!this._hasLineTerminatorBeforeNext() && token !== Tokens.SEMICOLON && token !== Tokens.RBRACE && token !== Tokens.EOS) { this._builder.addSpace(); this._expect(Tokens.IDENTIFIER); } this._expectSemicolon(); }, _parseBreakStatement: function() { this._expect(Tokens.BREAK); var token = this._peek(); if (!this._hasLineTerminatorBeforeNext() && token !== Tokens.SEMICOLON && token !== Tokens.RBRACE && token !== Tokens.EOS) { this._builder.addSpace(); this._expect(Tokens.IDENTIFIER); } this._expectSemicolon(); }, _parseReturnStatement: function() { this._expect(Tokens.RETURN); var token = this._peek(); if (!this._hasLineTerminatorBeforeNext() && token !== Tokens.SEMICOLON && token !== Tokens.RBRACE && token !== Tokens.EOS) { this._builder.addSpace(); this._parseExpression(); } this._expectSemicolon(); }, _parseWithStatement: function() { this._expect(Tokens.WITH); this._builder.addSpace(); this._expect(Tokens.LPAREN); this._parseExpression(); this._expect(Tokens.RPAREN); this._parseStatementOrBlock(); }, _parseCaseClause: function() { if (this._peek() === Tokens.CASE) { this._expect(Tokens.CASE); this._builder.addSpace(); this._parseExpression(); } else this._expect(Tokens.DEFAULT); this._expect(Tokens.COLON); this._builder.addNewLine(); this._builder.increaseNestingLevel(); while (this._peek() !== Tokens.CASE && this._peek() !== Tokens.DEFAULT && this._peek() !== Tokens.RBRACE) { this._parseStatement(); this._builder.addNewLine(); } this._builder.decreaseNestingLevel(); }, _parseSwitchStatement: function() { this._expect(Tokens.SWITCH); this._builder.addSpace(); this._expect(Tokens.LPAREN); this._parseExpression(); this._expect(Tokens.RPAREN); this._builder.addSpace(); this._expect(Tokens.LBRACE); this._builder.addNewLine(); this._builder.increaseNestingLevel(); while (this._peek() !== Tokens.RBRACE) this._parseCaseClause(); this._builder.decreaseNestingLevel(); this._expect(Tokens.RBRACE); }, _parseThrowStatement: function() { this._expect(Tokens.THROW); this._builder.addSpace(); this._parseExpression(); this._expectSemicolon(); }, _parseTryStatement: function() { this._expect(Tokens.TRY); this._builder.addSpace(); this._parseBlock(); var token = this._peek(); if (token === Tokens.CATCH) { this._builder.addSpace(); this._consume(Tokens.CATCH); this._builder.addSpace(); this._expect(Tokens.LPAREN); this._expect(Tokens.IDENTIFIER); this._expect(Tokens.RPAREN); this._builder.addSpace(); this._parseBlock(); token = this._peek(); } if (token === Tokens.FINALLY) { this._consume(Tokens.FINALLY); this._builder.addSpace(); this._parseBlock(); } }, _parseDoWhileStatement: function() { this._expect(Tokens.DO); var isBlock = this._parseStatementOrBlock(); if (isBlock) this._builder.addSpace(); else this._builder.addNewLine(); this._expect(Tokens.WHILE); this._builder.addSpace(); this._expect(Tokens.LPAREN); this._parseExpression(); this._expect(Tokens.RPAREN); this._expectSemicolon(); }, _parseWhileStatement: function() { this._expect(Tokens.WHILE); this._builder.addSpace(); this._expect(Tokens.LPAREN); this._parseExpression(); this._expect(Tokens.RPAREN); this._parseStatementOrBlock(); }, _parseForStatement: function() { this._expect(Tokens.FOR); this._builder.addSpace(); this._expect(Tokens.LPAREN); if (this._peek() !== Tokens.SEMICOLON) { if (this._peek() === Tokens.VAR || this._peek() === Tokens.CONST) { this._parseVariableDeclarations(); if (this._peek() === Tokens.IN) { this._builder.addSpace(); this._consume(Tokens.IN); this._builder.addSpace(); this._parseExpression(); } } else this._parseExpression(); } if (this._peek() !== Tokens.RPAREN) { this._expect(Tokens.SEMICOLON); this._builder.addSpace(); if (this._peek() !== Tokens.SEMICOLON) this._parseExpression(); this._expect(Tokens.SEMICOLON); this._builder.addSpace(); if (this._peek() !== Tokens.RPAREN) this._parseExpression(); } this._expect(Tokens.RPAREN); this._parseStatementOrBlock(); }, _parseExpression: function() { this._parseAssignmentExpression(); while (this._peek() === Tokens.COMMA) { this._expect(Tokens.COMMA); this._builder.addSpace(); this._parseAssignmentExpression(); } }, _parseAssignmentExpression: function() { this._parseConditionalExpression(); var token = this._peek(); if (Tokens.ASSIGN <= token && token <= Tokens.ASSIGN_MOD) { this._builder.addSpace(); this._next(); this._builder.addSpace(); this._parseAssignmentExpression(); } }, _parseConditionalExpression: function() { this._parseBinaryExpression(); if (this._peek() === Tokens.CONDITIONAL) { this._builder.addSpace(); this._consume(Tokens.CONDITIONAL); this._builder.addSpace(); this._parseAssignmentExpression(); this._builder.addSpace(); this._expect(Tokens.COLON); this._builder.addSpace(); this._parseAssignmentExpression(); } }, _parseBinaryExpression: function() { this._parseUnaryExpression(); var token = this._peek(); while (Tokens.OR <= token && token <= Tokens.IN) { this._builder.addSpace(); this._next(); this._builder.addSpace(); this._parseBinaryExpression(); token = this._peek(); } }, _parseUnaryExpression: function() { var token = this._peek(); if ((Tokens.NOT <= token && token <= Tokens.VOID) || token === Tokens.ADD || token === Tokens.SUB || token === Tokens.INC || token === Tokens.DEC) { this._next(); if (token === Tokens.DELETE || token === Tokens.TYPEOF || token === Tokens.VOID) this._builder.addSpace(); this._parseUnaryExpression(); } else return this._parsePostfixExpression(); }, _parsePostfixExpression: function() { this._parseLeftHandSideExpression(); var token = this._peek(); if (!this._hasLineTerminatorBeforeNext() && (token === Tokens.INC || token === Tokens.DEC)) this._next(); }, _parseLeftHandSideExpression: function() { if (this._peek() === Tokens.NEW) this._parseNewExpression(); else this._parseMemberExpression(); while (true) { switch (this._peek()) { case Tokens.LBRACK: this._consume(Tokens.LBRACK); this._parseExpression(); this._expect(Tokens.RBRACK); break; case Tokens.LPAREN: this._parseArguments(); break; case Tokens.PERIOD: this._consume(Tokens.PERIOD); this._expect(Tokens.IDENTIFIER); break; default: return; } } }, _parseNewExpression: function() { this._expect(Tokens.NEW); this._builder.addSpace(); if (this._peek() === Tokens.NEW) this._parseNewExpression(); else this._parseMemberExpression(); }, _parseMemberExpression: function() { if (this._peek() === Tokens.FUNCTION) { this._expect(Tokens.FUNCTION); if (this._peek() === Tokens.IDENTIFIER) { this._builder.addSpace(); this._expect(Tokens.IDENTIFIER); } this._parseFunctionLiteral(); } else this._parsePrimaryExpression(); while (true) { switch (this._peek()) { case Tokens.LBRACK: this._consume(Tokens.LBRACK); this._parseExpression(); this._expect(Tokens.RBRACK); break; case Tokens.PERIOD: this._consume(Tokens.PERIOD); this._expect(Tokens.IDENTIFIER); break; case Tokens.LPAREN: this._parseArguments(); break; default: return; } } }, _parseDebuggerStatement: function() { this._expect(Tokens.DEBUGGER); this._expectSemicolon(); }, _parsePrimaryExpression: function() { switch (this._peek()) { case Tokens.THIS: return this._consume(Tokens.THIS); case Tokens.NULL_LITERAL: return this._consume(Tokens.NULL_LITERAL); case Tokens.TRUE_LITERAL: return this._consume(Tokens.TRUE_LITERAL); case Tokens.FALSE_LITERAL: return this._consume(Tokens.FALSE_LITERAL); case Tokens.IDENTIFIER: return this._consume(Tokens.IDENTIFIER); case Tokens.NUMBER: return this._consume(Tokens.NUMBER); case Tokens.STRING: return this._consume(Tokens.STRING); case Tokens.ASSIGN_DIV: return this._parseRegExpLiteral(); case Tokens.DIV: return this._parseRegExpLiteral(); case Tokens.LBRACK: return this._parseArrayLiteral(); case Tokens.LBRACE: return this._parseObjectLiteral(); case Tokens.LPAREN: this._consume(Tokens.LPAREN); this._parseExpression(); this._expect(Tokens.RPAREN); return; default: return this._next(); } }, _parseArrayLiteral: function() { this._expect(Tokens.LBRACK); this._builder.increaseNestingLevel(); while (this._peek() !== Tokens.RBRACK) { if (this._peek() !== Tokens.COMMA) this._parseAssignmentExpression(); if (this._peek() !== Tokens.RBRACK) { this._expect(Tokens.COMMA); this._builder.addSpace(); } } this._builder.decreaseNestingLevel(); this._expect(Tokens.RBRACK); }, _parseObjectLiteralGetSet: function() { var token = this._peek(); if (token === Tokens.IDENTIFIER || token === Tokens.NUMBER || token === Tokens.STRING || Tokens.DELETE <= token && token <= Tokens.FALSE_LITERAL || token === Tokens.INSTANCEOF || token === Tokens.IN || token === Tokens.CONST) { this._next(); this._parseFunctionLiteral(); } }, _parseObjectLiteral: function() { this._expect(Tokens.LBRACE); this._builder.increaseNestingLevel(); while (this._peek() !== Tokens.RBRACE) { var token = this._peek(); switch (token) { case Tokens.IDENTIFIER: this._consume(Tokens.IDENTIFIER); var name = this._token.value; if ((name === "get" || name === "set") && this._peek() !== Tokens.COLON) { this._builder.addSpace(); this._parseObjectLiteralGetSet(); if (this._peek() !== Tokens.RBRACE) { this._expect(Tokens.COMMA); } continue; } break; case Tokens.STRING: this._consume(Tokens.STRING); break; case Tokens.NUMBER: this._consume(Tokens.NUMBER); break; default: this._next(); } this._expect(Tokens.COLON); this._builder.addSpace(); this._parseAssignmentExpression(); if (this._peek() !== Tokens.RBRACE) { this._expect(Tokens.COMMA); } } this._builder.decreaseNestingLevel(); this._expect(Tokens.RBRACE); }, _parseRegExpLiteral: function() { if (this._nextToken.type === "regexp") this._next(); else { this._forceRegexp = true; this._next(); } }, _parseArguments: function() { this._expect(Tokens.LPAREN); var done = (this._peek() === Tokens.RPAREN); while (!done) { this._parseAssignmentExpression(); done = (this._peek() === Tokens.RPAREN); if (!done) { this._expect(Tokens.COMMA); this._builder.addSpace(); } } this._expect(Tokens.RPAREN); }, _parseFunctionLiteral: function() { this._expect(Tokens.LPAREN); var done = (this._peek() === Tokens.RPAREN); while (!done) { this._expect(Tokens.IDENTIFIER); done = (this._peek() === Tokens.RPAREN); if (!done) { this._expect(Tokens.COMMA); this._builder.addSpace(); } } this._expect(Tokens.RPAREN); this._builder.addSpace(); this._expect(Tokens.LBRACE); this._builder.addNewLine(); this._builder.increaseNestingLevel(); this._parseSourceElements(Tokens.RBRACE); this._builder.decreaseNestingLevel(); this._expect(Tokens.RBRACE); } } ;
JavaScript
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // CodeMirror is the only global var we claim window.CodeMirror = (function() { "use strict"; // BROWSER SNIFFING // Crude, but necessary to handle a number of hard-to-feature-detect // bugs and behavior differences. var gecko = /gecko\/\d{7}/i.test(navigator.userAgent); var ie = /MSIE \d/.test(navigator.userAgent); var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); var ie_lt10 = /MSIE [1-9]\b/.test(navigator.userAgent); var webkit = /WebKit\//.test(navigator.userAgent); var chrome = /Chrome\//.test(navigator.userAgent); var opera = /Opera\//.test(navigator.userAgent); var safari = /Apple Computer/.test(navigator.vendor); var khtml = /KHTML\//.test(navigator.userAgent); var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); var phantom = /PhantomJS/.test(navigator.userAgent); var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); var mac = ios || /Mac/.test(navigator.platform); var win = /Win/.test(navigator.platform); // Optimize some code when these features are not used var sawReadOnlySpans = false, sawCollapsedSpans = false; // CONSTRUCTOR function CodeMirror(place, options) { if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); this.options = options = options || {}; // Determine effective options based on given values and defaults. for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt)) options[opt] = defaults[opt]; setGuttersForLineNumbers(options); var display = this.display = makeDisplay(place); display.wrapper.CodeMirror = this; updateGutters(this); if (options.autofocus) focusInput(this); var doc = new BranchChunk([new LeafChunk([makeLine("", null, textHeight(display))])]); // The selection. These are always maintained to point at valid // positions. Inverted is used to remember that the user is // selecting bottom-to-top. this.view = { doc: doc, // frontier is the point up to which the content has been parsed, frontier: 0, highlight: new Delayed(), sel: {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false, shift: false}, scrollTop: 0, scrollLeft: 0, overwrite: false, focused: false, // Tracks the maximum line length so that // the horizontal scrollbar can be kept // static when scrolling. maxLine: getLine(doc, 0), maxLineLength: 0, maxLineChanged: false, suppressEdits: false, goalColumn: null, cantEdit: false }; loadMode(this); // Initialize the content. this.setValue(options.value || ""); // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie) setTimeout(bind(resetInput, this, true), 20); this.view.history = makeHistory(); registerEventHandlers(this); // IE throws unspecified error in certain cases, when // trying to access activeElement before onload var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { } if (hasFocus || options.autofocus) setTimeout(bind(onFocus, this), 20); else onBlur(this); operation(this, function() { for (var opt in optionHandlers) if (optionHandlers.propertyIsEnumerable(opt)) optionHandlers[opt](this, options[opt], Init); for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); })(); } // DISPLAY CONSTRUCTOR function makeDisplay(place) { var d = {}; var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;"); input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); // Wraps and hides input textarea d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The actual fake scrollbars. d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar"); d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar"); d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); // DIVs containing the selection and the actual code d.lineDiv = elt("div"); d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); // Blinky cursor, and element used to ensure cursor fits at the end of a line d.cursor = elt("pre", "\u00a0", "CodeMirror-cursor"); // Secondary cursor, shown when on a 'jump' in bi-directional text d.otherCursor = elt("pre", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"); // Used to measure text size d.measure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor], null, "position: relative; outline: none"); // Moved around its parent to cover visible view d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Set to the height of the text, causes scrolling d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers d.heightForcer = elt("div", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px"); // Provides scrolling d.scroller = elt("div", [d.sizer, d.heightForcer], "CodeMirror-scroll"); d.scroller.setAttribute("tabIndex", "-1"); // The element in which the editor lives. d.wrapper = elt("div", [d.gutters, d.inputDiv, d.scrollbarH, d.scrollbarV, d.scrollbarFiller, d.scroller], "CodeMirror"); // Work around IE7 z-index bug if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); // Needed to hide big blue blinking cursor on Mobile Safari if (ios) input.style.width = "0px"; if (!webkit) d.scroller.draggable = true; // Needed to handle Tab key in KHTML if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px"; // Current visible range (may be bigger than the view window). d.viewOffset = d.showingFrom = d.showingTo = d.lastSizeC = 0; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; // See readInput and resetInput d.prevInput = ""; // Set to true when a non-horizontal-scrolling widget is added. As // an optimization, widget aligning is skipped when d is false. d.alignWidgets = false; // Flag that indicates whether we currently expect input to appear // (after some event like 'keypress' or 'input') and are polling // intensively. d.pollingFast = false; // Self-resetting timeout for the poller d.poll = new Delayed(); // True when a drag from the editor is active d.draggingText = false; d.cachedCharWidth = d.cachedTextHeight = null; d.measureLineCache = []; d.measureLineCache.pos = 0; // Tracks when resetInput has punted to just putting a short // string instead of the (large) selection. d.inaccurateSelection = false; // Used to adjust overwrite behaviour when a paste has been // detected d.pasteIncoming = false; return d; } // STATE UPDATES // Used to get the editor into a consistent state again when options change. function loadMode(cm) { var doc = cm.view.doc; cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode); doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); cm.view.frontier = 0; startWorker(cm, 100); } function wrappingChanged(cm) { var doc = cm.view.doc, th = textHeight(cm.display); if (cm.options.lineWrapping) { cm.display.wrapper.className += " CodeMirror-wrap"; var perLine = cm.display.scroller.clientWidth / charWidth(cm.display) - 3; doc.iter(0, doc.size, function(line) { if (line.height == 0) return; var guess = Math.ceil(line.text.length / perLine) || 1; if (guess != 1) updateLineHeight(line, guess * th); }); cm.display.sizer.style.minWidth = ""; } else { cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); computeMaxLength(cm.view); doc.iter(0, doc.size, function(line) { if (line.height != 0) updateLineHeight(line, th); }); } regChange(cm, 0, doc.size); } function keyMapChanged(cm) { var style = keyMap[cm.options.keyMap].style; cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + (style ? " cm-keymap-" + style : ""); } function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); } function guttersChanged(cm) { updateGutters(cm); updateDisplay(cm, true); } function updateGutters(cm) { var gutters = cm.display.gutters, specs = cm.options.gutters; removeChildren(gutters); for (var i = 0; i < specs.length; ++i) { var gutterClass = specs[i]; var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); if (gutterClass == "CodeMirror-linenumbers") { cm.display.lineGutter = gElt; gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; } } gutters.style.display = i ? "" : "none"; } function lineLength(doc, line) { if (line.height == 0) return 0; var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(); cur = getLine(doc, found.from.line); len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found = merged.find(); len -= cur.text.length - found.from.ch; cur = getLine(doc, found.to.line); len += cur.text.length - found.to.ch; } return len; } function computeMaxLength(view) { view.maxLine = getLine(view.doc, 0); view.maxLineLength = lineLength(view.doc, view.maxLine); view.maxLineChanged = true; view.doc.iter(1, view.doc.size, function(line) { var len = lineLength(view.doc, line); if (len > view.maxLineLength) { view.maxLineLength = len; view.maxLine = line; } }); } // Make sure the gutters options contains the element // "CodeMirror-linenumbers" when the lineNumbers option is true. function setGuttersForLineNumbers(options) { var found = false; for (var i = 0; i < options.gutters.length; ++i) { if (options.gutters[i] == "CodeMirror-linenumbers") { if (options.lineNumbers) found = true; else options.gutters.splice(i--, 1); } } if (!found && options.lineNumbers) options.gutters.push("CodeMirror-linenumbers"); } // SCROLLBARS // Re-synchronize the fake scrollbars with the actual size of the // content. Optionally force a scrollTop. function updateScrollbars(d /* display */, docHeight, scrollTop) { d.sizer.style.minHeight = d.heightForcer.style.top = (docHeight + 2 * paddingTop(d)) + "px"; var needsH = d.scroller.scrollWidth > d.scroller.clientWidth; var needsV = d.scroller.scrollHeight > d.scroller.clientHeight; if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarV.firstChild.style.height = (d.scroller.scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; if (scrollTop != null) { d.scrollbarV.scrollTop = d.scroller.scrollTop = scrollTop; // 'Nudge' the scrollbar to work around a Webkit bug where, // in some situations, we'd end up with a scrollbar that // reported its scrollTop (and looked) as expected, but // *behaved* as if it was still in a previous state (i.e. // couldn't scroll up, even though it appeared to be at the // bottom). if (webkit) setTimeout(function() { if (d.scrollbarV.scrollTop != scrollTop) return; d.scrollbarV.scrollTop = scrollTop + (scrollTop ? -1 : 1); d.scrollbarV.scrollTop = scrollTop; }, 0); } } else d.scrollbarV.style.display = ""; if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarH.firstChild.style.width = (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; } else d.scrollbarH.style.display = ""; if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; } else d.scrollbarFiller.style.display = ""; if (mac_geLion && scrollbarWidth(d.measure) === 0) d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; } function visibleLines(display, doc, viewPort) { var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; if (typeof viewPort == "number") top = viewPort; else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;} top = Math.floor(top - paddingTop(display)); var bottom = Math.ceil(top + height); return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; } // LINE NUMBERS function alignVertically(display) { if (!display.alignWidgets && !display.gutters.firstChild) return; var l = compensateForHScroll(display) + "px"; for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) { for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; } } function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) return false; var doc = cm.view.doc, last = lineNumberFor(cm.options, doc.size - 1), display = cm.display; if (last.length != display.lineNumChars) { var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; display.lineGutter.style.width = ""; display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; return true; } return false; } function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)); } function compensateForHScroll(display) { return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; } // DISPLAY DRAWING function updateDisplay(cm, changes, viewPort) { var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo; var updated = updateDisplayInner(cm, changes, viewPort); if (updated) { signalLater(cm, cm, "update", cm); if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) signalLater(cm, cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); } updateSelection(cm); updateScrollbars(cm.display, cm.view.doc.height, typeof viewPort == "number" ? viewPort : null); return updated; } // Uses a set of changes plus the current scroll position to // determine which DOM updates have to be made, and makes the // updates. function updateDisplayInner(cm, changes, viewPort) { var display = cm.display, doc = cm.view.doc; if (!display.wrapper.clientWidth) { display.showingFrom = display.showingTo = display.viewOffset = 0; return; } // Compute the new visible window // If scrollTop is specified, use that to determine which lines // to render instead of the current scrollbar position. var visible = visibleLines(display, doc, viewPort); // Bail out if the visible area is already rendered and nothing changed. if (changes !== true && changes.length == 0 && visible.from > display.showingFrom && visible.to < display.showingTo) return; if (changes && maybeUpdateLineNumberWidth(cm)) changes = true; display.sizer.style.marginLeft = display.scrollbarH.style.left = display.gutters.offsetWidth + "px"; // When merged lines are present, the line that needs to be // redrawn might not be the one that was changed. if (changes !== true && sawCollapsedSpans) for (var i = 0; i < changes.length; ++i) { var ch = changes[i], merged; while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) { var from = merged.find().from.line; if (ch.diff) ch.diff -= ch.from - from; ch.from = from; } } // Used to determine which lines need their line numbers updated var positionsChangedFrom = changes === true ? 0 : Infinity; if (cm.options.lineNumbers && changes && changes !== true) for (var i = 0; i < changes.length; ++i) if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; } var from = Math.max(visible.from - cm.options.viewportMargin, 0); var to = Math.min(doc.size, visible.to + cm.options.viewportMargin); if (display.showingFrom < from && from - display.showingFrom < 20) from = display.showingFrom; if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(doc.size, display.showingTo); // Create a range of theoretically intact lines, and punch holes // in that using the change info. var intact = changes === true ? [] : computeIntact([{from: display.showingFrom, to: display.showingTo, domStart: 0}], changes); // Clip off the parts that won't be visible var intactLines = 0; for (var i = 0; i < intact.length; ++i) { var range = intact[i]; if (range.from < from) {range.domStart += (from - range.from); range.from = from;} if (range.to > to) range.to = to; if (range.from >= range.to) intact.splice(i--, 1); else intactLines += range.to - range.from; } if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) return; intact.sort(function(a, b) {return a.domStart - b.domStart;}); if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; patchDisplay(cm, from, to, intact, positionsChangedFrom); display.lineDiv.style.display = ""; var different = from != display.showingFrom || to != display.showingTo || display.lastSizeC != display.wrapper.clientHeight; // This is just a bogus formula that detects when the editor is // resized or the font size changes. if (different) display.lastSizeC = display.wrapper.clientHeight; display.showingFrom = from; display.showingTo = to; display.viewOffset = heightAtLine(cm, getLine(doc, from)); startWorker(cm, 100); // Since this is all rather error prone, it is honoured with the // only assertion in the whole file. if (display.lineDiv.childNodes.length != display.showingTo - display.showingFrom) throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (display.showingTo - display.showingFrom) + " nodes=" + display.lineDiv.childNodes.length); // Update line heights for visible lines based on actual DOM // sizes var curNode = display.lineDiv.firstChild, relativeTo = curNode.offsetTop; doc.iter(display.showingFrom, display.showingTo, function(line) { // Work around bizarro IE7 bug where, sometimes, our curNode // is magically replaced with a new node in the DOM, leaving // us with a reference to an orphan (nextSibling-less) node. if (!curNode) return; if (!lineIsHidden(line)) { var end = curNode.offsetHeight + curNode.offsetTop; var height = end - relativeTo, diff = line.height - height; if (height < 2) height = textHeight(display); relativeTo = end; if (diff > .001 || diff < -.001) updateLineHeight(line, height); } curNode = curNode.nextSibling; }); // Position the mover div to align with the current virtual scroll position display.mover.style.top = display.viewOffset + "px"; return true; } function computeIntact(intact, changes) { for (var i = 0, l = changes.length || 0; i < l; ++i) { var change = changes[i], intact2 = [], diff = change.diff || 0; for (var j = 0, l2 = intact.length; j < l2; ++j) { var range = intact[j]; if (change.to <= range.from && change.diff) intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart}); else if (change.to <= range.from || change.from >= range.to) intact2.push(range); else { if (change.from > range.from) intact2.push({from: range.from, to: change.from, domStart: range.domStart}); if (change.to < range.to) intact2.push({from: change.to + diff, to: range.to + diff, domStart: range.domStart + (change.to - range.from)}); } } intact = intact2; } return intact; } function getDimensions(cm) { var d = cm.display, left = {}, width = {}; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { left[cm.options.gutters[i]] = n.offsetLeft; width[cm.options.gutters[i]] = n.offsetWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth}; } function patchDisplay(cm, from, to, intact, updateNumbersFrom) { function killNode(node) { var tmp = node.nextSibling; node.parentNode.removeChild(node); return tmp; } var dims = getDimensions(cm); var display = cm.display, lineNumbers = cm.options.lineNumbers; // The first pass removes the DOM nodes that aren't intact. if (!intact.length) { // old IE does bad things to nodes when .innerHTML = "" is used on a parent // we still need widgets and markers intact to add back to the new content later if (ie_lt10) for (var ld = display.lineDiv, tmp = ld.firstChild; tmp; tmp = ld.firstChild) ld.removeChild(tmp); else removeChildren(display.lineDiv); } else { var domPos = 0, curNode = display.lineDiv.firstChild, n; for (var i = 0; i < intact.length; ++i) { var cur = intact[i]; while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;} for (var j = cur.from, e = cur.to; j < e; ++j) { if (lineNumbers && updateNumbersFrom <= j && curNode.firstChild) setTextContent(curNode.firstChild.firstChild, lineNumberFor(cm.options, j)); curNode = curNode.nextSibling; domPos++; } } while (curNode) curNode = killNode(curNode); } // This pass fills in the lines that actually changed. var nextIntact = intact.shift(), curNode = display.lineDiv.firstChild; var j = from; cm.view.doc.iter(from, to, function(line) { if (nextIntact && nextIntact.to == j) nextIntact = intact.shift(); if (!nextIntact || nextIntact.from > j) display.lineDiv.insertBefore(buildLineElement(cm, line, j, dims), curNode); else curNode = curNode.nextSibling; ++j; }); } function buildLineElement(cm, line, lineNo, dims) { if (line.height == 0) return elt("div"); var lineElement = line.height == 0 ? elt("div") : lineContent(cm, line); var markers = line.gutterMarkers, display = cm.display; if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && (!line.widgets || !line.widgets.length)) return lineElement; // Lines with gutter elements or a background class need // to be wrapped again, and have the extra elements added // to the wrapper div var wrap = elt("div", null, line.wrapClass, "position: relative"); if (cm.options.lineNumbers || markers) { var gutterWrap = wrap.appendChild(elt("div", null, null, "position: absolute; left: " + dims.fixedPos + "px")); wrap.alignable = [gutterWrap]; if (cm.options.lineNumbers) gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineNo), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + display.lineNumInnerWidth + "px")); if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; if (found) { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); } } } // Kludge to make sure the styled element lies behind the selection (by z-index) if (line.bgClass) wrap.appendChild(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground")); wrap.appendChild(lineElement); if (line.widgets) for (var i = 0, ws = line.widgets; i < ws.length; ++i) { var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); node.widget = widget; if (widget.noHScroll) { (wrap.alignable || (wrap.alignable = [])).push(node); var width = dims.wrapperWidth; node.style.left = dims.fixedPos + "px"; if (!widget.coverGutter) { width -= dims.gutterTotalWidth; node.style.paddingLeft = dims.gutterTotalWidth + "px"; } node.style.width = width + "px"; } if (widget.coverGutter) { node.style.zIndex = 5; node.style.position = "relative"; if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; } if (widget.above) wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); else wrap.appendChild(node); } if (ie_lt8) wrap.style.zIndex = 2; return wrap; } // SELECTION / CURSOR function selHead(view) { return view.sel.inverted ? view.sel.from : view.sel.to; } function updateSelection(cm) { var headPos = posEq(cm.view.sel.from, cm.view.sel.to) ? updateSelectionCursor(cm) : updateSelectionRange(cm); var display = cm.display; // Move the hidden textarea near the cursor to prevent scrolling artifacts var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)) + "px"; display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)) + "px"; } // No selection, plain cursor function updateSelectionCursor(cm) { var display = cm.display, pos = cursorCoords(cm, cm.view.sel.from, "div"); display.cursor.style.left = pos.left + "px"; display.cursor.style.top = pos.top + "px"; display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; display.cursor.style.display = ""; display.selectionDiv.style.display = "none"; if (pos.other) { display.otherCursor.style.display = ""; display.otherCursor.style.left = pos.other.left + "px"; display.otherCursor.style.top = pos.other.top + "px"; display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } else { display.otherCursor.style.display = "none"; } return pos; } // Highlight selection function updateSelectionRange(cm) { var display = cm.display, doc = cm.view.doc, sel = cm.view.sel; var fragment = document.createDocumentFragment(); var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display); function add(left, top, width, bottom) { if (top < 0) top = 0; fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) + "px; height: " + (bottom - top) + "px")); } function drawForLine(line, fromArg, toArg, retTop) { var lineObj = getLine(doc, line); var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity; function coords(ch) { return charCoords(cm, {line: line, ch: ch}, "div", lineObj); } iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { var leftPos = coords(dir == "rtl" ? to - 1 : from); var rightPos = coords(dir == "rtl" ? from : to - 1); var left = leftPos.left, right = rightPos.right; if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part add(left, leftPos.top, null, leftPos.bottom); left = pl; if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); } if (toArg == null && to == lineLen) right = clientWidth; if (fromArg == null && from == 0) left = pl; rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal); if (left < pl + 1) left = pl; add(left, rightPos.top, right - left, rightPos.bottom); }); return rVal; } if (sel.from.line == sel.to.line) { drawForLine(sel.from.line, sel.from.ch, sel.to.ch); } else { var fromObj = getLine(doc, sel.from.line); var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine; while (merged = collapsedSpanAtEnd(cur)) { var found = merged.find(); path.push(found.from.ch, found.to.line, found.to.ch); if (found.to.line == sel.to.line) { path.push(sel.to.ch); singleLine = true; break; } cur = getLine(doc, found.to.line); } // This is a single, merged line if (singleLine) { for (var i = 0; i < path.length; i += 3) drawForLine(path[i], path[i+1], path[i+2]); } else { var middleTop, middleBot, toObj = getLine(doc, sel.to.line); if (sel.from.ch) // Draw the first line of selection. middleTop = drawForLine(sel.from.line, sel.from.ch, null, false); else // Simply include it in the middle block. middleTop = heightAtLine(cm, fromObj) - display.viewOffset; if (!sel.to.ch) middleBot = heightAtLine(cm, toObj) - display.viewOffset; else middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true); if (middleTop < middleBot) add(pl, middleTop, null, middleBot); } } removeChildrenAndAdd(display.selectionDiv, fragment); display.cursor.style.display = display.otherCursor.style.display = "none"; display.selectionDiv.style.display = ""; return cursorCoords(cm, selHead(cm.view), "div"); } // Cursor-blinking function restartBlink(cm) { var display = cm.display; clearInterval(display.blinker); var on = true; display.cursor.style.visibility = display.otherCursor.style.visibility = ""; display.blinker = setInterval(function() { display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.view.frontier < cm.display.showingTo) cm.view.highlight.set(time, bind(highlightWorker, cm)); } function highlightWorker(cm) { var view = cm.view, doc = view.doc; if (view.frontier >= cm.display.showingTo) return; var end = +new Date + cm.options.workTime; var state = copyState(view.mode, getStateBefore(cm, view.frontier)); var changed = [], prevChange; doc.iter(view.frontier, Math.min(doc.size, cm.display.showingTo + 500), function(line) { if (view.frontier >= cm.display.showingFrom) { // Visible if (highlightLine(cm, line, state) && view.frontier >= cm.display.showingFrom) { if (prevChange && prevChange.end == view.frontier) prevChange.end++; else changed.push(prevChange = {start: view.frontier, end: view.frontier + 1}); } line.stateAfter = copyState(view.mode, state); } else { processLine(cm, line, state); line.stateAfter = view.frontier % 5 == 0 ? copyState(view.mode, state) : null; } ++view.frontier; if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true; } }); if (changed.length) operation(cm, function() { for (var i = 0; i < changed.length; ++i) regChange(this, changed[i].start, changed[i].end); })(); } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n) { var minindent, minline, doc = cm.view.doc; for (var search = n, lim = n - 100; search > lim; --search) { if (search == 0) return 0; var line = getLine(doc, search-1); if (line.stateAfter) return search; var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline; } function getStateBefore(cm, n) { var view = cm.view; var pos = findStartLine(cm, n), state = pos && getLine(view.doc, pos-1).stateAfter; if (!state) state = startState(view.mode); else state = copyState(view.mode, state); view.doc.iter(pos, n, function(line) { processLine(cm, line, state); var save = pos == n - 1 || pos % 5 == 0 || pos >= view.showingFrom && pos < view.showingTo; line.stateAfter = save ? copyState(view.mode, state) : null; ++pos; }); return state; } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop;} function paddingLeft(display) { var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x")); return e.offsetLeft; } function measureChar(cm, line, ch, data) { var data = data || measureLine(cm, line); var dir = -1, len = line.text.length; for (var pos = ch;; pos += dir) { var r = data[pos]; if (r) break; if (dir < 0 && pos == 0) dir = 1; } return {left: pos < ch ? r.right : r.left, right: pos > ch ? r.left : r.right, top: r.top, bottom: r.bottom}; } function measureLine(cm, line) { // First look in the cache var display = cm.display, cache = cm.display.measureLineCache; for (var i = 0; i < cache.length; ++i) { var memo = cache[i]; if (memo.text == line.text && memo.markedSpans == line.markedSpans && display.scroller.clientWidth == memo.width) return memo.measure; } var measure = measureLineInner(cm, line); // Store result in the cache var memo = {text: line.text, width: display.scroller.clientWidth, markedSpans: line.markedSpans, measure: measure}; if (cache.length == 16) cache[++cache.pos % 16] = memo; else cache.push(memo); return measure; } function measureLineInner(cm, line) { var display = cm.display, measure = emptyArray(line.text.length); var pre = lineContent(cm, line, measure); removeChildrenAndAdd(display.measure, pre); var outer = display.lineDiv.getBoundingClientRect(); var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; for (var i = 0, elt; i < measure.length; ++i) if (elt = measure[i]) { var size = measure[i].getBoundingClientRect(); var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot); for (var j = 0; j < vranges.length; j += 2) { var rtop = vranges[j], rbot = vranges[j+1]; if (rtop > bot || rbot < top) continue; if (rtop <= top && rbot >= bot || top <= rtop && bot >= rbot || Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { vranges[j] = Math.min(top, rtop); vranges[j+1] = Math.max(bot, rbot); break; } } if (j == vranges.length) vranges.push(top, bot); data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j}; } for (var i = 0, elt; i < data.length; ++i) if (elt = data[i]) { var vr = elt.top; elt.top = vranges[vr]; elt.bottom = vranges[vr+1]; } return data; } // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page" function intoCoordSystem(cm, lineObj, pos, rect, context) { if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { var size = lineObj.widgets[i].node.offsetHeight; rect.top += size; rect.bottom += size; } if (context == "line") return rect; if (!context) context = "local"; var yOff = heightAtLine(cm, lineObj); if (context != "local") yOff -= cm.display.viewOffset; if (context == "page") { var lOff = cm.display.lineSpace.getBoundingClientRect(); yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop); var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft); rect.left += xOff; rect.right += xOff; } rect.top += yOff; rect.bottom += yOff; return rect; } function charCoords(cm, pos, context, lineObj) { if (!lineObj) lineObj = getLine(cm.view.doc, pos.line); return intoCoordSystem(cm, lineObj, pos, measureChar(cm, lineObj, pos.ch), context); } function cursorCoords(cm, pos, context, lineObj, measurement) { lineObj = lineObj || getLine(cm.view.doc, pos.line); if (!measurement) measurement = measureLine(cm, lineObj); function get(ch, right) { var m = measureChar(cm, lineObj, ch, measurement); if (right) m.left = m.right; else m.right = m.left; return intoCoordSystem(cm, lineObj, pos, m, context); } var order = getOrder(lineObj), ch = pos.ch; if (!order) return get(ch); var main, other, linedir = order[0].level; for (var i = 0; i < order.length; ++i) { var part = order[i], rtl = part.level % 2, nb, here; if (part.from < ch && part.to > ch) return get(ch, rtl); var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to; if (left == ch) { // Opera and IE return bogus offsets and widths for edges // where the direction flips, but only for the side with the // lower level. So we try to use the side with the higher // level. if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true); else here = get(rtl && part.from != part.to ? ch - 1 : ch); if (rtl == linedir) main = here; else other = here; } else if (right == ch) { var nb = i < order.length - 1 && order[i+1]; if (!rtl && nb && nb.from == nb.to) continue; if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from); else here = get(rtl ? ch : ch - 1, true); if (rtl == linedir) main = here; else other = here; } } if (linedir && !ch) other = get(order[0].to - 1); if (!main) return other; if (other) main.other = other; return main; } // Coords must be lineSpace-local function coordsChar(cm, x, y) { var doc = cm.view.doc; y += cm.display.viewOffset; if (y < 0) return {line: 0, ch: 0, outside: true}; var lineNo = lineAtHeight(doc, y); if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length}; if (x < 0) x = 0; for (;;) { var lineObj = getLine(doc, lineNo); var found = coordsCharInner(cm, lineObj, lineNo, x, y); var merged = collapsedSpanAtEnd(lineObj); if (merged && found.ch == lineRight(lineObj)) lineNo = merged.find().to.line; else return found; } } function coordsCharInner(cm, lineObj, lineNo, x, y) { var doc = cm.view.doc; var innerOff = y - heightAtLine(cm, lineObj); var wrongLine = false, cWidth = cm.display.wrapper.clientWidth; var measurement = measureLine(cm, lineObj); function getX(ch) { var sp = cursorCoords(cm, {line: lineNo, ch: ch}, "line", lineObj, measurement); wrongLine = true; if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth); else if (innerOff < sp.top) return sp.left + cWidth; else wrongLine = false; return sp.left; } var bidi = getOrder(lineObj), dist = lineObj.text.length; var from = lineLeft(lineObj), to = lineRight(lineObj), fromX = paddingLeft(cm.display), toX; if (!bidi) { // Guess a suitable upper bound for our search. var estimated = Math.min(to, Math.ceil((x + Math.floor(innerOff / textHeight(cm.display)) * cWidth * .9) / charWidth(cm.display))); for (;;) { var estX = getX(estimated); if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); else {toX = estX; to = estimated; break;} } // Try to guess a suitable lower bound as well. estimated = Math.floor(to * 0.8); estX = getX(estimated); if (estX < x) {from = estimated; fromX = estX;} dist = to - from; } else toX = getX(to); if (x > toX) return {line: lineNo, ch: to, outside: wrongLine}; // Do a binary search between these bounds. for (;;) { if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { var after = x - fromX < toX - x, ch = after ? from : to; while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; return {line: lineNo, ch: ch, after: after, outside: wrongLine}; } var step = Math.ceil(dist / 2), middle = from + step; if (bidi) { middle = from; for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); } var middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; dist -= step;} else {from = middle; fromX = middleX; dist = step;} } } var measureText; function textHeight(display) { if (display.cachedTextHeight != null) return display.cachedTextHeight; if (measureText == null) { measureText = elt("pre"); // Measure a bunch of lines, for browsers that compute // fractional heights. for (var i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")); measureText.appendChild(elt("br")); } measureText.appendChild(document.createTextNode("x")); } removeChildrenAndAdd(display.measure, measureText); var height = measureText.offsetHeight / 50; if (height > 3) display.cachedTextHeight = height; removeChildren(display.measure); return height || 1; } function charWidth(display) { if (display.cachedCharWidth != null) return display.cachedCharWidth; var anchor = elt("span", "x"); var pre = elt("pre", [anchor]); removeChildrenAndAdd(display.measure, pre); var width = anchor.offsetWidth; if (width > 2) display.cachedCharWidth = width; return width || 10; } // OPERATIONS // Operations are used to wrap changes in such a way that each // change won't have to update the cursor and display (which would // be awkward, slow, and error-prone), but instead updates are // batched and then all combined and executed at once. function startOperation(cm) { if (cm.curOp) ++cm.curOp.depth; else cm.curOp = { // Nested operations delay update until the outermost one // finishes. depth: 1, // An array of ranges of lines that have to be updated. See // updateDisplay. changes: [], delayedCallbacks: [], updateInput: null, userSelChange: null, textChanged: null, selectionChanged: false, updateMaxLine: false }; } function endOperation(cm) { var op = cm.curOp; if (--op.depth) return; cm.curOp = null; var view = cm.view, display = cm.display; if (op.updateMaxLine) computeMaxLength(view); if (view.maxLineChanged && !cm.options.lineWrapping) { var width = measureChar(cm, view.maxLine, view.maxLine.text.length).right; display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px"; view.maxLineChanged = false; } var newScrollPos, updated; if (op.selectionChanged) { var coords = cursorCoords(cm, selHead(view)); newScrollPos = calculateScrollPos(display, coords.left, coords.top, coords.left, coords.bottom); } if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop); if (!updated && op.selectionChanged) updateSelection(cm); if (newScrollPos) scrollCursorIntoView(cm); if (op.selectionChanged) restartBlink(cm); if (view.focused && op.updateInput) resetInput(cm, op.userSelChange); if (op.textChanged) signal(cm, "change", cm, op.textChanged); if (op.selectionChanged) signal(cm, "cursorActivity", cm); for (var i = 0; i < op.delayedCallbacks.length; ++i) op.delayedCallbacks[i](cm); } // Wraps a function in an operation. Returns the wrapped function. function operation(cm1, f) { return function() { var cm = cm1 || this; startOperation(cm); try {var result = f.apply(cm, arguments);} finally {endOperation(cm);} return result; }; } function regChange(cm, from, to, lendiff) { cm.curOp.changes.push({from: from, to: to, diff: lendiff}); } // INPUT HANDLING function slowPoll(cm) { if (cm.view.pollingFast) return; cm.display.poll.set(cm.options.pollInterval, function() { readInput(cm); if (cm.view.focused) slowPoll(cm); }); } function fastPoll(cm) { var missed = false; cm.display.pollingFast = true; function p() { var changed = readInput(cm); if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} else {cm.display.pollingFast = false; slowPoll(cm);} } cm.display.poll.set(20, p); } // prevInput is a hack to work with IME. If we reset the textarea // on every change, that breaks IME. So we look for changes // compared to the previous content instead. (Modern browsers have // events that indicate IME taking place, but these are not widely // supported or compatible enough yet to rely on.) function readInput(cm) { var input = cm.display.input, prevInput = cm.display.prevInput, view = cm.view, sel = view.sel; if (!view.focused || hasSelection(input) || isReadOnly(cm)) return false; var text = input.value; if (text == prevInput && posEq(sel.from, sel.to)) return false; startOperation(cm); view.sel.shift = null; var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput[same] == text[same]) ++same; if (same < prevInput.length) sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)}; else if (view.overwrite && posEq(sel.from, sel.to) && !cm.display.pasteIncoming) sel.to = {line: sel.to.line, ch: Math.min(getLine(cm.view.doc, sel.to.line).text.length, sel.to.ch + (text.length - same))}; var updateInput = cm.curOp.updateInput; cm.replaceSelection(text.slice(same), "end"); cm.curOp.updateInput = updateInput; if (text.length > 1000) { input.value = cm.display.prevInput = ""; } else cm.display.prevInput = text; endOperation(cm); cm.display.pasteIncoming = false; return true; } function resetInput(cm, user) { var view = cm.view, minimal, selected; if (!posEq(view.sel.from, view.sel.to)) { cm.display.prevInput = ""; minimal = hasCopyEvent && (view.sel.to.line - view.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); if (minimal) cm.display.input.value = "-"; else cm.display.input.value = selected || cm.getSelection(); if (view.focused) selectInput(cm.display.input); } else if (user) cm.display.prevInput = cm.display.input.value = ""; cm.display.inaccurateSelection = minimal; } function focusInput(cm) { if (cm.options.readOnly != "nocursor") cm.display.input.focus(); } function isReadOnly(cm) { return cm.options.readOnly || cm.view.cantEdit; } // EVENT HANDLERS function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); on(d.gutters, "mousedown", operation(cm, clickInGutter)); on(d.scroller, "dblclick", operation(cm, e_preventDefault)); on(d.lineSpace, "selectstart", function(e) { if (!mouseEventInWidget(d, e)) e_preventDefault(e); }); // Gecko browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for Gecko. if (!gecko) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); on(d.scroller, "scroll", function() { setScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft); signal(cm, "scroll", cm); }); on(d.scrollbarV, "scroll", function() { setScrollTop(cm, d.scrollbarV.scrollTop); }); on(d.scrollbarH, "scroll", function() { setScrollLeft(cm, d.scrollbarH.scrollLeft); }); on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); function reFocus() { if (cm.view.focused) setTimeout(bind(focusInput, cm), 0); } on(d.scrollbarH, "mousedown", reFocus); on(d.scrollbarV, "mousedown", reFocus); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); on(window, "resize", function resizeHandler() { // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = null; d.measureLineCache.length = d.measureLineCache.pos = 0; if (d.wrapper.parentNode) updateDisplay(cm, true); else off(window, "resize", resizeHandler); }); on(d.input, "keyup", operation(cm, function(e) { if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; if (e_prop(e, "keyCode") == 16) cm.view.sel.shift = null; })); on(d.input, "input", bind(fastPoll, cm)); on(d.input, "keydown", operation(cm, onKeyDown)); on(d.input, "keypress", operation(cm, onKeyPress)); on(d.input, "focus", bind(onFocus, cm)); on(d.input, "blur", bind(onBlur, cm)); function drag_(e) { if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; e_stop(e); } if (cm.options.dragDrop) { on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); on(d.scroller, "dragenter", drag_); on(d.scroller, "dragover", drag_); on(d.scroller, "drop", operation(cm, onDrop)); } on(d.scroller, "paste", function(){focusInput(cm); fastPoll(cm);}); on(d.input, "paste", function() { d.pasteIncoming = true; fastPoll(cm); }); function prepareCopy() { if (d.inaccurateSelection) { d.prevInput = ""; d.inaccurateSelection = false; d.input.value = cm.getSelection(); selectInput(d.input); } } on(d.input, "cut", prepareCopy); on(d.input, "copy", prepareCopy); // Needed to handle Tab key in KHTML if (khtml) on(d.sizer, "mouseup", function() { if (document.activeElement == d.input) d.input.blur(); focusInput(cm); }); } function mouseEventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) || n.parentNode == display.sizer && n != display.mover) return true; } function posFromMouse(cm, e, liberal) { var display = cm.display; if (!liberal) { var target = e_target(e); if (target == display.scrollbarH || target == display.scrollbarH.firstChild || target == display.scrollbarV || target == display.scrollbarV.firstChild || target == display.scrollbarFiller) return null; } var x, y, space = display.lineSpace.getBoundingClientRect(); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX; y = e.clientY; } catch (e) { return null; } return coordsChar(cm, x - space.left, y - space.top); } var lastClick, lastDoubleClick; function onMouseDown(e) { var cm = this, display = cm.display, view = cm.view, sel = view.sel, doc = view.doc; setShift(cm.view, e_prop(e, "shiftKey")); if (mouseEventInWidget(display, e)) { if (!webkit) { display.scroller.draggable = false; setTimeout(function(){display.scroller.draggable = true;}, 100); } return; } if (clickInGutter.call(cm, e)) return; var start = posFromMouse(cm, e); switch (e_button(e)) { case 3: if (gecko) onContextMenu.call(cm, cm, e); return; case 2: if (start) setSelectionUser(cm, start, start); setTimeout(bind(focusInput, cm), 20); e_preventDefault(e); return; } // For button 1, if it was clicked inside the editor // (posFromMouse returning non-null), we have to adjust the // selection. if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;} if (!view.focused) onFocus(cm); var now = +new Date, type = "single"; if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { type = "triple"; e_preventDefault(e); setTimeout(bind(focusInput, cm), 20); selectLine(cm, start.line); } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { type = "double"; lastDoubleClick = {time: now, pos: start}; e_preventDefault(e); var word = findWordAt(getLine(doc, start.line).text, start); setSelectionUser(cm, word.from, word.to); } else { lastClick = {time: now, pos: start}; } var last = start; if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) && !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { var dragEnd = operation(cm, function(e2) { if (webkit) display.scroller.draggable = false; view.draggingText = false; off(document, "mouseup", dragEnd); off(display.scroller, "drop", dragEnd); if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { e_preventDefault(e2); setSelectionUser(cm, start, start); focusInput(cm); } }); // Let the drag handler handle this. if (webkit) display.scroller.draggable = true; view.draggingText = dragEnd; // IE's approach to draggable if (display.scroller.dragDrop) display.scroller.dragDrop(); on(document, "mouseup", dragEnd); on(display.scroller, "drop", dragEnd); return; } e_preventDefault(e); if (type == "single") setSelectionUser(cm, start, start); var startstart = sel.from, startend = sel.to; function doSelect(cur) { if (type == "single") { setSelectionUser(cm, start, cur); } else if (type == "double") { var word = findWordAt(getLine(doc, cur.line).text, cur); if (posLess(cur, startstart)) setSelectionUser(cm, word.from, startend); else setSelectionUser(cm, startstart, word.to); } else if (type == "triple") { if (posLess(cur, startstart)) setSelectionUser(cm, startend, clipPos(doc, {line: cur.line, ch: 0})); else setSelectionUser(cm, startstart, clipPos(doc, {line: cur.line + 1, ch: 0})); } } var editorSize = display.wrapper.getBoundingClientRect(); // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). var counter = 0; function extend(e) { var curCount = ++counter; var cur = posFromMouse(cm, e, true); if (!cur) return; if (!posEq(cur, last)) { if (!view.focused) onFocus(cm); last = cur; doSelect(cur); var visible = visibleLines(display, doc); if (cur.line >= visible.to || cur.line < visible.from) setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); } else { var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; if (outside) setTimeout(operation(cm, function() { if (counter != curCount) return; display.scroller.scrollTop += outside; extend(e); }), 50); } } function done(e) { counter = Infinity; var cur = posFromMouse(cm, e); if (cur) doSelect(cur); e_preventDefault(e); focusInput(cm); off(document, "mousemove", move); off(document, "mouseup", up); } var move = operation(cm, function(e) { e_preventDefault(e); if (!ie && !e_button(e)) done(e); else extend(e); }); var up = operation(cm, done); on(document, "mousemove", move); on(document, "mouseup", up); } function onDrop(e) { var cm = this; if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; e_preventDefault(e); var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || isReadOnly(cm)) return; if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var loadFile = function(file, i) { var reader = new FileReader; reader.onload = function() { text[i] = reader.result; if (++read == n) { pos = clipPos(cm.view.doc, pos); operation(cm, function() { var end = replaceRange(cm, text.join(""), pos, pos); setSelectionUser(cm, pos, end); })(); } }; reader.readAsText(file); }; for (var i = 0; i < n; ++i) loadFile(files[i], i); } else { // Don't do a replace if the drop happened inside of the selected text. if (cm.view.draggingText && !(posLess(pos, cm.view.sel.from) || posLess(cm.view.sel.to, pos))) { cm.view.draggingText(e); if (ie) setTimeout(bind(focusInput, cm), 50); return; } try { var text = e.dataTransfer.getData("Text"); if (text) { compoundChange(cm, function() { var curFrom = cm.view.sel.from, curTo = cm.view.sel.to; setSelectionUser(cm, pos, pos); if (cm.view.draggingText) replaceRange(cm, "", curFrom, curTo); cm.replaceSelection(text); focusInput(cm); onFocus(cm); }); } } catch(e){} } } function clickInGutter(e) { var cm = this, display = cm.display; try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false; e_preventDefault(e); if (!hasHandler(cm, "gutterClick")) return true; var lineBox = display.lineDiv.getBoundingClientRect(); if (mY > lineBox.bottom) return true; mY -= lineBox.top - display.viewOffset; for (var i = 0; i < cm.options.gutters.length; ++i) { var g = display.gutters.childNodes[i]; if (g && g.getBoundingClientRect().right >= mX) { var line = lineAtHeight(cm.view.doc, mY); var gutter = cm.options.gutters[i]; signalLater(cm, cm, "gutterClick", cm, line, gutter, e); break; } } return true; } function onDragStart(cm, e) { var txt = cm.getSelection(); e.dataTransfer.setData("Text", txt); // Use dummy image instead of default browsers image. if (e.dataTransfer.setDragImage) e.dataTransfer.setDragImage(elt('img'), 0, 0); } function setScrollTop(cm, val) { if (Math.abs(cm.view.scrollTop - val) < 2) return; cm.view.scrollTop = val; if (!gecko) updateDisplay(cm, [], val); if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; if (gecko) updateDisplay(cm, []); } function setScrollLeft(cm, val) { if (Math.abs(cm.view.scrollLeft - val) < 2) return; cm.view.scrollLeft = val; if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; alignVertically(cm.display); } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelDX, wheelDY, wheelStartX, wheelStartY, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) wheelPixelsPerUnit = -.53; else if (gecko) wheelPixelsPerUnit = 15; else if (chrome) wheelPixelsPerUnit = -.7; else if (safari) wheelPixelsPerUnit = -1/3; function onScrollWheel(cm, e) { var dx = e.wheelDeltaX, dy = e.wheelDeltaY; if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; else if (dy == null) dy = e.wheelDelta; var scroll = cm.display.scroller; if (wheelPixelsPerUnit != null) { var pixels = dy * wheelPixelsPerUnit; var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight; if (pixels < 0) top = Math.max(0, top + pixels); else bot = Math.min(cm.view.doc.height, bot + pixels); updateDisplay(cm, [], {top: top, bottom: bot}); } if (wheelSamples < 20) { if (wheelStartX == null) { wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop; wheelDX = dx; wheelDY = dy; setTimeout(function() { var movedX = scroll.scrollLeft - wheelStartX; var movedY = scroll.scrollTop - wheelStartY; var sample = (movedY && wheelDY && movedY / wheelDY) || (movedX && wheelDX && movedX / wheelDX); wheelStartX = wheelStartY = null; if (!sample) return; wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); ++wheelSamples; }, 200); } else { wheelDX += dx; wheelDY += dy; } } } function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) return false; } var view = cm.view, prevShift = view.sel.shift; try { if (isReadOnly(cm)) view.suppressEdits = true; if (dropShift) view.sel.shift = null; bound(cm); } catch(e) { if (e != Pass) throw e; return false; } finally { view.sel.shift = prevShift; view.suppressEdits = false; } return true; } var maybeTransition; function handleKeyBinding(cm, e) { // Handle auto keymap transitions var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; clearTimeout(maybeTransition); if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { if (getKeyMap(cm.options.keyMap) == startMap) cm.options.keyMap = (next.call ? next.call(null, cm) : next); }, 50); var name = keyNames[e_prop(e, "keyCode")], handled = false; var flipCtrlCmd = opera && mac; if (name == null || e.altGraphKey) return false; if (e_prop(e, "altKey")) name = "Alt-" + name; if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name; if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name; var stopped = false; function stop() { stopped = true; } if (e_prop(e, "shiftKey")) { handled = lookupKey("Shift-" + name, cm.options.extraKeys, cm.options.keyMap, function(b) {return doHandleBinding(cm, b, true);}, stop) || lookupKey(name, cm.options.extraKeys, cm.options.keyMap, function(b) { if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b); }, stop); } else { handled = lookupKey(name, cm.options.extraKeys, cm.options.keyMap, function(b) { return doHandleBinding(cm, b); }, stop); } if (stopped) handled = false; if (handled) { e_preventDefault(e); restartBlink(cm); if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } } return handled; } function handleCharBinding(cm, e, ch) { var handled = lookupKey("'" + ch + "'", cm.options.extraKeys, cm.options.keyMap, function(b) { return doHandleBinding(cm, b, true); }); if (handled) { e_preventDefault(e); restartBlink(cm); } return handled; } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; if (!cm.view.focused) onFocus(cm); if (ie && e.keyCode == 27) { e.returnValue = false; } if (cm.display.pollingFast) { if (readInput(cm)) cm.display.pollingFast = false; } if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; var code = e_prop(e, "keyCode"); // IE does strange things with escape. setShift(cm.view, code == 16 || e_prop(e, "shiftKey")); // First give onKeyEvent option a chance to handle this. var handled = handleKeyBinding(cm, e); if (opera) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey")) cm.replaceSelection(""); } } function onKeyPress(e) { var cm = this; if (cm.display.pollingFast) readInput(cm); if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; var ch = String.fromCharCode(charCode == null ? keyCode : charCode); if (this.options.electricChars && this.view.mode.electricChars && this.options.smartIndent && !isReadOnly(this) && this.view.mode.electricChars.indexOf(ch) > -1) setTimeout(operation(cm, function() {indentLine(cm, cm.view.sel.to.line, "smart");}), 75); if (handleCharBinding(cm, e, ch)) return; fastPoll(cm); } function onFocus(cm) { if (cm.options.readOnly == "nocursor") return; if (!cm.view.focused) { signal(cm, "focus", cm); cm.view.focused = true; if (cm.display.scroller.className.search(/\bCodeMirror-focused\b/) == -1) cm.display.scroller.className += " CodeMirror-focused"; resetInput(cm, true); } slowPoll(cm); restartBlink(cm); } function onBlur(cm) { if (cm.view.focused) { signal(cm, "blur", cm); cm.view.focused = false; cm.display.scroller.className = cm.display.scroller.className.replace(" CodeMirror-focused", ""); } clearInterval(cm.display.blinker); setTimeout(function() {if (!cm.view.focused) cm.view.sel.shift = null;}, 150); } var detectingSelectAll; function onContextMenu(cm, e) { var display = cm.display, sel = cm.view.sel; var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || opera) return; // Opera is difficult. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) operation(cm, setSelection)(cm, pos, pos); var oldCSS = display.input.style.cssText; display.inputDiv.style.position = "absolute"; display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" + "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; focusInput(cm); resetInput(cm, true); // Adds "Select all" to context menu in FF if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; function rehide() { display.inputDiv.style.position = "relative"; display.input.style.cssText = oldCSS; if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; slowPoll(cm); // Try to detect the user choosing select-all if (display.input.selectionStart != null) { clearTimeout(detectingSelectAll); var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0; display.prevInput = " "; display.input.selectionStart = 1; display.input.selectionEnd = extval.length; detectingSelectAll = setTimeout(function poll(){ if (display.prevInput == " " && display.input.selectionStart == 0) operation(cm, commands.selectAll)(cm); else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); else resetInput(cm); }, 200); } } if (gecko) { e_stop(e); on(window, "mouseup", function mouseup() { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }); } else { setTimeout(rehide, 50); } } // UPDATING // Replace the range from from to to by the strings in newText. // Afterwards, set the selection to selFrom, selTo. function updateDoc(cm, from, to, newText, selUpdate) { // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && removeReadOnlyRanges(cm.view.doc, from, to); if (split) { for (var i = split.length - 1; i >= 1; --i) updateDocInner(cm, split[i].from, split[i].to, [""]); if (split.length) return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate); } else { return updateDocInner(cm, from, to, newText, selUpdate); } } function updateDocInner(cm, from, to, newText, selUpdate) { if (cm.view.suppressEdits) return; var view = cm.view, doc = view.doc, old = []; doc.iter(from.line, to.line + 1, function(line) { old.push(newHL(line.text, line.markedSpans)); }); if (view.history) { addChange(view.history, from.line, newText.length, old); while (view.history.done.length > cm.options.undoDepth) view.history.done.shift(); } var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText); return updateDocNoUndo(cm, from, to, lines, selUpdate); } function unredoHelper(cm, from, to, dir) { var doc = cm.view.doc, hist = cm.view.history; if (!from.length) return; var set = from.pop(), out = []; for (var i = set.length - 1; i >= 0; i -= 1) { hist.dirtyCounter += dir; var change = set[i]; var replaced = [], end = change.start + change.added; doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); }); out.push({start: change.start, added: change.old.length, old: replaced}); var pos = {line: change.start + change.old.length - 1, ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old)))}; updateDocNoUndo(cm, {line: change.start, ch: 0}, {line: end - 1, ch: getLine(doc, end-1).text.length}, change.old, pos); } to.push(out); } function updateDocNoUndo(cm, from, to, lines, selUpdate) { var view = cm.view, doc = view.doc, display = cm.display; if (view.suppressEdits) return; var nlines = to.line - from.line, firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); var recomputeMaxLength = false, checkWidthStart = from.line; if (!cm.options.lineWrapping) { for (var cur = firstLine, merged; merged = collapsedSpanAtStart(cur);) { checkWidthStart = merged.find().from.line; cur = getLine(doc, checkWidthStart); } doc.iter(checkWidthStart, to.line + 1, function(line) { if (lineLength(doc, line) == view.maxLineLength) { recomputeMaxLength = true; return true; } }); } var lastHL = lst(lines), th = textHeight(display); // First adjust the line structure if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. var added = [], prevLine = null; for (var i = 0, e = lines.length - 1; i < e; ++i) added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); updateLine(cm, lastLine, lastLine.text, hlSpans(lastHL)); if (nlines) doc.remove(from.line, nlines, cm); if (added.length) doc.insert(from.line, added); } else if (firstLine == lastLine) { if (lines.length == 1) { updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) + firstLine.text.slice(to.ch), hlSpans(lines[0])); } else { for (var added = [], i = 1, e = lines.length - 1; i < e; ++i) added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); added.push(makeLine(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL), th)); updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); doc.insert(from.line + 1, added); } } else if (lines.length == 1) { updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) + lastLine.text.slice(to.ch), hlSpans(lines[0])); doc.remove(from.line + 1, nlines, cm); } else { var added = []; updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); updateLine(cm, lastLine, hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL)); for (var i = 1, e = lines.length - 1; i < e; ++i) added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); if (nlines > 1) doc.remove(from.line + 1, nlines - 1, cm); doc.insert(from.line + 1, added); } if (cm.options.lineWrapping) { var perLine = Math.max(5, display.scroller.clientWidth / charWidth(display) - 3); doc.iter(from.line, from.line + lines.length, function(line) { if (line.height == 0) return; var guess = (Math.ceil(line.text.length / perLine) || 1) * th; if (guess != line.height) updateLineHeight(line, guess); }); } else { doc.iter(checkWidthStart, from.line + lines.length, function(line) { var len = lineLength(doc, line); if (len > view.maxLineLength) { view.maxLine = line; view.maxLineLength = len; view.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) cm.curOp.updateMaxLine = true; } // Adjust frontier, schedule worker view.frontier = Math.min(view.frontier, from.line); startWorker(cm, 400); var lendiff = lines.length - nlines - 1; // Remember that these lines changed, for updating the display regChange(cm, from.line, to.line + 1, lendiff); if (hasHandler(cm, "change")) { // Normalize lines to contain only strings, since that's what // the change event handler expects for (var i = 0; i < lines.length; ++i) if (typeof lines[i] != "string") lines[i] = lines[i].text; var changeObj = {from: from, to: to, text: lines}; if (cm.curOp.textChanged) { for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} cur.next = changeObj; } else cm.curOp.textChanged = changeObj; } // Update the selection var newSelFrom, newSelTo, end = {line: from.line + lines.length - 1, ch: hlText(lastHL).length + (lines.length == 1 ? from.ch : 0)}; if (typeof selUpdate == "object" && selUpdate.line != null) { newSelFrom = newSelTo = selUpdate; } else if (selUpdate == "end") { newSelFrom = newSelTo = end; } else if (selUpdate == "start") { newSelFrom = newSelTo = from; } else if (selUpdate == "around") { newSelFrom = from; newSelTo = end; } else { var adjustPos = function(pos) { if (posLess(pos, from)) return pos; if (!posLess(to, pos)) return end; var line = pos.line + lendiff; var ch = pos.ch; if (pos.line == to.line) ch += hlText(lastHL).length - (to.ch - (to.line == from.line ? from.ch : 0)); return {line: line, ch: ch}; }; newSelFrom = adjustPos(view.sel.from); newSelTo = adjustPos(view.sel.to); } setSelection(cm, newSelFrom, newSelTo, null, true); return end; } function replaceRange(cm, code, from, to) { if (!to) to = from; if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } code = splitLines(code); function adjustPos(pos) { if (posLess(pos, from)) return pos; if (!posLess(to, pos)) return end; var line = pos.line + code.length - (to.line - from.line) - 1; var ch = pos.ch; if (pos.line == to.line) ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0)); return {line: line, ch: ch}; } return updateDoc(cm, from, to, code); } // SELECTION function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} function copyPos(x) {return {line: x.line, ch: x.ch};} function clipLine(doc, n) {return Math.max(0, Math.min(n, doc.size-1));} function clipPos(doc, pos) { if (pos.line < 0) return {line: 0, ch: 0}; if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc, doc.size-1).text.length}; var ch = pos.ch, linelen = getLine(doc, pos.line).text.length; if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; else if (ch < 0) return {line: pos.line, ch: 0}; else return pos; } function isLine(doc, l) {return l >= 0 && l < doc.size;} function setShift(view, val) { if (val) view.sel.shift = view.sel.shift || selHead(view); else view.sel.shift = null; } function setSelectionUser(cm, from, to, bias) { var view = cm.view, sh = view.sel.shift; if (sh) { sh = clipPos(view.doc, sh); if (posLess(sh, from)) from = sh; else if (posLess(to, sh)) to = sh; } setSelection(cm, from, to, bias); cm.curOp.userSelChange = true; } // Update the selection. Last two args are only used by // updateDoc, since they have to be expressed in the line // numbers before the update. function setSelection(cm, from, to, bias, checkAtomic) { cm.curOp.updateInput = true; var sel = cm.view.sel, doc = cm.view.doc; cm.view.goalColumn = null; if (!checkAtomic && posEq(sel.from, from) && posEq(sel.to, to)) return; if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} // Skip over atomic spans. if (checkAtomic || !posEq(from, sel.from)) from = skipAtomic(cm, from, bias, checkAtomic != "push"); if (checkAtomic || !posEq(to, sel.to)) to = skipAtomic(cm, to, bias, checkAtomic != "push"); if (posEq(from, to)) sel.inverted = false; else if (posEq(from, sel.to)) sel.inverted = false; else if (posEq(to, sel.from)) sel.inverted = true; if (cm.options.autoClearEmptyLines && posEq(sel.from, sel.to)) { var head = selHead(cm.view); if (head.line != sel.from.line && sel.from.line < doc.size) { var oldLine = getLine(doc, sel.from.line); if (/^\s+$/.test(oldLine.text)) setTimeout(operation(cm, function() { if (oldLine.parent && /^\s+$/.test(oldLine.text)) { var no = lineNo(oldLine); replaceRange(cm, "", {line: no, ch: 0}, {line: no, ch: oldLine.text.length}); } }, 10)); } } sel.from = from; sel.to = to; cm.curOp.selectionChanged = true; } function reCheckSelection(cm) { setSelection(cm, cm.view.sel.from, cm.view.sel.to, null, "push"); } function skipAtomic(cm, pos, bias, mayClear) { var doc = cm.view.doc, flipped = false, curPos = pos; var dir = bias || 1; cm.view.cantEdit = false; search: for (;;) { var line = getLine(doc, curPos.line), toClear; if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var sp = line.markedSpans[i], m = sp.marker; if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { if (mayClear && m.clearOnEnter) { (toClear || (toClear = [])).push(m); continue; } else if (!m.atomic) continue; var newPos = m.find()[dir < 0 ? "from" : "to"]; if (posEq(newPos, curPos)) { newPos.ch += dir; if (newPos.ch < 0) { if (newPos.line) newPos = clipPos(doc, {line: newPos.line - 1}); else newPos = null; } else if (newPos.ch > line.text.length) { if (newPos.line < doc.size - 1) newPos = {line: newPos.line + 1, ch: 0}; else newPos = null; } if (!newPos) { if (flipped) { // Driven in a corner -- no valid cursor position found at all // -- try again *with* clearing, if we didn't already if (!mayClear) return skipAtomic(cm, pos, bias, true); // Otherwise, turn off editing until further notice, and return the start of the doc cm.view.cantEdit = true; return {line: 0, ch: 0}; } flipped = true; newPos = pos; dir = -dir; } } curPos = newPos; continue search; } } if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear(); } return curPos; } } // SCROLLING function scrollCursorIntoView(cm) { var view = cm.view, coords = cursorCoords(cm, selHead(view)); scrollIntoView(cm.display, coords.left, coords.top, coords.left, coords.bottom); if (!view.focused) return; var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; if (coords.top + box.top < 0) doScroll = true; else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; if (doScroll != null && !phantom) { var hidden = display.cursor.style.display == "none"; if (hidden) { display.cursor.style.display = ""; display.cursor.style.left = coords.left + "px"; display.cursor.style.top = (coords.top - display.viewOffset) + "px"; } display.cursor.scrollIntoView(doScroll); if (hidden) display.cursor.style.display = "none"; } } function scrollIntoView(display, x1, y1, x2, y2) { var scrollPos = calculateScrollPos(display, x1, y1, x2, y2); if (scrollPos.scrollLeft != null) {display.scrollbarH.scrollLeft = display.scroller.scrollLeft = scrollPos.scrollLeft;} if (scrollPos.scrollTop != null) {display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos.scrollTop;} } function calculateScrollPos(display, x1, y1, x2, y2) { var pt = paddingTop(display); y1 += pt; y2 += pt; var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; var docBottom = display.scroller.scrollHeight - scrollerCutOff; var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10; if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2 - screen); var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft; x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; var gutterw = display.gutters.offsetWidth; var atLeft = x1 < gutterw + 10; if (x1 < screenleft + gutterw || atLeft) { if (atLeft) x1 = 0; result.scrollLeft = Math.max(0, x1 - 10 - gutterw); } else if (x2 > screenw + screenleft - 3) { result.scrollLeft = x2 + 10 - screenw; } return result; } // API UTILITIES function indentLine(cm, n, how) { var doc = cm.view.doc; if (!how) how = "add"; if (how == "smart") { if (!cm.view.mode.indent) how = "prev"; else var state = getStateBefore(cm, n); } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (how == "smart") { indentation = cm.view.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass) how = "prev"; } if (how == "prev") { if (n) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); else indentation = 0; } else if (how == "add") indentation = curSpace + cm.options.indentUnit; else if (how == "subtract") indentation = curSpace - cm.options.indentUnit; indentation = Math.max(0, indentation); var diff = indentation - curSpace; var indentString = "", pos = 0; if (cm.options.indentWithTabs) for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} if (pos < indentation) indentString += spaceStr(indentation - pos); if (indentString != curSpaceString) replaceRange(cm, indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}); line.stateAfter = null; } function changeLine(cm, handle, op) { var no = handle, line = handle, doc = cm.view.doc; if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); else no = lineNo(handle); if (no == null) return null; if (op(line, no)) regChange(cm, no, no + 1); else return null; return line; } function findPosH(cm, dir, unit, visually) { var doc = cm.view.doc, end = selHead(cm.view), line = end.line, ch = end.ch; var lineObj = getLine(doc, line); function findNextLine() { var l = line + dir; if (l < 0 || l == doc.size) return false; line = l; return lineObj = getLine(doc, l); } function moveOnce(boundToLine) { var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); if (next == null) { if (!boundToLine && findNextLine()) { if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); else ch = dir < 0 ? lineObj.text.length : 0; } else return false; } else ch = next; return true; } if (unit == "char") moveOnce(); else if (unit == "column") moveOnce(true); else if (unit == "word") { var sawWord = false; for (;;) { if (dir < 0) if (!moveOnce()) break; if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} if (dir > 0) if (!moveOnce()) break; } } return skipAtomic(cm, {line: line, ch: ch}, dir, true); } function findWordAt(line, pos) { var start = pos.ch, end = pos.ch; if (line) { if (pos.after === false || end == line.length) --start; else ++end; var startChar = line.charAt(start); var check = isWordChar(startChar) ? isWordChar : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; while (start > 0 && check(line.charAt(start - 1))) --start; while (end < line.length && check(line.charAt(end))) ++end; } return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}}; } function selectLine(cm, line) { setSelectionUser(cm, {line: line, ch: 0}, clipPos(cm.view.doc, {line: line + 1, ch: 0})); } // PROTOTYPE // The publicly visible API. Note that operation(null, f) means // 'wrap f in an operation, performed on its `this` parameter' CodeMirror.prototype = { getValue: function(lineSep) { var text = [], doc = this.view.doc; doc.iter(0, doc.size, function(line) { text.push(line.text); }); return text.join(lineSep || "\n"); }, setValue: operation(null, function(code) { var doc = this.view.doc, top = {line: 0, ch: 0}, lastLen = getLine(doc, doc.size-1).text.length; updateDocInner(this, top, {line: doc.size - 1, ch: lastLen}, splitLines(code), top, top); }), getSelection: function(lineSep) { return this.getRange(this.view.sel.from, this.view.sel.to, lineSep); }, replaceSelection: operation(null, function(code, collapse) { var sel = this.view.sel; updateDoc(this, sel.from, sel.to, splitLines(code), collapse || "around"); }), focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);}, setOption: function(option, value) { var options = this.options, old = options[option]; if (options[option] == value && option != "mode") return; options[option] = value; if (optionHandlers.hasOwnProperty(option)) operation(this, optionHandlers[option])(this, value, old); }, getOption: function(option) {return this.options[option];}, getMode: function() {return this.view.mode;}, undo: operation(null, function() { var hist = this.view.history; unredoHelper(this, hist.done, hist.undone, -1); }), redo: operation(null, function() { var hist = this.view.history; unredoHelper(this, hist.undone, hist.done, 1); }), indentLine: operation(null, function(n, dir) { if (typeof dir != "string") { if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; else dir = dir ? "add" : "subtract"; } if (isLine(this.view.doc, n)) indentLine(this, n, dir); }), indentSelection: operation(null, function(how) { var sel = this.view.sel; if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how); var e = sel.to.line - (sel.to.ch ? 0 : 1); for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); }), historySize: function() { var hist = this.view.history; return {undo: hist.done.length, redo: hist.undone.length}; }, clearHistory: function() {this.view.history = makeHistory();}, markClean: function() { this.view.history.dirtyCounter = 0; this.view.history.closed = true; }, isClean: function () {return this.view.history.dirtyCounter == 0;}, getHistory: function() { var hist = this.view.history; function cp(arr) { for (var i = 0, nw = [], nwelt; i < arr.length; ++i) { nw.push(nwelt = []); for (var j = 0, elt = arr[i]; j < elt.length; ++j) { var old = [], cur = elt[j]; nwelt.push({start: cur.start, added: cur.added, old: old}); for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k])); } } return nw; } return {done: cp(hist.done), undone: cp(hist.undone)}; }, setHistory: function(histData) { var hist = this.view.history = makeHistory(); hist.done = histData.done; hist.undone = histData.undone; }, getTokenAt: function(pos) { var doc = this.view.doc; pos = clipPos(doc, pos); return getTokenAt(this, getLine(doc, pos.line), getStateBefore(this, pos.line), pos.ch); }, getStateAfter: function(line) { var doc = this.view.doc; line = clipLine(doc, line == null ? doc.size - 1: line); return getStateBefore(this, line + 1); }, cursorCoords: function(start, mode) { var pos, sel = this.view.sel; if (start == null) start = sel.inverted; if (typeof start == "object") pos = clipPos(this.view.doc, start); else pos = start ? sel.from : sel.to; return cursorCoords(this, pos, mode || "page"); }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.view.doc, pos), mode || "page"); }, coordsChar: function(coords) { var off = this.display.lineSpace.getBoundingClientRect(); return coordsChar(this, coords.left - off.left, coords.top - off.top); }, defaultTextHeight: function() { return textHeight(this.display); }, markText: operation(null, function(from, to, options) { return markText(this, clipPos(this.view.doc, from), clipPos(this.view.doc, to), options, "range"); }), setBookmark: operation(null, function(pos, widget) { pos = clipPos(this.view.doc, pos); return markText(this, pos, pos, widget ? {replacedWith: widget} : {}, "bookmark"); }), findMarksAt: function(pos) { var doc = this.view.doc; pos = clipPos(doc, pos); var markers = [], spans = getLine(doc, pos.line).markedSpans; if (spans) for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) markers.push(span.marker); } return markers; }, setGutterMarker: operation(null, function(line, gutterID, value) { return changeLine(this, line, function(line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) line.gutterMarkers = null; return true; }); }), clearGutter: operation(null, function(gutterID) { var i = 0, cm = this, doc = cm.view.doc; doc.iter(0, doc.size, function(line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { line.gutterMarkers[gutterID] = null; regChange(cm, i, i + 1); if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; } ++i; }); }), addLineClass: operation(null, function(handle, where, cls) { return changeLine(this, handle, function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; if (!line[prop]) line[prop] = cls; else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false; else line[prop] += " " + cls; return true; }); }), removeLineClass: operation(null, function(handle, where, cls) { return changeLine(this, handle, function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; var cur = line[prop]; if (!cur) return false; else if (cls == null) line[prop] = null; else { var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), ""); if (upd == cur) return false; line[prop] = upd || null; } return true; }); }), addLineWidget: operation(null, function addLineWidget(handle, node, options) { var widget = options || {}; widget.node = node; if (widget.noHScroll) this.display.alignWidgets = true; changeLine(this, handle, function(line) { (line.widgets || (line.widgets = [])).push(widget); widget.line = line; return true; }); return widget; }), removeLineWidget: operation(null, function(widget) { var ws = widget.line.widgets, no = lineNo(widget.line); if (no == null) return; for (var i = 0; i < ws.length; ++i) if (ws[i] == widget) ws.splice(i--, 1); regChange(this, no, no + 1); }), lineInfo: function(line) { if (typeof line == "number") { if (!isLine(this.view.doc, line)) return null; var n = line; line = getLine(this.view.doc, line); if (!line) return null; } else { var n = lineNo(line); if (n == null) return null; } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets}; }, getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};}, addWidget: function(pos, node, scroll, vert, horiz) { var display = this.display; pos = cursorCoords(this, clipPos(this.view.doc, pos)); var top = pos.top, left = pos.left; node.style.position = "absolute"; display.sizer.appendChild(node); if (vert == "over") top = pos.top; else if (vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.view.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); if (pos.bottom + node.offsetHeight > vspace && pos.top > node.offsetHeight) top = pos.top - node.offsetHeight; if (left + node.offsetWidth > hspace) left = hspace - node.offsetWidth; } node.style.top = (top + paddingTop(display)) + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") left = 0; else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; node.style.left = left + "px"; } if (scroll) scrollIntoView(display, left, top, left + node.offsetWidth, top + node.offsetHeight); }, lineCount: function() {return this.view.doc.size;}, clipPos: function(pos) {return clipPos(this.view.doc, pos);}, getCursor: function(start) { var sel = this.view.sel; if (start == null) start = sel.inverted; return copyPos(start ? sel.from : sel.to); }, somethingSelected: function() {return !posEq(this.view.sel.from, this.view.sel.to);}, setCursor: operation(null, function(line, ch, user) { var pos = typeof line == "number" ? {line: line, ch: ch || 0} : line; (user ? setSelectionUser : setSelection)(this, pos, pos); }), setSelection: operation(null, function(from, to, user) { var doc = this.view.doc; (user ? setSelectionUser : setSelection)(this, clipPos(doc, from), clipPos(doc, to || from)); }), getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, getLineHandle: function(line) { var doc = this.view.doc; if (isLine(doc, line)) return getLine(doc, line); }, getLineNumber: function(line) {return lineNo(line);}, setLine: operation(null, function(line, text) { if (isLine(this.view.doc, line)) replaceRange(this, text, {line: line, ch: 0}, {line: line, ch: getLine(this.view.doc, line).text.length}); }), removeLine: operation(null, function(line) { if (isLine(this.view.doc, line)) replaceRange(this, "", {line: line, ch: 0}, clipPos(this.view.doc, {line: line+1, ch: 0})); }), replaceRange: operation(null, function(code, from, to) { var doc = this.view.doc; from = clipPos(doc, from); to = to ? clipPos(doc, to) : from; return replaceRange(this, code, from, to); }), getRange: function(from, to, lineSep) { var doc = this.view.doc; from = clipPos(doc, from); to = clipPos(doc, to); var l1 = from.line, l2 = to.line; if (l1 == l2) return getLine(doc, l1).text.slice(from.ch, to.ch); var code = [getLine(doc, l1).text.slice(from.ch)]; doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); code.push(getLine(doc, l2).text.slice(0, to.ch)); return code.join(lineSep || "\n"); }, triggerOnKeyDown: operation(null, onKeyDown), execCommand: function(cmd) {return commands[cmd](this);}, // Stuff used by commands, probably not much use to outside code. moveH: operation(null, function(dir, unit) { var sel = this.view.sel, pos = dir < 0 ? sel.from : sel.to; if (sel.shift || posEq(sel.from, sel.to)) pos = findPosH(this, dir, unit, true); setSelectionUser(this, pos, pos, dir); }), deleteH: operation(null, function(dir, unit) { var sel = this.view.sel; if (!posEq(sel.from, sel.to)) replaceRange(this, "", sel.from, sel.to); else replaceRange(this, "", sel.from, findPosH(this, dir, unit, false)); this.curOp.userSelChange = true; }), moveV: operation(null, function(dir, unit) { var view = this.view, doc = view.doc, display = this.display; var dist = 0, cur = selHead(view), pos = cursorCoords(this, cur, "div"); var x = pos.left, y; if (view.goalColumn != null) x = view.goalColumn; if (unit == "page") { var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); y = pos.top + dir * pageSize; } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } do { var target = coordsChar(this, x, y); y += dir * 5; } while (target.outside && (dir < 0 ? y > 0 : y < doc.height)); if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top; setSelectionUser(this, target, target, dir); view.goalColumn = x; }), toggleOverwrite: function() { if (this.view.overwrite = !this.view.overwrite) this.display.cursor.className += " CodeMirror-overwrite"; else this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); }, posFromIndex: function(off) { var lineNo = 0, ch, doc = this.view.doc; doc.iter(0, doc.size, function(line) { var sz = line.text.length + 1; if (sz > off) { ch = off; return true; } off -= sz; ++lineNo; }); return clipPos(doc, {line: lineNo, ch: ch}); }, indexFromPos: function (coords) { if (coords.line < 0 || coords.ch < 0) return 0; var index = coords.ch; this.view.doc.iter(0, coords.line, function (line) { index += line.text.length + 1; }); return index; }, scrollTo: function(x, y) { if (x != null) this.display.scrollbarH.scrollLeft = this.display.scroller.scrollLeft = x; if (y != null) this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = y; updateDisplay(this, []); }, getScrollInfo: function() { var scroller = this.display.scroller, co = scrollerCutOff; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; }, scrollIntoView: function(pos) { pos = pos ? clipPos(this.view.doc, pos) : selHead(this.view); var coords = cursorCoords(this, pos); scrollIntoView(this.display, coords.left, coords.top, coords.left, coords.bottom); }, setSize: function(width, height) { function interpret(val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; } if (width != null) this.display.wrapper.style.width = interpret(width); if (height != null) this.display.wrapper.style.height = interpret(height); this.refresh(); }, on: function(type, f) {on(this, type, f);}, off: function(type, f) {off(this, type, f);}, operation: function(f){return operation(this, f)();}, compoundChange: function(f){return compoundChange(this, f);}, refresh: function(){ updateDisplay(this, true, this.view.scrollTop); if (this.display.scrollbarV.scrollHeight > this.view.scrollTop) this.display.scrollbarV.scrollTop = this.view.scrollTop; }, getInputField: function(){return this.display.input;}, getWrapperElement: function(){return this.display.wrapper;}, getScrollerElement: function(){return this.display.scroller;}, getGutterElement: function(){return this.display.gutters;} }; // OPTION DEFAULTS var optionHandlers = CodeMirror.optionHandlers = {}; // The default configuration options. var defaults = CodeMirror.defaults = {}; function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt; if (handle) optionHandlers[name] = notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; } var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", function(cm, val) {cm.setValue(val);}, true); option("mode", null, loadMode, true); option("indentUnit", 2, loadMode, true); option("indentWithTabs", false); option("smartIndent", true); option("tabSize", 4, function(cm) {loadMode(cm); updateDisplay(cm, true);}, true); option("electricChars", true); option("autoClearEmptyLines", false); option("theme", "default", function(cm, val, old) { themeChanged(cm); if (old != Init) guttersChanged(cm); }); option("keyMap", "default", keyMapChanged); option("extraKeys", null); option("onKeyEvent", null); option("onDragEvent", null); option("lineWrapping", false, wrappingChanged); option("gutters", [], function(cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("lineNumbers", false, function(cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("firstLineNumber", 1, guttersChanged, false); option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, false); option("readOnly", false, function(cm, val) { if (val == "nocursor") {onBlur(cm); cm.display.input.blur();} else if (!val) resetInput(cm, true); }); option("dragDrop", true); option("cursorBlinkRate", 530); option("cursorHeight", 1); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true); option("pollInterval", 100); option("undoDepth", 40); option("viewportMargin", 10, function(cm){cm.refresh();}, true); option("tabindex", null, function(cm, val) { cm.display.input.tabIndex = val || ""; }); option("autofocus", null); // MODE DEFINITION AND QUERYING // Known modes, by name and by MIME var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; CodeMirror.defineMode = function(name, mode) { if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; if (arguments.length > 2) { mode.dependencies = []; for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); } modes[name] = mode; }; CodeMirror.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; CodeMirror.resolveMode = function(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) spec = mimeModes[spec]; else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) return CodeMirror.resolveMode("application/xml"); if (typeof spec == "string") return {name: spec}; else return spec || {name: "null"}; }; CodeMirror.getMode = function(options, spec) { var spec = CodeMirror.resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) return CodeMirror.getMode(options, "text/plain"); var modeObj = mfactory(options, spec); if (modeExtensions.hasOwnProperty(spec.name)) { var exts = modeExtensions[spec.name]; for (var prop in exts) if (exts.hasOwnProperty(prop)) modeObj[prop] = exts[prop]; } modeObj.name = spec.name; return modeObj; }; CodeMirror.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); CodeMirror.defineMIME("text/plain", "null"); var modeExtensions = CodeMirror.modeExtensions = {}; CodeMirror.extendMode = function(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); for (var prop in properties) if (properties.hasOwnProperty(prop)) exts[prop] = properties[prop]; }; // EXTENSIONS CodeMirror.defineExtension = function(name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineOption = option; var initHooks = []; CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; // MODE STATE HANDLING // Utility functions for working with state. Exported because modes // sometimes need to do this. function copyState(mode, state) { if (state === true) return state; if (mode.copyState) return mode.copyState(state); var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) val = val.concat([]); nstate[n] = val; } return nstate; } CodeMirror.copyState = copyState; function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; } CodeMirror.startState = startState; CodeMirror.innerMode = function(mode, state) { while (mode.innerMode) { var info = mode.innerMode(state); state = info.state; mode = info.mode; } return info || {mode: mode, state: state}; }; // STANDARD COMMANDS var commands = CodeMirror.commands = { selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, killLine: function(cm) { var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0}); else cm.replaceRange("", from, sel ? to : {line: from.line}); }, deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});}, undo: function(cm) {cm.undo();}, redo: function(cm) {cm.redo();}, goDocStart: function(cm) {cm.setCursor(0, 0, true);}, goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);}, goLineStart: function(cm) { cm.setCursor(lineStart(cm, cm.getCursor().line), null, true); }, goLineStartSmart: function(cm) { var cur = cm.getCursor(), start = lineStart(cm, cur.line); var line = cm.getLineHandle(start.line); var order = getOrder(line); if (!order || order[0].level == 0) { var firstNonWS = Math.max(0, line.text.search(/\S/)); var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; cm.setCursor(start.line, inWS ? 0 : firstNonWS, true); } else cm.setCursor(start, null, true); }, goLineEnd: function(cm) { cm.setCursor(lineEnd(cm, cm.getCursor().line), null, true); }, goLineUp: function(cm) {cm.moveV(-1, "line");}, goLineDown: function(cm) {cm.moveV(1, "line");}, goPageUp: function(cm) {cm.moveV(-1, "page");}, goPageDown: function(cm) {cm.moveV(1, "page");}, goCharLeft: function(cm) {cm.moveH(-1, "char");}, goCharRight: function(cm) {cm.moveH(1, "char");}, goColumnLeft: function(cm) {cm.moveH(-1, "column");}, goColumnRight: function(cm) {cm.moveH(1, "column");}, goWordLeft: function(cm) {cm.moveH(-1, "word");}, goWordRight: function(cm) {cm.moveH(1, "word");}, delCharBefore: function(cm) {cm.deleteH(-1, "char");}, delCharAfter: function(cm) {cm.deleteH(1, "char");}, delWordBefore: function(cm) {cm.deleteH(-1, "word");}, delWordAfter: function(cm) {cm.deleteH(1, "word");}, indentAuto: function(cm) {cm.indentSelection("smart");}, indentMore: function(cm) {cm.indentSelection("add");}, indentLess: function(cm) {cm.indentSelection("subtract");}, insertTab: function(cm) {cm.replaceSelection("\t", "end");}, defaultTab: function(cm) { if (cm.somethingSelected()) cm.indentSelection("add"); else cm.replaceSelection("\t", "end"); }, transposeChars: function(cm) { var cur = cm.getCursor(), line = cm.getLine(cur.line); if (cur.ch > 0 && cur.ch < line.length - 1) cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1}); }, newlineAndIndent: function(cm) { cm.replaceSelection("\n", "end"); cm.indentLine(cm.getCursor().line); }, toggleOverwrite: function(cm) {cm.toggleOverwrite();} }; // STANDARD KEYMAPS var keyMap = CodeMirror.keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" }; // Note that the save and find-related commands aren't defined by // default. Unknown commands are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", fallthrough: "basic" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft", "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore", "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", fallthrough: ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" }; // KEYMAP DISPATCH function getKeyMap(val) { if (typeof val == "string") return keyMap[val]; else return val; } function lookupKey(name, extraMap, map, handle, stop) { function lookup(map) { map = getKeyMap(map); var found = map[name]; if (found === false) { if (stop) stop(); return true; } if (found != null && handle(found)) return true; if (map.nofallthrough) { if (stop) stop(); return true; } var fallthrough = map.fallthrough; if (fallthrough == null) return false; if (Object.prototype.toString.call(fallthrough) != "[object Array]") return lookup(fallthrough); for (var i = 0, e = fallthrough.length; i < e; ++i) { if (lookup(fallthrough[i])) return true; } return false; } if (extraMap && lookup(extraMap)) return true; return lookup(map); } function isModifierKey(event) { var name = keyNames[e_prop(event, "keyCode")]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; } CodeMirror.isModifierKey = isModifierKey; // FROMTEXTAREA CodeMirror.fromTextArea = function(textarea, options) { if (!options) options = {}; options.value = textarea.value; if (!options.tabindex && textarea.tabindex) options.tabindex = textarea.tabindex; // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { var hasFocus = document.body; // doc.activeElement occasionally throws on IE try { hasFocus = document.activeElement; } catch(e) {} options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} if (textarea.form) { // Deplorable hack to make the submit method do the right thing. on(textarea.form, "submit", save); if (typeof textarea.form.submit == "function") { var realSubmit = textarea.form.submit; textarea.form.submit = function wrappedSubmit() { save(); textarea.form.submit = realSubmit; textarea.form.submit(); textarea.form.submit = wrappedSubmit; }; } } textarea.style.display = "none"; var cm = CodeMirror(function(node) { textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); cm.save = save; cm.getTextArea = function() { return textarea; }; cm.toTextArea = function() { save(); textarea.parentNode.removeChild(cm.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { off(textarea.form, "submit", save); if (typeof textarea.form.submit == "function") textarea.form.submit = realSubmit; } }; return cm; }; // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. // The character stream used by a mode's parser. function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos) || undefined;}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() {return countColumn(this.string, this.start, this.tabSize);}, indentation: function() {return countColumn(this.string, null, this.tabSize);}, match: function(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { if (consume !== false) this.pos += pattern.length; return true; } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) return null; if (match && consume !== false) this.pos += match[0].length; return match; } }, current: function(){return this.string.slice(this.start, this.pos);} }; CodeMirror.StringStream = StringStream; // TEXTMARKERS function TextMarker(cm, type) { this.lines = []; this.type = type; this.cm = cm; } TextMarker.prototype.clear = function() { if (this.explicitlyCleared) return; startOperation(this.cm); var min = null, max = null; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.to != null) max = lineNo(line); line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from != null) min = lineNo(line); else if (this.collapsed && !lineIsHidden(line)) updateLineHeight(line, textHeight(this.cm.display)); } if (min != null) regChange(this.cm, min, max + 1); this.lines.length = 0; this.explicitlyCleared = true; if (this.collapsed && this.cm.view.cantEdit) { this.cm.view.cantEdit = false; reCheckSelection(this.cm); } endOperation(this.cm); signalLater(this.cm, this, "clear"); }; TextMarker.prototype.find = function() { var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.from != null || span.to != null) { var found = lineNo(line); if (span.from != null) from = {line: found, ch: span.from}; if (span.to != null) to = {line: found, ch: span.to}; } } if (this.type == "bookmark") return from; return from && {from: from, to: to}; }; function markText(cm, from, to, options, type) { var doc = cm.view.doc; var marker = new TextMarker(cm, type); if (type == "range" && !posLess(from, to)) return marker; if (options) for (var opt in options) if (options.hasOwnProperty(opt)) marker[opt] = options[opt]; if (marker.replacedWith) { marker.collapsed = true; marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); } if (marker.collapsed) sawCollapsedSpans = true; var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd; doc.iter(curLine, to.line + 1, function(line) { var span = {from: null, to: null, marker: marker}; size += line.text.length; if (curLine == from.line) {span.from = from.ch; size -= from.ch;} if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;} if (marker.collapsed) { if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch); if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch); else updateLineHeight(line, 0); } addMarkedSpan(line, span); if (marker.collapsed && curLine == from.line && lineIsHidden(line)) updateLineHeight(line, 0); ++curLine; }); if (marker.readOnly) { sawReadOnlySpans = true; if (cm.view.history.done.length || cm.view.history.undone.length) cm.clearHistory(); } if (marker.collapsed) { if (collapsedAtStart != collapsedAtEnd) throw new Error("Inserting collapsed marker overlapping an existing one"); marker.size = size; marker.atomic = true; } if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed) regChange(cm, from.line, to.line + 1); if (marker.atomic) reCheckSelection(cm); return marker; } // TEXTMARKER SPANS function getMarkedSpanFor(spans, marker) { if (spans) for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) return span; } } function removeMarkedSpan(spans, span) { for (var r, i = 0; i < spans.length; ++i) if (spans[i] != span) (r || (r = [])).push(spans[i]); return r; } function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; span.marker.lines.push(line); } function markedSpansBefore(old, startCh) { if (old) for (var i = 0, nw; i < old.length; ++i) { var span = old[i], marker = span.marker; var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); if (startsBefore || marker.type == "bookmark" && span.from == startCh) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); (nw || (nw = [])).push({from: span.from, to: endsAfter ? null : span.to, marker: marker}); } } return nw; } function markedSpansAfter(old, startCh, endCh) { if (old) for (var i = 0, nw; i < old.length; ++i) { var span = old[i], marker = span.marker; var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); if (endsAfter || marker.type == "bookmark" && span.from == endCh && span.from != startCh) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, to: span.to == null ? null : span.to - endCh, marker: marker}); } } return nw; } function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) { if (!oldFirst && !oldLast) return newText; // Get the spans that 'stick out' on both sides var first = markedSpansBefore(oldFirst, startCh); var last = markedSpansAfter(oldLast, startCh, endCh); // Next, merge those two ends var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0); if (first) { // Fix up .to properties of first for (var i = 0; i < first.length; ++i) { var span = first[i]; if (span.to == null) { var found = getMarkedSpanFor(last, span.marker); if (!found) span.to = startCh; else if (sameLine) span.to = found.to == null ? null : found.to + offset; } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (var i = 0; i < last.length; ++i) { var span = last[i]; if (span.to != null) span.to += offset; if (span.from == null) { var found = getMarkedSpanFor(first, span.marker); if (!found) { span.from = offset; if (sameLine) (first || (first = [])).push(span); } } else { span.from += offset; if (sameLine) (first || (first = [])).push(span); } } } var newMarkers = [newHL(newText[0], first)]; if (!sameLine) { // Fill gap with whole-line-spans var gap = newText.length - 2, gapMarkers; if (gap > 0 && first) for (var i = 0; i < first.length; ++i) if (first[i].to == null) (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); for (var i = 0; i < gap; ++i) newMarkers.push(newHL(newText[i+1], gapMarkers)); newMarkers.push(newHL(lst(newText), last)); } return newMarkers; } function removeReadOnlyRanges(doc, from, to) { var markers = null; doc.iter(from.line, to.line + 1, function(line) { if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { var mark = line.markedSpans[i].marker; if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) (markers || (markers = [])).push(mark); } }); if (!markers) return null; var parts = [{from: from, to: to}]; for (var i = 0; i < markers.length; ++i) { var m = markers[i].find(); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (!posLess(m.from, p.to) || posLess(m.to, p.from)) continue; var newParts = [j, 1]; if (posLess(p.from, m.from)) newParts.push({from: p.from, to: m.from}); if (posLess(m.to, p.to)) newParts.push({from: m.to, to: p.to}); parts.splice.apply(parts, newParts); j += newParts.length - 1; } } return parts; } function collapsedSpanAt(line, ch) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) continue; if ((sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || found.width < sp.marker.width)) found = sp.marker; } return found; } function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); } function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); } function lineIsHidden(line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) continue; if (sp.from == null) return true; if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(line, sp)) return true; } } window.lineIsHidden = lineIsHidden; function lineIsHiddenInner(line, span) { if (span.to == null || span.marker.inclusiveRight && span.to == line.text.length) return true; for (var sp, i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && sp.from == span.to && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(line, sp)) return true; } } // hl stands for history-line, a data structure that can be either a // string (line without markers) or a {text, markedSpans} object. function hlText(val) { return typeof val == "string" ? val : val.text; } function hlSpans(val) { if (typeof val == "string") return null; var spans = val.markedSpans, out = null; for (var i = 0; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } else if (out) out.push(spans[i]); } return !out ? spans : out.length ? out : null; } function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; } function detachMarkedSpans(line) { var spans = line.markedSpans; if (!spans) return; for (var i = 0; i < spans.length; ++i) { var lines = spans[i].marker.lines; var ix = indexOf(lines, line); lines.splice(ix, 1); } line.markedSpans = null; } function attachMarkedSpans(line, spans) { if (!spans) return; for (var i = 0; i < spans.length; ++i) var marker = spans[i].marker.lines.push(line); line.markedSpans = spans; } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). function makeLine(text, markedSpans, height) { var line = {text: text, height: height}; attachMarkedSpans(line, markedSpans); if (markedSpans && collapsedSpanAtStart(line)) line.height = 0; return line; } function updateLine(cm, line, text, markedSpans) { line.text = text; line.stateAfter = line.styles = null; if (line.order != null) line.order = null; detachMarkedSpans(line); attachMarkedSpans(line, markedSpans); var hidden = collapsedSpanAtStart(line); if (hidden) line.height = 0; else if (!line.height) line.height = textHeight(cm.display); signalLater(cm, line, "change"); } function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } // Run the given mode's parser over a line, update the styles // array, which contains alternating fragments of text and CSS // classes. function highlightLine(cm, line, state) { var mode = cm.view.mode, flattenSpans = cm.options.flattenSpans; var changed = !line.styles, pos = 0, curText = "", curStyle = null; var stream = new StringStream(line.text, cm.options.tabSize), st = line.styles || (line.styles = []); if (line.text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { var style = mode.token(stream, state), substr = stream.current(); stream.start = stream.pos; if (!flattenSpans || curStyle != style) { if (curText) { changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1]; st[pos++] = curText; st[pos++] = curStyle; } curText = substr; curStyle = style; } else curText = curText + substr; // Give up when line is ridiculously long if (stream.pos > 5000) break; } if (curText) { changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1]; st[pos++] = curText; st[pos++] = curStyle; } if (stream.pos > 5000) { st[pos++] = line.text.slice(stream.pos); st[pos++] = null; } if (pos != st.length) { st.length = pos; changed = true; } return changed; } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. function processLine(cm, line, state) { var mode = cm.view.mode; var stream = new StringStream(line.text, cm.options.tabSize); if (line.text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol() && stream.pos <= 5000) { mode.token(stream, state); stream.start = stream.pos; } } // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). function getTokenAt(cm, line, state, ch) { var mode = cm.view.mode; var txt = line.text, stream = new StringStream(txt, cm.options.tabSize); while (stream.pos < ch && !stream.eol()) { stream.start = stream.pos; var style = mode.token(stream, state); } return {start: stream.start, end: stream.pos, string: stream.current(), className: style || null, state: state}; } var styleToClassCache = {}; function styleToClass(style) { if (!style) return null; return styleToClassCache[style] || (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); } function lineContent(cm, realLine, measure) { var merged, line = realLine, lineBefore, sawBefore; while (merged = collapsedSpanAtStart(line)) { line = getLine(cm.view.doc, merged.find().from.line); if (!lineBefore) lineBefore = line; } var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure, measure: null, addedOne: false, cm: cm}; if (line.textClass) builder.pre.className = line.textClass; do { if (!line.styles) highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); builder.measure = line == realLine && measure; builder.pos = 0; builder.addToken = builder.measure ? buildTokenMeasure : buildToken; if (measure && sawBefore && line != realLine && !builder.addedOne) { measure[0] = builder.pre.appendChild(elt("span", "\u200b")); builder.addedOne = true; } var next = insertLineContent(line, builder); sawBefore = line == lineBefore; if (next) line = getLine(cm.view.doc, next.to.line); } while (next); if (measure && !builder.addedOne) measure[0] = builder.pre.appendChild(elt("span", "\u200b")); if (!builder.pre.firstChild && !lineIsHidden(realLine)) builder.pre.appendChild(document.createTextNode("\u00a0")); return builder.pre; } var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g; function buildToken(builder, text, style, startStyle, endStyle) { if (!text) return; if (!tokenSpecialChars.test(text)) { builder.col += text.length; var content = document.createTextNode(text); } else { var content = document.createDocumentFragment(), pos = 0; while (true) { tokenSpecialChars.lastIndex = pos; var m = tokenSpecialChars.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); builder.col += skipped; } if (!m) break; pos += skipped + 1; if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); builder.col += tabWidth; } else { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + m[0].charCodeAt(0).toString(16); content.appendChild(token); builder.col += 1; } } } if (style || startStyle || endStyle || builder.measure) { var fullStyle = style || ""; if (startStyle) fullStyle += startStyle; if (endStyle) fullStyle += endStyle; return builder.pre.appendChild(elt("span", [content], fullStyle)); } builder.pre.appendChild(content); } function buildTokenMeasure(builder, text, style, startStyle, endStyle) { for (var i = 0; i < text.length; ++i) { if (i && i < text.length - 1 && builder.cm.options.lineWrapping && spanAffectsWrapping.test(text.slice(i - 1, i + 1))) builder.pre.appendChild(elt("wbr")); builder.measure[builder.pos++] = buildToken(builder, text.charAt(i), style, i == 0 && startStyle, i == text.length - 1 && endStyle); } if (text.length) builder.addedOne = true; } function buildCollapsedSpan(builder, size, widget) { if (widget) { if (!builder.display) widget = widget.cloneNode(true); builder.pre.appendChild(widget); if (builder.measure && size) { builder.measure[builder.pos] = widget; builder.addedOne = true; } } builder.pos += size; } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder) { var st = line.styles, spans = line.markedSpans; if (!spans) { for (var i = 0; i < st.length; i+=2) builder.addToken(builder, st[i], styleToClass(st[i+1])); return; } var allText = line.text, len = allText.length; var pos = 0, i = 0, text = "", style; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = ""; collapsed = null; nextChange = Infinity; var foundBookmark = null; for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (sp.from <= pos && (sp.to == null || sp.to > pos)) { if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) spanStyle += " " + m.className; if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; if (m.collapsed && (!collapsed || collapsed.marker.width < m.width)) collapsed = sp; } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmark = m.replacedWith; } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, collapsed.from != null && collapsed.marker.replacedWith); if (collapsed.to == null) return collapsed.marker.find(); } if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark); } if (pos >= len) break; var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; if (!collapsed) { var tokenText = end > upto ? text.slice(0, upto - pos) : text; builder.addToken(builder, tokenText, style + spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : ""); } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} pos = end; spanStartStyle = ""; } text = st[i++]; style = styleToClass(st[i++]); } } } // DOCUMENT DATA STRUCTURE function LeafChunk(lines) { this.lines = lines; this.parent = null; for (var i = 0, e = lines.length, height = 0; i < e; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length; }, remove: function(at, n, cm) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; this.height -= line.height; cleanUpLine(line); signalLater(cm, line, "delete"); } this.lines.splice(at, n); }, collapse: function(lines) { lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); }, insertHeight: function(at, lines, height) { this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; }, iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) if (op(this.lines[at])) return true; } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0, e = children.length; i < e; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size; }, remove: function(at, n, callbacks) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.remove(at, rm, callbacks); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) break; at = 0; } else at -= sz; } if (this.size - n < 25) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); }, insert: function(at, lines) { var height = 0; for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; this.insertHeight(at, lines, height); }, insertHeight: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertHeight(at, lines, height); if (child.lines && child.lines.length > 50) { while (child.lines.length > 50) { var spilled = child.lines.splice(child.lines.length - 25, 25); var newleaf = new LeafChunk(spilled); child.height -= newleaf.height; this.children.splice(i + 1, 0, newleaf); newleaf.parent = this; } this.maybeSpill(); } break; } at -= sz; } }, maybeSpill: function() { if (this.children.length <= 10) return; var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10); me.parent.maybeSpill(); }, iter: function(from, to, op) { this.iterN(from, to - from, op); }, iterN: function(at, n, op) { for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) return true; if ((n -= used) == 0) break; at = 0; } else at -= sz; } } }; // LINE UTILITIES function lineDoc(line) { for (var d = line.parent; d && d.parent; d = d.parent) {} return d; } function getLine(chunk, n) { while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break; } n -= sz; } } return chunk.lines[n]; } function updateLineHeight(line, height) { var diff = height - line.height; for (var n = line; n; n = n.parent) n.height += diff; } function lineNo(line) { if (line.parent == null) return null; var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0, e = chunk.children.length; ; ++i) { if (chunk.children[i] == cur) break; no += chunk.children[i].chunkSize(); } } return no; } function lineAtHeight(chunk, h) { var n = 0; outer: do { for (var i = 0, e = chunk.children.length; i < e; ++i) { var child = chunk.children[i], ch = child.height; if (h < ch) { chunk = child; continue outer; } h -= ch; n += child.chunkSize(); } return n; } while (!chunk.lines); for (var i = 0, e = chunk.lines.length; i < e; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) break; h -= lh; } return n + i; } function heightAtLine(cm, lineObj) { var merged; while (merged = collapsedSpanAtStart(lineObj)) lineObj = getLine(cm.view.doc, merged.find().from.line); var h = 0, chunk = lineObj.parent; for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i]; if (line == lineObj) break; else h += line.height; } for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { for (var i = 0; i < p.children.length; ++i) { var cur = p.children[i]; if (cur == chunk) break; else h += cur.height; } } return h; } function getOrder(line) { var order = line.order; if (order == null) order = line.order = bidiOrdering(line.text); return order; } // HISTORY // The history object 'chunks' changes that are made close together // and at almost the same time into bigger undoable units. function makeHistory() { return {time: 0, done: [], undone: [], compound: 0, closed: false, dirtyCounter: 0}; } function addChange(history, start, added, old) { history.undone.length = 0; var time = +new Date, cur = lst(history.done), last = cur && lst(cur); var dtime = time - history.time; function updateDirty() { if (history.dirtyCounter < 0) { // The user has made a change after undoing past the last clean state. // We can never get back to a clean state now until markClean() is called. history.dirtyCounter = NaN; } history.dirtyCounter++; } if (cur && !history.closed && history.compound) { updateDirty(); cur.push({start: start, added: added, old: old}); } else if (dtime > 400 || !last || history.closed || last.start > start + old.length || last.start + last.added < start) { updateDirty(); history.done.push([{start: start, added: added, old: old}]); history.closed = false; } else { var startBefore = Math.max(0, last.start - start), endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); if (startBefore) last.start = start; last.added += added - (old.length - startBefore - endAfter); } history.time = time; } function compoundChange(cm, f) { var hist = cm.view.history; if (!hist.compound++) hist.closed = true; try { return f(); } finally { if (!--hist.compound) hist.closed = true; } } // EVENT OPERATORS function stopMethod() {e_stop(this);} // Ensure an event has a stop method. function addStop(event) { if (!event.stop) event.stop = stopMethod; return event; } function e_preventDefault(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } function e_stopPropagation(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} CodeMirror.e_stop = e_stop; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; function e_target(e) {return e.target || e.srcElement;} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) b = 1; else if (e.button & 2) b = 3; else if (e.button & 4) b = 2; } if (mac && e.ctrlKey && b == 1) b = 3; return b; } // Allow 3rd-party code to override event properties by adding an override // object to an event object. function e_prop(e, prop) { var overridden = e.override && e.override.hasOwnProperty(prop); return overridden ? e.override[prop] : e[prop]; } // EVENT HANDLING function on(emitter, type, f) { if (emitter.addEventListener) emitter.addEventListener(type, f, false); else if (emitter.attachEvent) emitter.attachEvent("on" + type, f); else { var map = emitter._handlers || (emitter._handlers = {}); var arr = map[type] || (map[type] = []); arr.push(f); } } function off(emitter, type, f) { if (emitter.removeEventListener) emitter.removeEventListener(type, f, false); else if (emitter.detachEvent) emitter.detachEvent("on" + type, f); else { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; for (var i = 0; i < arr.length; ++i) if (arr[i] == f) { arr.splice(i, 1); break; } } } function signal(emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); } function signalLater(cm, emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 3), flist = cm.curOp && cm.curOp.delayedCallbacks; function bnd(f) {return function(){f.apply(null, args);};}; for (var i = 0; i < arr.length; ++i) if (flist) flist.push(bnd(arr[i])); else arr[i].apply(null, args); } function hasHandler(emitter, type) { var arr = emitter._handlers && emitter._handlers[type]; return arr && arr.length > 0; } CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; // MISC UTILITIES // Number of pixels added to scroller and sizer to hide scrollbar var scrollerCutOff = 30; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; function Delayed() {this.id = null;} Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = 0, n = 0; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; } CodeMirror.countColumn = countColumn; var spaceStrs = [""]; function spaceStr(n) { while (spaceStrs.length <= n) spaceStrs.push(lst(spaceStrs) + " "); return spaceStrs[n]; } function lst(arr) { return arr[arr.length-1]; } function selectInput(node) { if (ios) { // Mobile Safari apparently has a bug where select() is broken. node.selectionStart = 0; node.selectionEnd = node.value.length; } else node.select(); } // Used to position the cursor after an undo/redo by finding the // last edited character. function editEnd(from, to) { if (!to) return 0; if (!from) return to.length; for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) if (from.charAt(i) != to.charAt(j)) break; return j + 1; } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } function emptyArray(size) { for (var a = [], i = 0; i < size; ++i) a.push(undefined); return a; } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args);}; } var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/; function isWordChar(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); } function isEmpty(obj) { var c = 0; for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) ++c; return !c; } var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F]/; // DOM UTILITIES function elt(tag, content, className, style) { var e = document.createElement(tag); if (className) e.className = className; if (style) e.style.cssText = style; if (typeof content == "string") setTextContent(e, content); else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); return e; } function removeChildren(e) { e.innerHTML = ""; return e; } function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e); } function setTextContent(e, str) { if (ie_lt9) { e.innerHTML = ""; e.appendChild(document.createTextNode(str)); } else e.textContent = str; } // FEATURE DETECTION // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie_lt9) return false; var div = elt('div'); return "draggable" in div || "dragDrop" in div; }(); // Feature-detect whether newlines in textareas are converted to \r\n var lineSep = function () { var te = elt("textarea"); te.value = "foo\nbar"; if (te.value.indexOf("\r") > -1) return "\r\n"; return "\n"; }(); // For a reason I have yet to figure out, some browsers disallow // word wrapping between certain characters *only* if a new inline // element is started between them. This makes it hard to reliably // measure the position of things, since that requires inserting an // extra span. This terribly fragile set of regexps matches the // character combinations that suffer from this phenomenon on the // various browsers. var spanAffectsWrapping = /^$/; // Won't match any two-character string if (gecko) spanAffectsWrapping = /$'/; else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; var knownScrollbarWidth; function scrollbarWidth(measure) { if (knownScrollbarWidth != null) return knownScrollbarWidth; var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); removeChildrenAndAdd(measure, test); if (test.offsetWidth) knownScrollbarWidth = test.offsetHeight - test.clientHeight; return knownScrollbarWidth || 0; } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) nl = string.length; var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result; } : function(string){return string.split(/\r\n?|\n/);}; CodeMirror.splitLines = splitLines; var hasSelection = window.getSelection ? function(te) { try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } } : function(te) { try {var range = te.ownerDocument.selection.createRange();} catch(e) {} if (!range || range.parentElement() != te) return false; return range.compareEndPoints("StartToEnd", range) != 0; }; var hasCopyEvent = (function() { var e = elt("div"); if ("oncopy" in e) return true; e.setAttribute("oncopy", "return;"); return typeof e.oncopy == 'function'; })(); // KEY NAMING var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; CodeMirror.keyNames = keyNames; (function() { // Number keys for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); // Alphabetic keys for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); // Function keys for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; })(); // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) return f(from, to, "ltr"); for (var i = 0; i < order.length; ++i) { var part = order[i]; if (part.from < to && part.to > from) f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); } } function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } function bidiRight(part) { return part.level % 2 ? part.from : part.to; } function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } function lineRight(line) { var order = getOrder(line); if (!order) return line.text.length; return bidiRight(lst(order)); } function lineStart(cm, lineNo) { var merged, line; while (merged = collapsedSpanAtStart(line = getLine(cm.view.doc, lineNo))) lineNo = merged.find().from.line; var order = getOrder(line); var ch = !order ? 0 : order[0].level % 2 ? lineRight(line) : lineLeft(line); return {line: lineNo, ch: ch}; } function lineEnd(cm, lineNo) { var merged, line; while (merged = collapsedSpanAtEnd(line = getLine(cm.view.doc, lineNo))) lineNo = merged.find().to.line; var order = getOrder(line); var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); return {line: lineNo, ch: ch}; } // This is somewhat involved. It is needed in order to move // 'visually' through bi-directional text -- i.e., pressing left // should make the cursor go left, even when in RTL text. The // tricky part is the 'jumps', where RTL and LTR text touch each // other. This often requires the cursor offset to move more than // one unit, in order to visually move one unit. function moveVisually(line, start, dir, byUnit) { var bidi = getOrder(line); if (!bidi) return moveLogically(line, start, dir, byUnit); var moveOneUnit = byUnit ? function(pos, dir) { do pos += dir; while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); return pos; } : function(pos, dir) { return pos + dir; }; var linedir = bidi[0].level; for (var i = 0; i < bidi.length; ++i) { var part = bidi[i], sticky = part.level % 2 == linedir; if ((part.from < start && part.to > start) || (sticky && (part.from == start || part.to == start))) break; } var target = moveOneUnit(start, part.level % 2 ? -dir : dir); while (target != null) { if (part.level % 2 == linedir) { if (target < part.from || target > part.to) { part = bidi[i += dir]; target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1)); } else break; } else { if (target == bidiLeft(part)) { part = bidi[--i]; target = part && bidiRight(part); } else if (target == bidiRight(part)) { part = bidi[++i]; target = part && bidiLeft(part); } else break; } } return target < 0 || target > line.text.length ? null : target; } function moveLogically(line, start, dir, byUnit) { var target = start + dir; if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir; return target < 0 || target > line.text.length ? null : target; } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. var bidiOrdering = (function() { // Character types for codepoints 0 to 0xff var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; // Character types for codepoints 0x600 to 0x6ff var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; function charType(code) { var type = "L"; if (code <= 0xff) return lowTypes.charAt(code); else if (0x590 <= code && code <= 0x5f4) return "R"; else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600); else if (0x700 <= code && code <= 0x8ac) return "r"; else return "L"; } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; return function charOrdering(str) { if (!bidiRE.test(str)) return false; var len = str.length, types = [], startType = null; for (var i = 0, type; i < len; ++i) { types.push(type = charType(str.charCodeAt(i))); if (startType == null) { if (type == "L") startType = "L"; else if (type == "R" || type == "r") startType = "R"; } } if (startType == null) startType = "L"; // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (var i = 0, prev = startType; i < len; ++i) { var type = types[i]; if (type == "m") types[i] = prev; else prev = type; } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i = 0, cur = startType; i < len; ++i) { var type = types[i]; if (type == "1" && cur == "r") types[i] = "n"; else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i = 1, prev = types[0]; i < len - 1; ++i) { var type = types[i]; if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; else if (type == "," && prev == types[i+1] && (prev == "1" || prev == "n")) types[i] = prev; prev = type; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i = 0; i < len; ++i) { var type = types[i]; if (type == ",") types[i] = "N"; else if (type == "%") { for (var end = i + 1; end < len && types[end] == "%"; ++end) {} var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i = 0, cur = startType; i < len; ++i) { var type = types[i]; if (cur == "L" && type == "1") types[i] = "L"; else if (isStrong.test(type)) cur = type; } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i = 0; i < len; ++i) { if (isNeutral.test(types[i])) { for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} var before = (i ? types[i-1] : startType) == "L"; var after = (end < len - 1 ? types[end] : startType) == "L"; var replace = before || after ? "L" : "R"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i = 0; i < len;) { if (countsAsLeft.test(types[i])) { var start = i; for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} order.push({from: start, to: i, level: 0}); } else { var pos = i, at = order.length; for (++i; i < len && types[i] != "L"; ++i) {} for (var j = pos; j < i;) { if (countsAsNum.test(types[j])) { if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); var nstart = j; for (++j; j < i && countsAsNum.test(types[j]); ++j) {} order.splice(at, 0, {from: nstart, to: j, level: 2}); pos = j; } else ++j; } if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); } } if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift({from: 0, to: m[0].length, level: 0}); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push({from: len - m[0].length, to: len, level: 0}); } if (order[0].level != lst(order).level) order.push({from: len, to: len, level: order[0].level}); return order; }; })(); // THE END CodeMirror.version = "3.0 B2"; return CodeMirror; })(); ; CodeMirror.defineMode("css", function(config) { var indentUnit = config.indentUnit, type; var keywords = keySet(["above", "absolute", "activeborder", "activecaption", "afar", "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", "both", "bottom", "break-all", "break-word", "button", "button-bevel", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", "col-resize", "collapse", "compact", "condensed", "contain", "content", "content-box", "context-menu", "continuous", "copy", "cover", "crop", "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", "decimal-leading-zero", "default", "default-button", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer", "landscape", "lao", "large", "larger", "left", "level", "lighter", "line-through", "linear", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", "lower-roman", "lowercase", "ltr", "malayalam", "match", "media-controls-background", "media-current-time-display", "media-fullscreen-button", "media-mute-button", "media-play-button", "media-return-to-realtime-button", "media-rewind-button", "media-seek-back-button", "media-seek-forward-button", "media-slider", "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", "media-volume-slider-container", "media-volume-sliderthumb", "medium", "menu", "menulist", "menulist-button", "menulist-text", "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize", "narrower", "navy", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", "outside", "overlay", "overline", "padding", "padding-box", "painted", "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radio", "read-only", "read-write", "read-write-plaintext-only", "relative", "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", "single", "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps", "small-caption", "smaller", "solid", "somali", "source-atop", "source-in", "source-out", "source-over", "space", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", "subpixel-antialiased", "super", "sw-resize", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "white", "wider", "window", "windowframe", "windowtext", "x-large", "x-small", "xor", "xx-large", "xx-small", "yellow", "-wap-marquee", "-webkit-activelink", "-webkit-auto", "-webkit-baseline-middle", "-webkit-body", "-webkit-box", "-webkit-center", "-webkit-control", "-webkit-focus-ring-color", "-webkit-grab", "-webkit-grabbing", "-webkit-gradient", "-webkit-inline-box", "-webkit-left", "-webkit-link", "-webkit-marquee", "-webkit-mini-control", "-webkit-nowrap", "-webkit-pictograph", "-webkit-right", "-webkit-small-control", "-webkit-text", "-webkit-xxx-large", "-webkit-zoom-in", "-webkit-zoom-out"]); function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) keys[array[i]] = true; return keys; } function ret(style, tp) {type = tp; return style;} function tokenBase(stream, state) { var ch = stream.next(); if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());} else if (ch == "/" && stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else if (ch == "<" && stream.eat("!")) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (ch == "=") ret(null, "compare"); else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "#") { stream.eatWhile(/[\w\\\-]/); return ret("atom", "hash"); } else if (ch == "!") { stream.match(/^\s*\w*/); return ret("keyword", "important"); } else if (/\d/.test(ch)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (/[,.+>*\/]/.test(ch)) { return ret(null, "select-op"); } else if (/[;{}:\[\]]/.test(ch)) { return ret(null, ch); } else { stream.eatWhile(/[\w\\\-]/); return ret("variable", "variable"); } } function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenSGMLComment(stream, state) { var dashes = 0, ch; while ((ch = stream.next()) != null) { if (dashes >= 2 && ch == ">") { state.tokenize = tokenBase; break; } dashes = (ch == "-") ? dashes + 1 : 0; } return ret("comment", "comment"); } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } return { startState: function(base) { return {tokenize: tokenBase, baseIndent: base || 0, stack: []}; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); var context = state.stack[state.stack.length-1]; if (type == "hash" && context != "rule") style = "string-2"; else if (style == "variable") { if (context == "rule") style = keywords[stream.current()] ? "keyword" : "number"; else if (!context || context == "@media{") style = "tag"; } if (context == "rule" && /^[\{\};]$/.test(type)) state.stack.pop(); if (type == "{") { if (context == "@media") state.stack[state.stack.length-1] = "@media{"; else state.stack.push("{"); } else if (type == "}") state.stack.pop(); else if (type == "@media") state.stack.push("@media"); else if (context == "{" && type != "comment") state.stack.push("rule"); return style; }, indent: function(state, textAfter) { var n = state.stack.length; if (/^\}/.test(textAfter)) n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1; return state.baseIndent + n * indentUnit; }, electricChars: "}" }; }); CodeMirror.defineMIME("text/css", "css"); ; CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var jsonMode = parserConfig.json; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; return { "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom }; }(); var isOperatorChar = /[+\-*&%=<>!?|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function nextUntilUnescaped(stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function jsTokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") return chain(stream, state, jsTokenString(ch)); else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return ret(ch); else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); } else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) { stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { return chain(stream, state, jsTokenComment); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (state.reAllowed) { nextUntilUnescaped(stream, "/"); stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla return ret("regexp", "string-2"); } else { stream.eatWhile(isOperatorChar); return ret("operator", null, stream.current()); } } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return ret("operator", null, stream.current()); } else { stream.eatWhile(/[\w\$_]/); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return (known && state.kwAllowed) ? ret(known.type, known.style, word) : ret("variable", "variable", word); } } function jsTokenString(quote) { return function(stream, state) { if (!nextUntilUnescaped(stream, quote)) state.tokenize = jsTokenBase; return ret("string", "string"); }; } function jsTokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = jsTokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function register(varname) { var state = cx.state; if (state.context) { cx.marked = "def"; for (var v = state.localVars; v; v = v.next) if (v.name == varname) return; state.localVars = {name: varname, next: state.localVars}; } } // Combinators var defaultVars = {name: "this", next: {name: "arguments"}}; function pushcontext() { if (!cx.state.context) cx.state.localVars = defaultVars; cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; } function popcontext() { cx.state.localVars = cx.state.context.vars; cx.state.context = cx.state.context.prev; } function pushlex(type, info) { var result = function() { var state = cx.state; state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { return function expecting(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); else return cont(arguments.callee); }; } function statement(type) { if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "{") return cont(pushlex("}"), block, poplex); if (type == ";") return cont(); if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); if (type == "variable") return cont(pushlex("stat"), maybelabel); if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); if (type == "function") return cont(functiondef); if (type == "keyword c") return cont(maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator); if (type == "operator") return cont(expression); if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeoperator(type, value) { if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); if (type == "operator" && value == "?") return cont(expression, expect(":"), expression); if (type == ";") return; if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); if (type == ".") return cont(property, maybeoperator); if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperator, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type) { if (type == "variable") cx.marked = "property"; if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression); } function commasep(what, end) { function proceed(type) { if (type == ",") return cont(what, proceed); if (type == end) return cont(); return cont(expect(end)); } return function commaSeparated(type) { if (type == end) return cont(); else return pass(what, proceed); }; } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function vardef1(type, value) { if (type == "variable"){register(value); return cont(vardef2);} return cont(); } function vardef2(type, value) { if (value == "=") return cont(expression, vardef2); if (type == ",") return cont(vardef1); } function forspec1(type) { if (type == "var") return cont(vardef1, forspec2); if (type == ";") return pass(forspec2); if (type == "variable") return cont(formaybein); return pass(forspec2); } function formaybein(type, value) { if (value == "in") return cont(expression); return cont(maybeoperator, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in") return cont(expression); return cont(expression, expect(";"), forspec3); } function forspec3(type) { if (type != ")") cont(expression); } function functiondef(type, value) { if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); } function funarg(type, value) { if (type == "variable") {register(value); return cont();} } // Interface return { startState: function(basecolumn) { return { tokenize: jsTokenBase, reAllowed: true, kwAllowed: true, cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && {vars: parserConfig.localVars}, indented: 0 }; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/)); state.kwAllowed = type != '.'; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize != jsTokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricChars: ":{}" }; }); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); ; CodeMirror.defineMode("xml", function(config, parserConfig) { var indentUnit = config.indentUnit; var Kludges = parserConfig.htmlMode ? { autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true}, implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, 'th': true, 'tr': true}, contextGrabbers: { 'dd': {'dd': true, 'dt': true}, 'dt': {'dd': true, 'dt': true}, 'li': {'li': true}, 'option': {'option': true, 'optgroup': true}, 'optgroup': {'optgroup': true}, 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, 'rp': {'rp': true, 'rt': true}, 'rt': {'rp': true, 'rt': true}, 'tbody': {'tbody': true, 'tfoot': true}, 'td': {'td': true, 'th': true}, 'tfoot': {'tbody': true}, 'th': {'td': true, 'th': true}, 'thead': {'tbody': true, 'tfoot': true}, 'tr': {'tr': true} }, doNotIndent: {"pre": true}, allowUnquoted: true, allowMissing: true } : { autoSelfClosers: {}, implicitlyClosed: {}, contextGrabbers: {}, doNotIndent: {}, allowUnquoted: false, allowMissing: false }; var alignCDATA = parserConfig.alignCDATA; // Return variables for tokenizers var tagName, type; function inText(stream, state) { function chain(parser) { state.tokenize = parser; return parser(stream, state); } var ch = stream.next(); if (ch == "<") { if (stream.eat("!")) { if (stream.eat("[")) { if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); else return null; } else if (stream.match("--")) return chain(inBlock("comment", "-->")); else if (stream.match("DOCTYPE", true, true)) { stream.eatWhile(/[\w\._\-]/); return chain(doctype(1)); } else return null; } else if (stream.eat("?")) { stream.eatWhile(/[\w\._\-]/); state.tokenize = inBlock("meta", "?>"); return "meta"; } else { type = stream.eat("/") ? "closeTag" : "openTag"; stream.eatSpace(); tagName = ""; var c; while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; state.tokenize = inTag; return "tag"; } } else if (ch == "&") { var ok; if (stream.eat("#")) { if (stream.eat("x")) { ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); } else { ok = stream.eatWhile(/[\d]/) && stream.eat(";"); } } else { ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); } return ok ? "atom" : "error"; } else { stream.eatWhile(/[^&<]/); return null; } } function inTag(stream, state) { var ch = stream.next(); if (ch == ">" || (ch == "/" && stream.eat(">"))) { state.tokenize = inText; type = ch == ">" ? "endTag" : "selfcloseTag"; return "tag"; } else if (ch == "=") { type = "equals"; return null; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); return state.tokenize(stream, state); } else { stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/); return "word"; } } function inAttribute(quote) { return function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inTag; break; } } return "string"; }; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } return style; }; } function doctype(depth) { return function(stream, state) { var ch; while ((ch = stream.next()) != null) { if (ch == "<") { state.tokenize = doctype(depth + 1); return state.tokenize(stream, state); } else if (ch == ">") { if (depth == 1) { state.tokenize = inText; break; } else { state.tokenize = doctype(depth - 1); return state.tokenize(stream, state); } } } return "meta"; }; } var curState, setStyle; function pass() { for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function pushContext(tagName, startOfLine) { var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); curState.context = { prev: curState.context, tagName: tagName, indent: curState.indented, startOfLine: startOfLine, noIndent: noIndent }; } function popContext() { if (curState.context) curState.context = curState.context.prev; } function element(type) { if (type == "openTag") { curState.tagName = tagName; return cont(attributes, endtag(curState.startOfLine)); } else if (type == "closeTag") { var err = false; if (curState.context) { if (curState.context.tagName != tagName) { if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { popContext(); } err = !curState.context || curState.context.tagName != tagName; } } else { err = true; } if (err) setStyle = "error"; return cont(endclosetag(err)); } return cont(); } function endtag(startOfLine) { return function(type) { if (type == "selfcloseTag" || (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase()))) { maybePopContext(curState.tagName.toLowerCase()); return cont(); } if (type == "endTag") { maybePopContext(curState.tagName.toLowerCase()); pushContext(curState.tagName, startOfLine); return cont(); } return cont(); }; } function endclosetag(err) { return function(type) { if (err) setStyle = "error"; if (type == "endTag") { popContext(); return cont(); } setStyle = "error"; return cont(arguments.callee); }; } function maybePopContext(nextTagName) { var parentTagName; while (true) { if (!curState.context) { return; } parentTagName = curState.context.tagName.toLowerCase(); if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { return; } popContext(); } } function attributes(type) { if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} if (type == "endTag" || type == "selfcloseTag") return pass(); setStyle = "error"; return cont(attributes); } function attribute(type) { if (type == "equals") return cont(attvalue, attributes); if (!Kludges.allowMissing) setStyle = "error"; return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); } function attvalue(type) { if (type == "string") return cont(attvaluemaybe); if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} setStyle = "error"; return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); } function attvaluemaybe(type) { if (type == "string") return cont(attvaluemaybe); else return pass(); } return { startState: function() { return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null}; }, token: function(stream, state) { if (stream.sol()) { state.startOfLine = true; state.indented = stream.indentation(); } if (stream.eatSpace()) return null; setStyle = type = tagName = null; var style = state.tokenize(stream, state); state.type = type; if ((style || type) && style != "comment") { curState = state; while (true) { var comb = state.cc.pop() || element; if (comb(type || style)) break; } } state.startOfLine = false; return setStyle || style; }, indent: function(state, textAfter, fullLine) { var context = state.context; if ((state.tokenize != inTag && state.tokenize != inText) || context && context.noIndent) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0; if (context && /^<\//.test(textAfter)) context = context.prev; while (context && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return 0; }, compareStates: function(a, b) { if (a.indented != b.indented || a.tokenize != b.tokenize) return false; for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) { if (!ca || !cb) return ca == cb; if (ca.tagName != cb.tagName || ca.indent != cb.indent) return false; } }, electricChars: "/" }; }); CodeMirror.defineMIME("text/xml", "xml"); CodeMirror.defineMIME("application/xml", "xml"); if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); ; CodeMirror.defineMode("htmlmixed", function(config, parserConfig) { var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true}); var jsMode = CodeMirror.getMode(config, "javascript"); var cssMode = CodeMirror.getMode(config, "css"); function html(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (style == "tag" && stream.current() == ">" && state.htmlState.context) { if (/^script$/i.test(state.htmlState.context.tagName)) { state.token = javascript; state.localState = jsMode.startState(htmlMode.indent(state.htmlState, "")); state.mode = "javascript"; } else if (/^style$/i.test(state.htmlState.context.tagName)) { state.token = css; state.localState = cssMode.startState(htmlMode.indent(state.htmlState, "")); state.mode = "css"; } } return style; } function maybeBackup(stream, pat, style) { var cur = stream.current(); var close = cur.search(pat); if (close > -1) stream.backUp(cur.length - close); return style; } function javascript(stream, state) { if (stream.match(/^<\/\s*script\s*>/i, false)) { state.token = html; state.localState = null; state.mode = "html"; return html(stream, state); } return maybeBackup(stream, /<\/\s*script\s*>/, jsMode.token(stream, state.localState)); } function css(stream, state) { if (stream.match(/^<\/\s*style\s*>/i, false)) { state.token = html; state.localState = null; state.mode = "html"; return html(stream, state); } return maybeBackup(stream, /<\/\s*style\s*>/, cssMode.token(stream, state.localState)); } return { startState: function() { var state = htmlMode.startState(); return {token: html, localState: null, mode: "html", htmlState: state}; }, copyState: function(state) { if (state.localState) var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState); return {token: state.token, localState: local, mode: state.mode, htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; }, token: function(stream, state) { return state.token(stream, state); }, indent: function(state, textAfter) { if (state.token == html || /^\s*<\//.test(textAfter)) return htmlMode.indent(state.htmlState, textAfter); else if (state.token == javascript) return jsMode.indent(state.localState, textAfter); else return cssMode.indent(state.localState, textAfter); }, compareStates: function(a, b) { if (a.mode != b.mode) return false; if (a.localState) return CodeMirror.Pass; return htmlMode.compareStates(a.htmlState, b.htmlState); }, electricChars: "/{}:" }; }, "xml", "javascript", "css"); CodeMirror.defineMIME("text/html", "htmlmixed"); ; /** * @constructor * @extends {WebInspector.View} * @implements {WebInspector.TextEditor} * @param {?string} url * @param {WebInspector.TextEditorDelegate} delegate */ WebInspector.CodeMirrorTextEditor = function(url, delegate) { WebInspector.View.call(this); this._delegate = delegate; this._url = url; this.registerRequiredCSS("codemirror.css"); this.registerRequiredCSS("cmdevtools.css"); this._codeMirror = window.CodeMirror(this.element, { lineNumbers: true, gutters: ["CodeMirror-linenumbers", "breakpoints"] }); this._codeMirror.on("change", this._change.bind(this)); this._codeMirror.on("gutterClick", this._gutterClick.bind(this)); this.element.addEventListener("contextmenu", this._contextMenu.bind(this)); this._lastRange = this.range(); this.element.firstChild.addStyleClass("source-code"); this.element.firstChild.addStyleClass("fill"); this._elementToWidget = new Map(); } WebInspector.CodeMirrorTextEditor.prototype = { /** * @param {string} mimeType */ set mimeType(mimeType) { this._codeMirror.setOption("mode", mimeType); switch(mimeType) { case "text/html": this._codeMirror.setOption("theme", "web-inspector-html"); break; case "text/css": this._codeMirror.setOption("theme", "web-inspector-css"); break; case "text/javascript": this._codeMirror.setOption("theme", "web-inspector-js"); break; } }, /** * @param {boolean} readOnly */ setReadOnly: function(readOnly) { this._codeMirror.setOption("readOnly", readOnly); }, /** * @return {boolean} */ readOnly: function() { return !!this._codeMirror.getOption("readOnly"); }, /** * @return {Element} */ defaultFocusedElement: function() { return this.element.firstChild; }, focus: function() { this._codeMirror.focus(); }, beginUpdates: function() { }, endUpdates: function() { }, /** * @param {number} lineNumber */ revealLine: function(lineNumber) { this._codeMirror.setCursor({ line: lineNumber, ch: 0 }); this._codeMirror.scrollIntoView(); }, _gutterClick: function(instance, lineNumber, gutter, event) { this.dispatchEventToListeners(WebInspector.TextEditor.Events.GutterClick, { lineNumber: lineNumber, event: event }); }, _contextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); var target = event.target.enclosingNodeOrSelfWithClass("CodeMirror-gutter-elt"); if (target) this._delegate.populateLineGutterContextMenu(contextMenu, parseInt(target.textContent, 10) - 1); else this._delegate.populateTextAreaContextMenu(contextMenu, null); contextMenu.show(); }, /** * @param {number} lineNumber * @param {boolean} disabled * @param {boolean} conditional */ addBreakpoint: function(lineNumber, disabled, conditional) { var element = document.createElement("span"); element.textContent = lineNumber + 1; element.className = "cm-breakpoint" + (disabled ? " cm-breakpoint-disabled" : "") + (conditional ? " cm-breakpoint-conditional" : ""); this._codeMirror.setGutterMarker(lineNumber, "breakpoints", element); }, /** * @param {number} lineNumber */ removeBreakpoint: function(lineNumber) { this._codeMirror.setGutterMarker(lineNumber, "breakpoints", null); }, /** * @param {number} lineNumber */ setExecutionLine: function(lineNumber) { this._executionLine = this._codeMirror.getLineHandle(lineNumber); this._codeMirror.addLineClass(this._executionLine, null, "cm-execution-line"); }, clearExecutionLine: function() { if (this._executionLine) this._codeMirror.removeLineClass(this._executionLine, null, "cm-execution-line"); delete this._executionLine; }, /** * @param {number} lineNumber * @param {Element} element */ addDecoration: function(lineNumber, element) { var widget = this._codeMirror.addLineWidget(lineNumber, element); this._elementToWidget.put(element, widget); }, /** * @param {number} lineNumber * @param {Element} element */ removeDecoration: function(lineNumber, element) { var widget = this._elementToWidget.remove(element); if (widget) this._codeMirror.removeLineWidget(widget); }, /** * @param {WebInspector.TextRange} range */ markAndRevealRange: function(range) { if (range) this.setSelection(range); }, /** * @param {number} lineNumber */ highlightLine: function(lineNumber) { this.clearLineHighlight(); this._highlightedLine = this._codeMirror.getLineHandle(lineNumber); if (!this._highlightedLine) return; this.revealLine(lineNumber); this._codeMirror.addLineClass(this._highlightedLine, null, "cm-highlight"); this._clearHighlightTimeout = setTimeout(this.clearLineHighlight.bind(this), 2000); }, clearLineHighlight: function() { if (this._clearHighlightTimeout) clearTimeout(this._clearHighlightTimeout); delete this._clearHighlightTimeout; if (this._highlightedLine) this._codeMirror.removeLineClass(this._highlightedLine, null, "cm-highlight"); delete this._highlightedLine; }, /** * @return {Array.<Element>} */ elementsToRestoreScrollPositionsFor: function() { return []; }, /** * @param {WebInspector.TextEditor} textEditor */ inheritScrollPositions: function(textEditor) { }, onResize: function() { this._codeMirror.refresh(); }, /** * @param {WebInspector.TextRange} range * @param {string} text * @return {WebInspector.TextRange} */ editRange: function(range, text) { var pos = this._toPos(range); this._codeMirror.replaceRange(text, pos.start, pos.end); var newRange = this._toRange(pos.start, this._codeMirror.posFromIndex(this._codeMirror.indexFromPos(pos.start) + text.length)); this._delegate.onTextChanged(range, newRange); return newRange; }, _change: function() { var widgets = this._elementToWidget.values(); for (var i = 0; i < widgets.length; ++i) this._codeMirror.removeLineWidget(widgets[i]); this._elementToWidget.clear(); var newRange = this.range(); this._delegate.onTextChanged(this._lastRange, newRange); this._lastRange = newRange; }, /** * @param {number} lineNumber */ scrollToLine: function(lineNumber) { this._codeMirror.setCursor({line:lineNumber, ch:0}); }, /** * @return {WebInspector.TextRange} */ selection: function(textRange) { var start = this._codeMirror.getCursor(true); var end = this._codeMirror.getCursor(false); if (start.line > end.line || (start.line == end.line && start.ch > end.ch)) return this._toRange(end, start); return this._toRange(start, end); }, /** * @return {WebInspector.TextRange?} */ lastSelection: function() { return this._lastSelection; }, /** * @param {WebInspector.TextRange} textRange */ setSelection: function(textRange) { this._lastSelection = textRange; var pos = this._toPos(textRange); this._codeMirror.setSelection(pos.start, pos.end); }, /** * @param {string} text */ setText: function(text) { this._codeMirror.setValue(text); }, /** * @return {string} */ text: function() { return this._codeMirror.getValue(); }, /** * @return {WebInspector.TextRange} */ range: function() { var lineCount = this.linesCount; var lastLine = this._codeMirror.getLine(lineCount - 1); return this._toRange({ line: 0, ch: 0 }, { line: lineCount - 1, ch: lastLine.length }); }, /** * @param {number} lineNumber * @return {string} */ line: function(lineNumber) { return this._codeMirror.getLine(lineNumber); }, /** * @return {number} */ get linesCount() { return this._codeMirror.lineCount(); }, /** * @param {number} line * @param {string} name * @param {Object?} value */ setAttribute: function(line, name, value) { var handle = this._codeMirror.getLineHandle(line); if (handle.attributes === undefined) handle.attributes = {}; handle.attributes[name] = value; }, /** * @param {number} line * @param {string} name * @return {Object|null} value */ getAttribute: function(line, name) { var handle = this._codeMirror.getLineHandle(line); return handle.attributes && handle.attributes[name] !== undefined ? handle.attributes[name] : null; }, /** * @param {number} line * @param {string} name */ removeAttribute: function(line, name) { var handle = this._codeMirror.getLineHandle(line); if (handle && handle.attributes) delete handle.attributes[name]; }, _toPos: function(range) { return { start: {line: range.startLine, ch: range.startColumn}, end: {line: range.endLine, ch: range.endColumn} } }, _toRange: function(start, end) { return new WebInspector.TextRange(start.line, start.ch, end.line, end.ch); }, __proto__: WebInspector.View.prototype }
JavaScript
/* * Copyright (C) 2011 Brian Grinstead All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @extends {WebInspector.View} */ WebInspector.Spectrum = function() { WebInspector.View.call(this); this.registerRequiredCSS("spectrum.css"); this.element.className = "spectrum-container"; this.element.tabIndex = 0; var topElement = this.element.createChild("div", "spectrum-top"); topElement.createChild("div", "spectrum-fill"); var topInnerElement = topElement.createChild("div", "spectrum-top-inner fill"); this._draggerElement = topInnerElement.createChild("div", "spectrum-color"); this._dragHelperElement = this._draggerElement.createChild("div", "spectrum-sat fill").createChild("div", "spectrum-val fill").createChild("div", "spectrum-dragger"); this._sliderElement = topInnerElement.createChild("div", "spectrum-hue"); this.slideHelper = this._sliderElement.createChild("div", "spectrum-slider"); var rangeContainer = this.element.createChild("div", "spectrum-range-container"); var alphaLabel = rangeContainer.createChild("label"); alphaLabel.textContent = WebInspector.UIString("\u03B1:"); this._alphaElement = rangeContainer.createChild("input", "spectrum-range"); this._alphaElement.setAttribute("type", "range"); this._alphaElement.setAttribute("min", "0"); this._alphaElement.setAttribute("max", "100"); this._alphaElement.addEventListener("change", alphaDrag.bind(this), false); var swatchElement = document.createElement("span"); swatchElement.className = "swatch"; this._swatchInnerElement = swatchElement.createChild("span", "swatch-inner"); var displayContainer = this.element.createChild("div"); displayContainer.appendChild(swatchElement); this._displayElement = displayContainer.createChild("span", "source-code spectrum-display-value"); WebInspector.Spectrum.draggable(this._sliderElement, hueDrag.bind(this)); WebInspector.Spectrum.draggable(this._draggerElement, colorDrag.bind(this), colorDragStart.bind(this)); function hueDrag(element, dragX, dragY) { this.hsv[0] = (dragY / this.slideHeight); this._onchange(); } var initialHelperOffset; function colorDragStart(element, dragX, dragY) { initialHelperOffset = { x: this._dragHelperElement.offsetLeft, y: this._dragHelperElement.offsetTop }; } function colorDrag(element, dragX, dragY, event) { if (event.shiftKey) { if (Math.abs(dragX - initialHelperOffset.x) >= Math.abs(dragY - initialHelperOffset.y)) dragY = initialHelperOffset.y; else dragX = initialHelperOffset.x; } this.hsv[1] = dragX / this.dragWidth; this.hsv[2] = (this.dragHeight - dragY) / this.dragHeight; this._onchange(); } function alphaDrag() { this.hsv[3] = this._alphaElement.value / 100; this._onchange(); } }; WebInspector.Spectrum.Events = { ColorChanged: "ColorChanged" }; WebInspector.Spectrum.hsvaToRGBA = function(h, s, v, a) { var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch(i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a]; }; WebInspector.Spectrum.rgbaToHSVA = function(r, g, b, a) { r = r / 255; g = g / 255; b = b / 255; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var h; var s; var v = max; var d = max - min; s = max ? d / max : 0; if(max === min) { // Achromatic. h = 0; } else { switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, v, a]; }; //FIXME: migrate to WebInspector.installDragHandle /** * @param {Function=} onmove * @param {Function=} onstart * @param {Function=} onstop */ WebInspector.Spectrum.draggable = function(element, onmove, onstart, onstop) { var doc = document; var dragging; var offset; var scrollOffset; var maxHeight; var maxWidth; function consume(e) { e.consume(true); } function move(e) { if (dragging) { var dragX = Math.max(0, Math.min(e.pageX - offset.left + scrollOffset.left, maxWidth)); var dragY = Math.max(0, Math.min(e.pageY - offset.top + scrollOffset.top, maxHeight)); if (onmove) onmove(element, dragX, dragY, e); } } function start(e) { var rightClick = e.which ? (e.which === 3) : (e.button === 2); if (!rightClick && !dragging) { if (onstart) onstart(element, e) dragging = true; maxHeight = element.clientHeight; maxWidth = element.clientWidth; scrollOffset = element.scrollOffset(); offset = element.totalOffset(); doc.addEventListener("selectstart", consume, false); doc.addEventListener("dragstart", consume, false); doc.addEventListener("mousemove", move, false); doc.addEventListener("mouseup", stop, false); move(e); consume(e); } } function stop(e) { if (dragging) { doc.removeEventListener("selectstart", consume, false); doc.removeEventListener("dragstart", consume, false); doc.removeEventListener("mousemove", move, false); doc.removeEventListener("mouseup", stop, false); if (onstop) onstop(element, e); } dragging = false; } element.addEventListener("mousedown", start, false); }; WebInspector.Spectrum.prototype = { /** * @type {WebInspector.Color} */ set color(color) { var rgba = (color.rgba || color.rgb).slice(0); if (rgba.length === 3) rgba[3] = 1; this.hsv = WebInspector.Spectrum.rgbaToHSVA(rgba[0], rgba[1], rgba[2], rgba[3]); }, get color() { var rgba = WebInspector.Spectrum.hsvaToRGBA(this.hsv[0], this.hsv[1], this.hsv[2], this.hsv[3]); var color; if (rgba[3] === 1) color = WebInspector.Color.fromRGB(rgba[0], rgba[1], rgba[2]); else color = WebInspector.Color.fromRGBA(rgba[0], rgba[1], rgba[2], rgba[3]); var colorValue = color.toString(this.outputColorFormat); if (!colorValue) colorValue = color.toString(); // this.outputColorFormat can be invalid for current color (e.g. "nickname"). return new WebInspector.Color(colorValue); }, get outputColorFormat() { var cf = WebInspector.Color.Format; var format = this._originalFormat; if (this.hsv[3] === 1) { // Simplify transparent formats. if (format === cf.RGBA) format = cf.RGB; else if (format === cf.HSLA) format = cf.HSL; } else { // Everything except HSL(A) should be returned as RGBA if transparency is involved. if (format === cf.HSL || format === cf.HSLA) format = cf.HSLA; else format = cf.RGBA; } return format; }, get colorHueOnly() { var rgba = WebInspector.Spectrum.hsvaToRGBA(this.hsv[0], 1, 1, 1); return WebInspector.Color.fromRGBA(rgba[0], rgba[1], rgba[2], rgba[3]); }, set displayText(text) { this._displayElement.textContent = text; }, _onchange: function() { this._updateUI(); this.dispatchEventToListeners(WebInspector.Spectrum.Events.ColorChanged, this.color); }, _updateHelperLocations: function() { var h = this.hsv[0]; var s = this.hsv[1]; var v = this.hsv[2]; // Where to show the little circle that displays your current selected color. var dragX = s * this.dragWidth; var dragY = this.dragHeight - (v * this.dragHeight); dragX = Math.max(-this._dragHelperElementHeight, Math.min(this.dragWidth - this._dragHelperElementHeight, dragX - this._dragHelperElementHeight)); dragY = Math.max(-this._dragHelperElementHeight, Math.min(this.dragHeight - this._dragHelperElementHeight, dragY - this._dragHelperElementHeight)); this._dragHelperElement.positionAt(dragX, dragY); // Where to show the bar that displays your current selected hue. var slideY = (h * this.slideHeight) - this.slideHelperHeight; this.slideHelper.style.top = slideY + "px"; this._alphaElement.value = this.hsv[3] * 100; }, _updateUI: function() { this._updateHelperLocations(); var rgb = (this.color.rgba || this.color.rgb).slice(0); if (rgb.length === 3) rgb[3] = 1; var rgbHueOnly = this.colorHueOnly.rgb; var flatColor = "rgb(" + rgbHueOnly[0] + ", " + rgbHueOnly[1] + ", " + rgbHueOnly[2] + ")"; var fullColor = "rgba(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ", " + rgb[3] + ")"; this._draggerElement.style.backgroundColor = flatColor; this._swatchInnerElement.style.backgroundColor = fullColor; this._alphaElement.value = this.hsv[3] * 100; }, wasShown: function() { this.slideHeight = this._sliderElement.offsetHeight; this.dragWidth = this._draggerElement.offsetWidth; this.dragHeight = this._draggerElement.offsetHeight; this._dragHelperElementHeight = this._dragHelperElement.offsetHeight / 2; this.slideHelperHeight = this.slideHelper.offsetHeight / 2; this._updateUI(); }, __proto__: WebInspector.View.prototype } /** * @constructor * @extends {WebInspector.Object} */ WebInspector.SpectrumPopupHelper = function() { this._spectrum = new WebInspector.Spectrum(); this._spectrum.element.addEventListener("keydown", this._onKeyDown.bind(this), false); this._popover = new WebInspector.Popover(); this._popover.setCanShrink(false); this._popover.element.addEventListener("mousedown", consumeEvent, false); this._hideProxy = this.hide.bind(this, true); } WebInspector.SpectrumPopupHelper.Events = { Hidden: "Hidden" }; WebInspector.SpectrumPopupHelper.prototype = { /** * @return {WebInspector.Spectrum} */ spectrum: function() { return this._spectrum; }, toggle: function(element, color, format) { if (this._popover.isShowing()) this.hide(true); else this.show(element, color, format); return this._popover.isShowing(); }, show: function(element, color, format) { if (this._popover.isShowing()) { if (this._anchorElement === element) return false; // Reopen the picker for another anchor element. this.hide(true); } this._anchorElement = element; this._spectrum.color = color; this._spectrum._originalFormat = format || color.format; this.reposition(element); document.addEventListener("mousedown", this._hideProxy, false); window.addEventListener("blur", this._hideProxy, false); return true; }, reposition: function(element) { if (!this._previousFocusElement) this._previousFocusElement = WebInspector.currentFocusElement(); this._popover.showView(this._spectrum, element); WebInspector.setCurrentFocusElement(this._spectrum.element); }, /** * @param {boolean=} commitEdit */ hide: function(commitEdit) { if (!this._popover.isShowing()) return; this._popover.hide(); document.removeEventListener("mousedown", this._hideProxy, false); window.removeEventListener("blur", this._hideProxy, false); this.dispatchEventToListeners(WebInspector.SpectrumPopupHelper.Events.Hidden, !!commitEdit); WebInspector.setCurrentFocusElement(this._previousFocusElement); delete this._previousFocusElement; delete this._anchorElement; }, _onKeyDown: function(event) { if (event.keyIdentifier === "Enter") { this.hide(true); event.consume(true); return; } if (event.keyIdentifier === "U+001B") { // Escape key this.hide(false); event.consume(true); } }, __proto__: WebInspector.Object.prototype } /** * @constructor */ WebInspector.ColorSwatch = function() { this.element = document.createElement("span"); this._swatchInnerElement = this.element.createChild("span", "swatch-inner"); this.element.title = WebInspector.UIString("Click to open a colorpicker. Shift-click to change color format"); this.element.className = "swatch"; this.element.addEventListener("mousedown", consumeEvent, false); this.element.addEventListener("dblclick", consumeEvent, false); } WebInspector.ColorSwatch.prototype = { /** * @param {string} colorString */ setColorString: function(colorString) { this._swatchInnerElement.style.backgroundColor = colorString; } }
JavaScript
WebInspector.RequestView = function(request) { WebInspector.View.call(this); this.registerRequiredCSS("resourceView.css"); this.element.addStyleClass("resource-view"); this.request = request; } WebInspector.RequestView.prototype = { hasContent: function() { return false; }, __proto__: WebInspector.View.prototype } WebInspector.RequestView.hasTextContent = function(request) { if (request.type.isTextType()) return true; if (request.type === WebInspector.resourceTypes.Other || request.hasErrorStatusCode()) return request.content && !request.contentEncoded; return false; } WebInspector.RequestView.nonSourceViewForRequest = function(request) { switch (request.type) { case WebInspector.resourceTypes.Image: return new WebInspector.ImageView(request); case WebInspector.resourceTypes.Font: return new WebInspector.FontView(request); default: return new WebInspector.RequestView(request); } } ; WebInspector.NetworkItemView = function(request) { WebInspector.TabbedPane.call(this); this.element.addStyleClass("network-item-view"); var headersView = new WebInspector.RequestHeadersView(request); this.appendTab("headers", WebInspector.UIString("Headers"), headersView); this.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); if (request.frames().length > 0) { var frameView = new WebInspector.ResourceWebSocketFrameView(request); this.appendTab("webSocketFrames", WebInspector.UIString("Frames"), frameView); return; } var responseView = new WebInspector.RequestResponseView(request); var previewView = new WebInspector.RequestPreviewView(request, responseView); this.appendTab("preview", WebInspector.UIString("Preview"), previewView); this.appendTab("response", WebInspector.UIString("Response"), responseView); if (request.requestCookies || request.responseCookies) { this._cookiesView = new WebInspector.RequestCookiesView(request); this.appendTab("cookies", WebInspector.UIString("Cookies"), this._cookiesView); } if (request.timing) { var timingView = new WebInspector.RequestTimingView(request); this.appendTab("timing", WebInspector.UIString("Timing"), timingView); } this._request = request; } WebInspector.NetworkItemView.prototype = { wasShown: function() { WebInspector.TabbedPane.prototype.wasShown.call(this); this._selectTab(); }, _selectTab: function(tabId) { if (!tabId) tabId = WebInspector.settings.resourceViewTab.get(); if (!this.selectTab(tabId)) { this._isInFallbackSelection = true; this.selectTab("headers"); delete this._isInFallbackSelection; } }, _tabSelected: function(event) { if (!event.data.isUserGesture) return; WebInspector.settings.resourceViewTab.set(event.data.tabId); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.NetworkRequestTabSelected, tab: event.data.tabId, url: this._request.url }); }, request: function() { return this._request; }, __proto__: WebInspector.TabbedPane.prototype } WebInspector.RequestContentView = function(request) { WebInspector.RequestView.call(this, request); } WebInspector.RequestContentView.prototype = { hasContent: function() { return true; }, get innerView() { return this._innerView; }, set innerView(innerView) { this._innerView = innerView; }, wasShown: function() { this._ensureInnerViewShown(); }, _ensureInnerViewShown: function() { if (this._innerViewShowRequested) return; this._innerViewShowRequested = true; function callback(content, contentEncoded, mimeType) { this._innerViewShowRequested = false; this.contentLoaded(); } this.request.requestContent(callback.bind(this)); }, contentLoaded: function() { }, canHighlightLine: function() { return this._innerView && this._innerView.canHighlightLine(); }, highlightLine: function(line) { if (this.canHighlightLine()) this._innerView.highlightLine(line); }, __proto__: WebInspector.RequestView.prototype } ; WebInspector.RequestCookiesView = function(request) { WebInspector.View.call(this); this.element.addStyleClass("resource-cookies-view"); this._request = request; request.addEventListener(WebInspector.NetworkRequest.Events.RequestHeadersChanged, this._refreshCookies, this); request.addEventListener(WebInspector.NetworkRequest.Events.ResponseHeadersChanged, this._refreshCookies, this); } WebInspector.RequestCookiesView.prototype = { wasShown: function() { if (!this._gotCookies) { if (!this._emptyView) { this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("This request has no cookies.")); this._emptyView.show(this.element); } return; } if (!this._cookiesTable) this._buildCookiesTable(); }, get _gotCookies() { return (this._request.requestCookies && this._request.requestCookies.length) || (this._request.responseCookies && this._request.responseCookies.length); }, _buildCookiesTable: function() { this.detachChildViews(); this._cookiesTable = new WebInspector.CookiesTable(true); this._cookiesTable.addCookiesFolder(WebInspector.UIString("Request Cookies"), this._request.requestCookies); this._cookiesTable.addCookiesFolder(WebInspector.UIString("Response Cookies"), this._request.responseCookies); this._cookiesTable.show(this.element); }, _refreshCookies: function() { delete this._cookiesTable; if (!this._gotCookies || !this.isShowing()) return; this._buildCookiesTable(); this._cookiesTable.updateWidths(); }, __proto__: WebInspector.View.prototype } ; WebInspector.RequestHeadersView = function(request) { WebInspector.View.call(this); this.registerRequiredCSS("resourceView.css"); this.element.addStyleClass("resource-headers-view"); this._request = request; this._headersListElement = document.createElement("ol"); this._headersListElement.className = "outline-disclosure"; this.element.appendChild(this._headersListElement); this._headersTreeOutline = new TreeOutline(this._headersListElement); this._headersTreeOutline.expandTreeElementsWhenArrowing = true; this._urlTreeElement = new TreeElement("", null, false); this._urlTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._urlTreeElement); this._requestMethodTreeElement = new TreeElement("", null, false); this._requestMethodTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._requestMethodTreeElement); this._statusCodeTreeElement = new TreeElement("", null, false); this._statusCodeTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._statusCodeTreeElement); this._requestHeadersTreeElement = new TreeElement("", null, true); this._requestHeadersTreeElement.expanded = true; this._requestHeadersTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._requestHeadersTreeElement); this._decodeRequestParameters = true; this._showRequestHeadersText = false; this._showResponseHeadersText = false; this._queryStringTreeElement = new TreeElement("", null, true); this._queryStringTreeElement.expanded = true; this._queryStringTreeElement.selectable = false; this._queryStringTreeElement.hidden = true; this._headersTreeOutline.appendChild(this._queryStringTreeElement); this._urlFragmentTreeElement = new TreeElement("", null, true); this._urlFragmentTreeElement.expanded = true; this._urlFragmentTreeElement.selectable = false; this._urlFragmentTreeElement.hidden = true; this._headersTreeOutline.appendChild(this._urlFragmentTreeElement); this._formDataTreeElement = new TreeElement("", null, true); this._formDataTreeElement.expanded = true; this._formDataTreeElement.selectable = false; this._formDataTreeElement.hidden = true; this._headersTreeOutline.appendChild(this._formDataTreeElement); this._requestPayloadTreeElement = new TreeElement(WebInspector.UIString("Request Payload"), null, true); this._requestPayloadTreeElement.expanded = true; this._requestPayloadTreeElement.selectable = false; this._requestPayloadTreeElement.hidden = true; this._headersTreeOutline.appendChild(this._requestPayloadTreeElement); this._responseHeadersTreeElement = new TreeElement("", null, true); this._responseHeadersTreeElement.expanded = true; this._responseHeadersTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._responseHeadersTreeElement); request.addEventListener(WebInspector.NetworkRequest.Events.RequestHeadersChanged, this._refreshRequestHeaders, this); request.addEventListener(WebInspector.NetworkRequest.Events.ResponseHeadersChanged, this._refreshResponseHeaders, this); request.addEventListener(WebInspector.NetworkRequest.Events.FinishedLoading, this._refreshHTTPInformation, this); this._refreshURL(); this._refreshQueryString(); this._refreshUrlFragment(); this._refreshRequestHeaders(); this._refreshResponseHeaders(); this._refreshHTTPInformation(); } WebInspector.RequestHeadersView.prototype = { _formatHeader: function(name, value) { var fragment = document.createDocumentFragment(); fragment.createChild("div", "header-name").textContent = name + ":"; fragment.createChild("div", "header-value source-code").textContent = value; return fragment; }, _formatParameter: function(value, className, decodeParameters) { var errorDecoding = false; if (decodeParameters) { value = value.replace(/\+/g, " "); if (value.indexOf("%") >= 0) { try { value = decodeURIComponent(value); } catch(e) { errorDecoding = true; } } } var div = document.createElement("div"); div.className = className; if (errorDecoding) div.createChild("span", "error-message").textContent = WebInspector.UIString("(unable to decode value)"); else div.textContent = value; return div; }, _refreshURL: function() { this._urlTreeElement.title = this._formatHeader(WebInspector.UIString("Request URL"), this._request.url); }, _refreshQueryString: function() { var queryString = this._request.queryString(); var queryParameters = this._request.queryParameters; this._queryStringTreeElement.hidden = !queryParameters; if (queryParameters) this._refreshParams(WebInspector.UIString("Query String Parameters"), queryParameters, queryString, this._queryStringTreeElement); }, _refreshUrlFragment: function() { var urlFragment = this._request.parsedURL.fragment; this._urlFragmentTreeElement.hidden = !urlFragment; if (!urlFragment) return; var sectionTitle = WebInspector.UIString("URL fragment"); this._urlFragmentTreeElement.removeChildren(); this._urlFragmentTreeElement.listItemElement.removeChildren(); this._urlFragmentTreeElement.listItemElement.appendChild(document.createTextNode(sectionTitle)); var fragmentTreeElement = new TreeElement(null, null, false); fragmentTreeElement.title = this._formatHeader("#", urlFragment); fragmentTreeElement.selectable = false; this._urlFragmentTreeElement.appendChild(fragmentTreeElement); }, _refreshFormData: function() { this._formDataTreeElement.hidden = true; this._requestPayloadTreeElement.hidden = true; var formData = this._request.requestFormData; if (!formData) return; var formParameters = this._request.formParameters; if (formParameters) { this._formDataTreeElement.hidden = false; this._refreshParams(WebInspector.UIString("Form Data"), formParameters, formData, this._formDataTreeElement); } else { this._requestPayloadTreeElement.hidden = false; this._populateTreeElementWithSourceText(this._requestPayloadTreeElement, formData) } }, _populateTreeElementWithSourceText: function(treeElement, sourceText) { treeElement.removeChildren(); var sourceTreeElement = new TreeElement(null, null, false); sourceTreeElement.selectable = false; treeElement.appendChild(sourceTreeElement); var sourceTextElement = document.createElement("span"); sourceTextElement.addStyleClass("header-value"); sourceTextElement.addStyleClass("source-code"); sourceTextElement.textContent = String(sourceText).trim(); sourceTreeElement.listItemElement.appendChild(sourceTextElement); }, _refreshParams: function(title, params, sourceText, paramsTreeElement) { paramsTreeElement.removeChildren(); paramsTreeElement.listItemElement.removeChildren(); paramsTreeElement.listItemElement.appendChild(document.createTextNode(title)); var headerCount = document.createElement("span"); headerCount.addStyleClass("header-count"); headerCount.textContent = WebInspector.UIString(" (%d)", params.length); paramsTreeElement.listItemElement.appendChild(headerCount); function toggleViewSource() { paramsTreeElement._viewSource = !paramsTreeElement._viewSource; this._refreshParams(title, params, sourceText, paramsTreeElement); } var viewSourceToggleTitle = paramsTreeElement._viewSource ? WebInspector.UIString("view parsed") : WebInspector.UIString("view source"); var viewSourceToggleButton = this._createToggleButton(viewSourceToggleTitle); viewSourceToggleButton.addEventListener("click", toggleViewSource.bind(this)); paramsTreeElement.listItemElement.appendChild(viewSourceToggleButton); if (paramsTreeElement._viewSource) { this._populateTreeElementWithSourceText(paramsTreeElement, sourceText); return; } var toggleTitle = this._decodeRequestParameters ? WebInspector.UIString("view URL encoded") : WebInspector.UIString("view decoded"); var toggleButton = this._createToggleButton(toggleTitle); toggleButton.addEventListener("click", this._toggleURLDecoding.bind(this)); paramsTreeElement.listItemElement.appendChild(toggleButton); for (var i = 0; i < params.length; ++i) { var paramNameValue = document.createDocumentFragment(); var name = this._formatParameter(params[i].name + ":", "header-name", this._decodeRequestParameters); var value = this._formatParameter(params[i].value, "header-value source-code", this._decodeRequestParameters); paramNameValue.appendChild(name); paramNameValue.appendChild(value); var parmTreeElement = new TreeElement(paramNameValue, null, false); parmTreeElement.selectable = false; paramsTreeElement.appendChild(parmTreeElement); } }, _toggleURLDecoding: function(event) { this._decodeRequestParameters = !this._decodeRequestParameters; this._refreshQueryString(); this._refreshFormData(); }, _getHeaderValue: function(headers, key) { var lowerKey = key.toLowerCase(); for (var testKey in headers) { if (testKey.toLowerCase() === lowerKey) return headers[testKey]; } }, _refreshRequestHeaders: function() { var additionalRow = null; if (typeof this._request.webSocketRequestKey3 !== "undefined") additionalRow = {name: "(Key3)", value: this._request.webSocketRequestKey3}; if (this._showRequestHeadersText) this._refreshHeadersText(WebInspector.UIString("Request Headers"), this._request.sortedRequestHeaders, this._request.requestHeadersText, this._requestHeadersTreeElement); else this._refreshHeaders(WebInspector.UIString("Request Headers"), this._request.sortedRequestHeaders, additionalRow, this._requestHeadersTreeElement); if (this._request.requestHeadersText) { var toggleButton = this._createHeadersToggleButton(this._showRequestHeadersText); toggleButton.addEventListener("click", this._toggleRequestHeadersText.bind(this)); this._requestHeadersTreeElement.listItemElement.appendChild(toggleButton); } this._refreshFormData(); }, _refreshResponseHeaders: function() { var additionalRow = null; if (typeof this._request.webSocketChallengeResponse !== "undefined") additionalRow = {name: "(Challenge Response)", value: this._request.webSocketChallengeResponse}; if (this._showResponseHeadersText) this._refreshHeadersText(WebInspector.UIString("Response Headers"), this._request.sortedResponseHeaders, this._request.responseHeadersText, this._responseHeadersTreeElement); else this._refreshHeaders(WebInspector.UIString("Response Headers"), this._request.sortedResponseHeaders, additionalRow, this._responseHeadersTreeElement); if (this._request.responseHeadersText) { var toggleButton = this._createHeadersToggleButton(this._showResponseHeadersText); toggleButton.addEventListener("click", this._toggleResponseHeadersText.bind(this)); this._responseHeadersTreeElement.listItemElement.appendChild(toggleButton); } }, _refreshHTTPInformation: function() { var requestMethodElement = this._requestMethodTreeElement; requestMethodElement.hidden = !this._request.statusCode; var statusCodeElement = this._statusCodeTreeElement; statusCodeElement.hidden = !this._request.statusCode; if (this._request.statusCode) { var statusImageSource = ""; if (this._request.statusCode < 300 || this._request.statusCode === 304) statusImageSource = "Images/successGreenDot.png"; else if (this._request.statusCode < 400) statusImageSource = "Images/warningOrangeDot.png"; else statusImageSource = "Images/errorRedDot.png"; requestMethodElement.title = this._formatHeader(WebInspector.UIString("Request Method"), this._request.requestMethod); var statusCodeFragment = document.createDocumentFragment(); statusCodeFragment.createChild("div", "header-name").textContent = WebInspector.UIString("Status Code") + ":"; var statusCodeImage = statusCodeFragment.createChild("img", "resource-status-image"); statusCodeImage.src = statusImageSource; statusCodeImage.title = this._request.statusCode + " " + this._request.statusText; var value = statusCodeFragment.createChild("div", "header-value source-code"); value.textContent = this._request.statusCode + " " + this._request.statusText; if (this._request.cached) value.createChild("span", "status-from-cache").textContent = " " + WebInspector.UIString("(from cache)"); statusCodeElement.title = statusCodeFragment; } }, _refreshHeadersTitle: function(title, headersTreeElement, headersLength) { headersTreeElement.listItemElement.removeChildren(); headersTreeElement.listItemElement.appendChild(document.createTextNode(title)); var headerCount = document.createElement("span"); headerCount.addStyleClass("header-count"); headerCount.textContent = WebInspector.UIString(" (%d)", headersLength); headersTreeElement.listItemElement.appendChild(headerCount); }, _refreshHeaders: function(title, headers, additionalRow, headersTreeElement) { headersTreeElement.removeChildren(); var length = headers.length; this._refreshHeadersTitle(title, headersTreeElement, length); headersTreeElement.hidden = !length; for (var i = 0; i < length; ++i) { var headerTreeElement = new TreeElement(null, null, false); headerTreeElement.title = this._formatHeader(headers[i].name, headers[i].value); headerTreeElement.selectable = false; headersTreeElement.appendChild(headerTreeElement); } if (additionalRow) { var headerTreeElement = new TreeElement(null, null, false); headerTreeElement.title = this._formatHeader(additionalRow.name, additionalRow.value); headerTreeElement.selectable = false; headersTreeElement.appendChild(headerTreeElement); } }, _refreshHeadersText: function(title, headers, headersText, headersTreeElement) { this._populateTreeElementWithSourceText(headersTreeElement, headersText); this._refreshHeadersTitle(title, headersTreeElement, headers.length); }, _toggleRequestHeadersText: function(event) { this._showRequestHeadersText = !this._showRequestHeadersText; this._refreshRequestHeaders(); }, _toggleResponseHeadersText: function(event) { this._showResponseHeadersText = !this._showResponseHeadersText; this._refreshResponseHeaders(); }, _createToggleButton: function(title) { var button = document.createElement("span"); button.addStyleClass("header-toggle"); button.textContent = title; return button; }, _createHeadersToggleButton: function(isHeadersTextShown) { var toggleTitle = isHeadersTextShown ? WebInspector.UIString("view parsed") : WebInspector.UIString("view source"); return this._createToggleButton(toggleTitle); }, __proto__: WebInspector.View.prototype } ; WebInspector.RequestHTMLView = function(request, dataURL) { WebInspector.RequestView.call(this, request); this._dataURL = dataURL; this.element.addStyleClass("html"); } WebInspector.RequestHTMLView.prototype = { hasContent: function() { return true; }, wasShown: function() { this._createIFrame(); }, willHide: function(parentElement) { this.element.removeChildren(); }, _createIFrame: function() { this.element.removeChildren(); var iframe = document.createElement("iframe"); iframe.setAttribute("sandbox", ""); iframe.setAttribute("src", this._dataURL); this.element.appendChild(iframe); }, __proto__: WebInspector.RequestView.prototype } ; WebInspector.RequestJSONView = function(request, parsedJSON) { WebInspector.RequestView.call(this, request); this._parsedJSON = parsedJSON; this.element.addStyleClass("json"); } WebInspector.RequestJSONView.parseJSON = function(text) { var prefix = ""; var start = /[{[]/.exec(text); if (start && start.index) { prefix = text.substring(0, start.index); text = text.substring(start.index); } try { return new WebInspector.ParsedJSON(JSON.parse(text), prefix, ""); } catch (e) { return; } } WebInspector.RequestJSONView.parseJSONP = function(text) { var start = text.indexOf("("); var end = text.lastIndexOf(")"); if (start == -1 || end == -1 || end < start) return; var prefix = text.substring(0, start + 1); var suffix = text.substring(end); text = text.substring(start + 1, end); try { return new WebInspector.ParsedJSON(JSON.parse(text), prefix, suffix); } catch (e) { return; } } WebInspector.RequestJSONView.prototype = { hasContent: function() { return true; }, wasShown: function() { this._initialize(); }, _initialize: function() { if (this._initialized) return; this._initialized = true; var obj = WebInspector.RemoteObject.fromLocalObject(this._parsedJSON.data); var title = this._parsedJSON.prefix + obj.description + this._parsedJSON.suffix; var section = new WebInspector.ObjectPropertiesSection(obj, title); section.expand(); section.editable = false; this.element.appendChild(section.element); }, __proto__: WebInspector.RequestView.prototype } WebInspector.ParsedJSON = function(data, prefix, suffix) { this.data = data; this.prefix = prefix; this.suffix = suffix; } ; WebInspector.RequestPreviewView = function(request, responseView) { WebInspector.RequestContentView.call(this, request); this._responseView = responseView; } WebInspector.RequestPreviewView.prototype = { contentLoaded: function() { if (!this.request.content) { if (!this._emptyView) { this._emptyView = this._createEmptyView(); this._emptyView.show(this.element); this.innerView = this._emptyView; } } else { if (this._emptyView) { this._emptyView.detach(); delete this._emptyView; } if (!this._previewView) this._previewView = this._createPreviewView(); this._previewView.show(this.element); this.innerView = this._previewView; } }, _createEmptyView: function() { return new WebInspector.EmptyView(WebInspector.UIString("This request has no preview available.")); }, _jsonView: function() { var parsedJSON = WebInspector.RequestJSONView.parseJSON(this.request.content); if (parsedJSON) return new WebInspector.RequestJSONView(this.request, parsedJSON); }, _htmlView: function() { var dataURL = this.request.asDataURL(); if (dataURL !== null) return new WebInspector.RequestHTMLView(this.request, dataURL); }, _createPreviewView: function() { if (this.request.content) { if (this.request.hasErrorStatusCode()) { var htmlView = this._htmlView(); if (htmlView) return htmlView; } if (this.request.type === WebInspector.resourceTypes.XHR) { var jsonView = this._jsonView(); if (jsonView) return jsonView; } if (this.request.type === WebInspector.resourceTypes.XHR && this.request.mimeType === "text/html") { var htmlView = this._htmlView(); if (htmlView) return htmlView; } if (this.request.type === WebInspector.resourceTypes.Script && this.request.mimeType === "application/json") { var jsonView = this._jsonView(); if (jsonView) return jsonView; } } if (this._responseView.sourceView) return this._responseView.sourceView; if (this.request.type === WebInspector.resourceTypes.Other) return this._createEmptyView(); return WebInspector.RequestView.nonSourceViewForRequest(this.request); }, __proto__: WebInspector.RequestContentView.prototype } ; WebInspector.RequestResponseView = function(request) { WebInspector.RequestContentView.call(this, request); } WebInspector.RequestResponseView.prototype = { get sourceView() { if (!this._sourceView && WebInspector.RequestView.hasTextContent(this.request)) this._sourceView = new WebInspector.ResourceSourceFrame(this.request); return this._sourceView; }, contentLoaded: function() { if (!this.request.content || !this.sourceView) { if (!this._emptyView) { this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("This request has no response data available.")); this._emptyView.show(this.element); this.innerView = this._emptyView; } } else { if (this._emptyView) { this._emptyView.detach(); delete this._emptyView; } this.sourceView.show(this.element); this.innerView = this.sourceView; } }, __proto__: WebInspector.RequestContentView.prototype } ; WebInspector.RequestTimingView = function(request) { WebInspector.View.call(this); this.element.addStyleClass("resource-timing-view"); this._request = request; request.addEventListener(WebInspector.NetworkRequest.Events.TimingChanged, this._refresh, this); } WebInspector.RequestTimingView.prototype = { wasShown: function() { if (!this._request.timing) { if (!this._emptyView) { this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("This request has no detailed timing info.")); this._emptyView.show(this.element); this.innerView = this._emptyView; } return; } if (this._emptyView) { this._emptyView.detach(); delete this._emptyView; } this._refresh(); }, _refresh: function() { if (this._tableElement) this._tableElement.parentElement.removeChild(this._tableElement); this._tableElement = WebInspector.RequestTimingView.createTimingTable(this._request); this.element.appendChild(this._tableElement); }, __proto__: WebInspector.View.prototype } WebInspector.RequestTimingView.createTimingTable = function(request) { var tableElement = document.createElement("table"); var rows = []; function addRow(title, className, start, end) { var row = {}; row.title = title; row.className = className; row.start = start; row.end = end; rows.push(row); } if (request.timing.proxyStart !== -1) addRow(WebInspector.UIString("Proxy"), "proxy", request.timing.proxyStart, request.timing.proxyEnd); if (request.timing.dnsStart !== -1) addRow(WebInspector.UIString("DNS Lookup"), "dns", request.timing.dnsStart, request.timing.dnsEnd); if (request.timing.connectStart !== -1) { if (request.connectionReused) addRow(WebInspector.UIString("Blocking"), "connecting", request.timing.connectStart, request.timing.connectEnd); else { var connectStart = request.timing.connectStart; if (request.timing.dnsStart !== -1) connectStart += request.timing.dnsEnd - request.timing.dnsStart; addRow(WebInspector.UIString("Connecting"), "connecting", connectStart, request.timing.connectEnd); } } if (request.timing.sslStart !== -1) addRow(WebInspector.UIString("SSL"), "ssl", request.timing.sslStart, request.timing.sslEnd); var sendStart = request.timing.sendStart; if (request.timing.sslStart !== -1) sendStart += request.timing.sslEnd - request.timing.sslStart; addRow(WebInspector.UIString("Sending"), "sending", request.timing.sendStart, request.timing.sendEnd); addRow(WebInspector.UIString("Waiting"), "waiting", request.timing.sendEnd, request.timing.receiveHeadersEnd); addRow(WebInspector.UIString("Receiving"), "receiving", (request.responseReceivedTime - request.timing.requestTime) * 1000, (request.endTime - request.timing.requestTime) * 1000); const chartWidth = 200; var total = (request.endTime - request.timing.requestTime) * 1000; var scale = chartWidth / total; for (var i = 0; i < rows.length; ++i) { var tr = document.createElement("tr"); tableElement.appendChild(tr); var td = document.createElement("td"); td.textContent = rows[i].title; tr.appendChild(td); td = document.createElement("td"); td.width = chartWidth + "px"; var row = document.createElement("div"); row.className = "network-timing-row"; td.appendChild(row); var bar = document.createElement("span"); bar.className = "network-timing-bar " + rows[i].className; bar.style.left = scale * rows[i].start + "px"; bar.style.right = scale * (total - rows[i].end) + "px"; bar.style.backgroundColor = rows[i].color; bar.textContent = "\u200B"; row.appendChild(bar); var title = document.createElement("span"); title.className = "network-timing-bar-title"; if (total - rows[i].end < rows[i].start) title.style.right = (scale * (total - rows[i].end) + 3) + "px"; else title.style.left = (scale * rows[i].start + 3) + "px"; title.textContent = Number.secondsToString((rows[i].end - rows[i].start) / 1000); row.appendChild(title); tr.appendChild(td); } return tableElement; } ; WebInspector.ResourceWebSocketFrameView = function(resource) { WebInspector.View.call(this); this.element.addStyleClass("resource-websocket"); this.resource = resource; this.element.removeChildren(); var dataGrid = new WebInspector.DataGrid({ data: {title: WebInspector.UIString("Data"), sortable: false}, length: {title: WebInspector.UIString("Length"), sortable: false, aligned: "right", width: "50px"}, time: {title: WebInspector.UIString("Time"), width: "70px"} }); var frames = this.resource.frames(); for (var i = 0; i < frames.length; i++) { var payload = frames[i]; var date = new Date(payload.time * 1000); var row = { data: "", length: payload.payloadData.length.toString(), time: date.toLocaleTimeString() }; var rowClass = ""; if (payload.errorMessage) { rowClass = "error"; row.data = payload.errorMessage; } else if (payload.opcode == WebInspector.ResourceWebSocketFrameView.OpCodes.TextFrame) { if (payload.sent) rowClass = "outcoming"; row.data = payload.payloadData; } else { rowClass = "opcode"; var opcodeMeaning = ""; switch (payload.opcode) { case WebInspector.ResourceWebSocketFrameView.OpCodes.ContinuationFrame: opcodeMeaning = WebInspector.UIString("Continuation Frame"); break; case WebInspector.ResourceWebSocketFrameView.OpCodes.BinaryFrame: opcodeMeaning = WebInspector.UIString("Binary Frame"); break; case WebInspector.ResourceWebSocketFrameView.OpCodes.ConnectionCloseFrame: opcodeMeaning = WebInspector.UIString("Connection Close Frame"); break; case WebInspector.ResourceWebSocketFrameView.OpCodes.PingFrame: opcodeMeaning = WebInspector.UIString("Ping Frame"); break; case WebInspector.ResourceWebSocketFrameView.OpCodes.PongFrame: opcodeMeaning = WebInspector.UIString("Pong Frame"); break; } row.data = WebInspector.UIString("%s (Opcode %d%s)", opcodeMeaning, payload.opcode, (payload.mask ? ", mask" : "")); } var node = new WebInspector.DataGridNode(row, false); dataGrid.rootNode().appendChild(node); if (rowClass) node.element.classList.add("resource-websocket-row-" + rowClass); } dataGrid.show(this.element); } WebInspector.ResourceWebSocketFrameView.OpCodes = { ContinuationFrame: 0, TextFrame: 1, BinaryFrame: 2, ConnectionCloseFrame: 8, PingFrame: 9, PongFrame: 10 }; WebInspector.ResourceWebSocketFrameView.prototype = { __proto__: WebInspector.View.prototype } ; WebInspector.NetworkLogView = function() { WebInspector.View.call(this); this.registerRequiredCSS("networkLogView.css"); this._allowRequestSelection = false; this._requests = []; this._requestsById = {}; this._requestsByURL = {}; this._staleRequests = {}; this._requestGridNodes = {}; this._lastRequestGridNodeId = 0; this._mainRequestLoadTime = -1; this._mainRequestDOMContentTime = -1; this._hiddenCategories = {}; this._matchedRequests = []; this._highlightedSubstringChanges = []; this._filteredOutRequests = new Map(); this._matchedRequestsMap = {}; this._currentMatchedRequestIndex = -1; this._createStatusbarButtons(); this._createStatusBarItems(); this._linkifier = new WebInspector.Linkifier(); WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestStarted, this._onRequestStarted, this); WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestUpdated, this._onRequestUpdated, this); WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestFinished, this._onRequestUpdated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.OnLoad, this._onLoadEventFired, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.DOMContentLoaded, this._domContentLoadedEventFired, this); this._initializeView(); function onCanClearBrowserCache(error, result) { this._canClearBrowserCache = result; } NetworkAgent.canClearBrowserCache(onCanClearBrowserCache.bind(this)); function onCanClearBrowserCookies(error, result) { this._canClearBrowserCookies = result; } NetworkAgent.canClearBrowserCookies(onCanClearBrowserCookies.bind(this)); WebInspector.networkLog.requests.forEach(this._appendRequest.bind(this)); } WebInspector.NetworkLogView.prototype = { _initializeView: function() { this.element.id = "network-container"; this._createSortingFunctions(); this._createTable(); this._createTimelineGrid(); this._createSummaryBar(); if (!this.useLargeRows) this._setLargerRequests(this.useLargeRows); this._allowPopover = true; this._popoverHelper = new WebInspector.PopoverHelper(this.element, this._getPopoverAnchor.bind(this), this._showPopover.bind(this)); this._popoverHelper.setTimeout(100); this.calculator = new WebInspector.NetworkTransferTimeCalculator(); this._filter(this._filterAllElement, false); this.switchToDetailedView(); }, get statusBarItems() { return [this._largerRequestsButton.element, this._preserveLogToggle.element, this._clearButton.element, this._filterBarElement, this._progressBarContainer]; }, get useLargeRows() { return WebInspector.settings.resourcesLargeRows.get(); }, set allowPopover(flag) { this._allowPopover = flag; }, elementsToRestoreScrollPositionsFor: function() { if (!this._dataGrid) return []; return [this._dataGrid.scrollContainer]; }, onResize: function() { this._updateOffscreenRows(); }, _createTimelineGrid: function() { this._timelineGrid = new WebInspector.TimelineGrid(); this._timelineGrid.element.addStyleClass("network-timeline-grid"); this._dataGrid.element.appendChild(this._timelineGrid.element); }, _createTable: function() { var columns = {name: {}, method: {}, status: {}, type: {}, initiator: {}, size: {}, time: {}, timeline: {}}; columns.name.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Name"), WebInspector.UIString("Path")); columns.name.sortable = true; columns.name.width = "20%"; columns.name.disclosure = true; columns.method.title = WebInspector.UIString("Method"); columns.method.sortable = true; columns.method.width = "6%"; columns.status.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Status"), WebInspector.UIString("Text")); columns.status.sortable = true; columns.status.width = "6%"; columns.type.title = WebInspector.UIString("Type"); columns.type.sortable = true; columns.type.width = "6%"; columns.initiator.title = WebInspector.UIString("Initiator"); columns.initiator.sortable = true; columns.initiator.width = "10%"; columns.size.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Size"), WebInspector.UIString("Content")); columns.size.sortable = true; columns.size.width = "6%"; columns.size.aligned = "right"; columns.time.titleDOMFragment = this._makeHeaderFragment(WebInspector.UIString("Time"), WebInspector.UIString("Latency")); columns.time.sortable = true; columns.time.width = "6%"; columns.time.aligned = "right"; columns.timeline.title = ""; columns.timeline.sortable = false; columns.timeline.width = "40%"; columns.timeline.sort = "ascending"; this._dataGrid = new WebInspector.DataGrid(columns); this._dataGrid.resizeMethod = WebInspector.DataGrid.ResizeMethod.Last; this._dataGrid.element.addStyleClass("network-log-grid"); this._dataGrid.element.addEventListener("contextmenu", this._contextMenu.bind(this), true); this._dataGrid.show(this.element); this._dataGrid.addEventListener("sorting changed", this._sortItems, this); this._dataGrid.addEventListener("width changed", this._updateDividersIfNeeded, this); this._dataGrid.scrollContainer.addEventListener("scroll", this._updateOffscreenRows.bind(this)); this._patchTimelineHeader(); }, _makeHeaderFragment: function(title, subtitle) { var fragment = document.createDocumentFragment(); fragment.appendChild(document.createTextNode(title)); var subtitleDiv = document.createElement("div"); subtitleDiv.className = "network-header-subtitle"; subtitleDiv.textContent = subtitle; fragment.appendChild(subtitleDiv); return fragment; }, _patchTimelineHeader: function() { var timelineSorting = document.createElement("select"); var option = document.createElement("option"); option.value = "startTime"; option.label = WebInspector.UIString("Timeline"); timelineSorting.appendChild(option); option = document.createElement("option"); option.value = "startTime"; option.label = WebInspector.UIString("Start Time"); timelineSorting.appendChild(option); option = document.createElement("option"); option.value = "responseTime"; option.label = WebInspector.UIString("Response Time"); timelineSorting.appendChild(option); option = document.createElement("option"); option.value = "endTime"; option.label = WebInspector.UIString("End Time"); timelineSorting.appendChild(option); option = document.createElement("option"); option.value = "duration"; option.label = WebInspector.UIString("Duration"); timelineSorting.appendChild(option); option = document.createElement("option"); option.value = "latency"; option.label = WebInspector.UIString("Latency"); timelineSorting.appendChild(option); var header = this._dataGrid.headerTableHeader("timeline"); header.replaceChild(timelineSorting, header.firstChild); timelineSorting.addEventListener("click", function(event) { event.consume() }, false); timelineSorting.addEventListener("change", this._sortByTimeline.bind(this), false); this._timelineSortSelector = timelineSorting; }, _createSortingFunctions: function() { this._sortingFunctions = {}; this._sortingFunctions.name = WebInspector.NetworkDataGridNode.NameComparator; this._sortingFunctions.method = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "method", false); this._sortingFunctions.status = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "statusCode", false); this._sortingFunctions.type = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "mimeType", false); this._sortingFunctions.initiator = WebInspector.NetworkDataGridNode.InitiatorComparator; this._sortingFunctions.size = WebInspector.NetworkDataGridNode.SizeComparator; this._sortingFunctions.time = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "duration", false); this._sortingFunctions.timeline = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "startTime", false); this._sortingFunctions.startTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "startTime", false); this._sortingFunctions.endTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "endTime", false); this._sortingFunctions.responseTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "responseReceivedTime", false); this._sortingFunctions.duration = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "duration", true); this._sortingFunctions.latency = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "latency", true); var timeCalculator = new WebInspector.NetworkTransferTimeCalculator(); var durationCalculator = new WebInspector.NetworkTransferDurationCalculator(); this._calculators = {}; this._calculators.timeline = timeCalculator; this._calculators.startTime = timeCalculator; this._calculators.endTime = timeCalculator; this._calculators.responseTime = timeCalculator; this._calculators.duration = durationCalculator; this._calculators.latency = durationCalculator; }, _sortItems: function() { this._removeAllNodeHighlights(); var columnIdentifier = this._dataGrid.sortColumnIdentifier; if (columnIdentifier === "timeline") { this._sortByTimeline(); return; } var sortingFunction = this._sortingFunctions[columnIdentifier]; if (!sortingFunction) return; this._dataGrid.sortNodes(sortingFunction, this._dataGrid.sortOrder === "descending"); this._timelineSortSelector.selectedIndex = 0; this._updateOffscreenRows(); this.searchCanceled(); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.NetworkSort, column: columnIdentifier, sortOrder: this._dataGrid.sortOrder }); }, _sortByTimeline: function() { this._removeAllNodeHighlights(); var selectedIndex = this._timelineSortSelector.selectedIndex; if (!selectedIndex) selectedIndex = 1; var selectedOption = this._timelineSortSelector[selectedIndex]; var value = selectedOption.value; var sortingFunction = this._sortingFunctions[value]; this._dataGrid.sortNodes(sortingFunction); this.calculator = this._calculators[value]; if (this.calculator.startAtZero) this._timelineGrid.hideEventDividers(); else this._timelineGrid.showEventDividers(); this._dataGrid.markColumnAsSortedBy("timeline", "ascending"); this._updateOffscreenRows(); }, _createStatusBarItems: function() { var filterBarElement = document.createElement("div"); filterBarElement.className = "scope-bar status-bar-item"; function createFilterElement(typeName, label) { var categoryElement = document.createElement("li"); categoryElement.typeName = typeName; categoryElement.className = typeName; categoryElement.appendChild(document.createTextNode(label)); categoryElement.addEventListener("click", this._updateFilter.bind(this), false); filterBarElement.appendChild(categoryElement); return categoryElement; } this._filterAllElement = createFilterElement.call(this, "all", WebInspector.UIString("All")); var dividerElement = document.createElement("div"); dividerElement.addStyleClass("scope-bar-divider"); filterBarElement.appendChild(dividerElement); for (var typeId in WebInspector.resourceTypes) { var type = WebInspector.resourceTypes[typeId]; createFilterElement.call(this, type.name(), type.categoryTitle()); } this._filterBarElement = filterBarElement; this._progressBarContainer = document.createElement("div"); this._progressBarContainer.className = "status-bar-item"; }, _createSummaryBar: function() { var tbody = this._dataGrid.dataTableBody; var tfoot = document.createElement("tfoot"); var tr = tfoot.createChild("tr", "revealed network-summary-bar"); var td = tr.createChild("td"); td.setAttribute("colspan", 7); tbody.parentNode.insertBefore(tfoot, tbody); this._summaryBarElement = td; }, _updateSummaryBar: function() { var requestsNumber = this._requests.length; if (!requestsNumber) { if (this._summaryBarElement._isDisplayingWarning) return; this._summaryBarElement._isDisplayingWarning = true; var img = document.createElement("img"); img.src = "Images/warningIcon.png"; this._summaryBarElement.removeChildren(); this._summaryBarElement.appendChild(img); this._summaryBarElement.appendChild(document.createTextNode( WebInspector.UIString("No requests captured. Reload the page to see detailed information on the network activity."))); return; } delete this._summaryBarElement._isDisplayingWarning; var transferSize = 0; var selectedRequestsNumber = 0; var selectedTransferSize = 0; var baseTime = -1; var maxTime = -1; for (var i = 0; i < this._requests.length; ++i) { var request = this._requests[i]; var requestTransferSize = (request.cached || !request.transferSize) ? 0 : request.transferSize; transferSize += requestTransferSize; if ((!this._hiddenCategories.all || !this._hiddenCategories[request.type.name()]) && !this._filteredOutRequests.get(request)) { selectedRequestsNumber++; selectedTransferSize += requestTransferSize; } if (request.url === WebInspector.inspectedPageURL) baseTime = request.startTime; if (request.endTime > maxTime) maxTime = request.endTime; } var text = ""; if (selectedRequestsNumber !== requestsNumber) { text += String.sprintf(WebInspector.UIString("%d / %d requests"), selectedRequestsNumber, requestsNumber); text += " \u2758 " + String.sprintf(WebInspector.UIString("%s / %s transferred"), Number.bytesToString(selectedTransferSize), Number.bytesToString(transferSize)); } else { text += String.sprintf(WebInspector.UIString("%d requests"), requestsNumber); text += " \u2758 " + String.sprintf(WebInspector.UIString("%s transferred"), Number.bytesToString(transferSize)); } if (baseTime !== -1 && this._mainRequestLoadTime !== -1 && this._mainRequestDOMContentTime !== -1 && this._mainRequestDOMContentTime > baseTime) { text += " \u2758 " + String.sprintf(WebInspector.UIString("%s (onload: %s, DOMContentLoaded: %s)"), Number.secondsToString(maxTime - baseTime), Number.secondsToString(this._mainRequestLoadTime - baseTime), Number.secondsToString(this._mainRequestDOMContentTime - baseTime)); } this._summaryBarElement.textContent = text; }, _showCategory: function(typeName) { this._dataGrid.element.addStyleClass("filter-" + typeName); delete this._hiddenCategories[typeName]; }, _hideCategory: function(typeName) { this._dataGrid.element.removeStyleClass("filter-" + typeName); this._hiddenCategories[typeName] = true; }, _updateFilter: function(e) { this._removeAllNodeHighlights(); var isMac = WebInspector.isMac(); var selectMultiple = false; if (isMac && e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey) selectMultiple = true; if (!isMac && e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey) selectMultiple = true; this._filter(e.target, selectMultiple); this.searchCanceled(); this._updateSummaryBar(); }, _filter: function(target, selectMultiple) { function unselectAll() { for (var i = 0; i < this._filterBarElement.childNodes.length; ++i) { var child = this._filterBarElement.childNodes[i]; if (!child.typeName) continue; child.removeStyleClass("selected"); this._hideCategory(child.typeName); } } if (target === this._filterAllElement) { if (target.hasStyleClass("selected")) { return; } unselectAll.call(this); } else { if (this._filterAllElement.hasStyleClass("selected")) { this._filterAllElement.removeStyleClass("selected"); this._hideCategory("all"); } } if (!selectMultiple) { unselectAll.call(this); target.addStyleClass("selected"); this._showCategory(target.typeName); this._updateOffscreenRows(); return; } if (target.hasStyleClass("selected")) { target.removeStyleClass("selected"); this._hideCategory(target.typeName); } else { target.addStyleClass("selected"); this._showCategory(target.typeName); } this._updateOffscreenRows(); }, _defaultRefreshDelay: 500, _scheduleRefresh: function() { if (this._needsRefresh) return; this._needsRefresh = true; if (this.isShowing() && !this._refreshTimeout) this._refreshTimeout = setTimeout(this.refresh.bind(this), this._defaultRefreshDelay); }, _updateDividersIfNeeded: function() { if (!this._dataGrid) return; var timelineColumn = this._dataGrid.columns.timeline; for (var i = 0; i < this._dataGrid.resizers.length; ++i) { if (timelineColumn.ordinal === this._dataGrid.resizers[i].rightNeighboringColumnID) { this._timelineGrid.element.style.left = this._dataGrid.resizers[i].style.left; this._timelineGrid.element.style.right = "18px"; } } var proceed = true; if (!this.isShowing()) { this._scheduleRefresh(); proceed = false; } else { this.calculator.setDisplayWindow(this._timelineGrid.element.clientWidth); proceed = this._timelineGrid.updateDividers(this.calculator); } if (!proceed) return; if (this.calculator.startAtZero || !this.calculator.computePercentageFromEventTime) { return; } this._timelineGrid.removeEventDividers(); if (this._mainRequestLoadTime !== -1) { var percent = this.calculator.computePercentageFromEventTime(this._mainRequestLoadTime); var loadDivider = document.createElement("div"); loadDivider.className = "network-event-divider network-red-divider"; var loadDividerPadding = document.createElement("div"); loadDividerPadding.className = "network-event-divider-padding"; loadDividerPadding.title = WebInspector.UIString("Load event fired"); loadDividerPadding.appendChild(loadDivider); loadDividerPadding.style.left = percent + "%"; this._timelineGrid.addEventDivider(loadDividerPadding); } if (this._mainRequestDOMContentTime !== -1) { var percent = this.calculator.computePercentageFromEventTime(this._mainRequestDOMContentTime); var domContentDivider = document.createElement("div"); domContentDivider.className = "network-event-divider network-blue-divider"; var domContentDividerPadding = document.createElement("div"); domContentDividerPadding.className = "network-event-divider-padding"; domContentDividerPadding.title = WebInspector.UIString("DOMContent event fired"); domContentDividerPadding.appendChild(domContentDivider); domContentDividerPadding.style.left = percent + "%"; this._timelineGrid.addEventDivider(domContentDividerPadding); } }, _refreshIfNeeded: function() { if (this._needsRefresh) this.refresh(); }, _invalidateAllItems: function() { for (var i = 0; i < this._requests.length; ++i) { var request = this._requests[i]; this._staleRequests[request.requestId] = request; } }, get calculator() { return this._calculator; }, set calculator(x) { if (!x || this._calculator === x) return; this._calculator = x; this._calculator.reset(); this._invalidateAllItems(); this.refresh(); }, _requestGridNode: function(request) { return this._requestGridNodes[request.__gridNodeId]; }, _createRequestGridNode: function(request) { var node = new WebInspector.NetworkDataGridNode(this, request); request.__gridNodeId = this._lastRequestGridNodeId++; this._requestGridNodes[request.__gridNodeId] = node; return node; }, _createStatusbarButtons: function() { this._preserveLogToggle = new WebInspector.StatusBarButton(WebInspector.UIString("Preserve Log upon Navigation"), "record-profile-status-bar-item"); this._preserveLogToggle.addEventListener("click", this._onPreserveLogClicked, this); this._clearButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear"), "clear-status-bar-item"); this._clearButton.addEventListener("click", this._reset, this); this._largerRequestsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Use small resource rows."), "network-larger-resources-status-bar-item"); this._largerRequestsButton.toggled = WebInspector.settings.resourcesLargeRows.get(); this._largerRequestsButton.addEventListener("click", this._toggleLargerRequests, this); }, _onLoadEventFired: function(event) { this._mainRequestLoadTime = event.data || -1; this._scheduleRefresh(); }, _domContentLoadedEventFired: function(event) { this._mainRequestDOMContentTime = event.data || -1; this._scheduleRefresh(); }, wasShown: function() { this._refreshIfNeeded(); }, willHide: function() { this._popoverHelper.hidePopover(); }, refresh: function() { this._needsRefresh = false; if (this._refreshTimeout) { clearTimeout(this._refreshTimeout); delete this._refreshTimeout; } this._removeAllNodeHighlights(); var wasScrolledToLastRow = this._dataGrid.isScrolledToLastRow(); var boundariesChanged = false; if (this.calculator.updateBoundariesForEventTime) { boundariesChanged = this.calculator.updateBoundariesForEventTime(this._mainRequestLoadTime) || boundariesChanged; boundariesChanged = this.calculator.updateBoundariesForEventTime(this._mainRequestDOMContentTime) || boundariesChanged; } for (var requestId in this._staleRequests) { var request = this._staleRequests[requestId]; var node = this._requestGridNode(request); if (node) node.refreshRequest(); else { node = this._createRequestGridNode(request); this._dataGrid.rootNode().appendChild(node); node.refreshRequest(); this._applyFilter(node); } if (this.calculator.updateBoundaries(request)) boundariesChanged = true; if (!node.isFilteredOut()) this._updateHighlightIfMatched(request); } if (boundariesChanged) { this._invalidateAllItems(); } for (var requestId in this._staleRequests) this._requestGridNode(this._staleRequests[requestId]).refreshGraph(this.calculator); this._staleRequests = {}; this._sortItems(); this._updateSummaryBar(); this._dataGrid.updateWidths(); if (wasScrolledToLastRow) this._dataGrid.scrollToLastRow(); }, _onPreserveLogClicked: function(e) { this._preserveLogToggle.toggled = !this._preserveLogToggle.toggled; }, _reset: function() { this.dispatchEventToListeners(WebInspector.NetworkLogView.EventTypes.ViewCleared); this._clearSearchMatchedList(); if (this._popoverHelper) this._popoverHelper.hidePopover(); if (this._calculator) this._calculator.reset(); this._requests = []; this._requestsById = {}; this._requestsByURL = {}; this._staleRequests = {}; this._requestGridNodes = {}; if (this._dataGrid) { this._dataGrid.rootNode().removeChildren(); this._updateDividersIfNeeded(); this._updateSummaryBar(); } this._mainRequestLoadTime = -1; this._mainRequestDOMContentTime = -1; this._linkifier.reset(); }, get requests() { return this._requests; }, requestById: function(id) { return this._requestsById[id]; }, _onRequestStarted: function(event) { this._appendRequest(event.data); }, _appendRequest: function(request) { this._requests.push(request); if (request.redirects && this._requestsById[request.requestId]) { var oldRequest = request.redirects[request.redirects.length - 1]; this._requestsById[oldRequest.requestId] = oldRequest; this._updateSearchMatchedListAfterRequestIdChanged(request.requestId, oldRequest.requestId); } this._requestsById[request.requestId] = request; this._requestsByURL[request.url] = request; if (request.redirects) { for (var i = 0; i < request.redirects.length; ++i) this._refreshRequest(request.redirects[i]); } this._refreshRequest(request); }, _onRequestUpdated: function(event) { var request = (event.data); this._refreshRequest(request); }, _refreshRequest: function(request) { this._staleRequests[request.requestId] = request; this._scheduleRefresh(); }, clear: function() { if (this._preserveLogToggle.toggled) return; this._reset(); }, _mainFrameNavigated: function(event) { if (this._preserveLogToggle.toggled) return; var frame = (event.data); var loaderId = frame.loaderId; var requestsToPreserve = []; for (var i = 0; i < this._requests.length; ++i) { var request = this._requests[i]; if (request.loaderId === loaderId) requestsToPreserve.push(request); } this._reset(); for (var i = 0; i < requestsToPreserve.length; ++i) this._appendRequest(requestsToPreserve[i]); }, switchToDetailedView: function() { if (!this._dataGrid) return; if (this._dataGrid.selectedNode) this._dataGrid.selectedNode.selected = false; this.element.removeStyleClass("brief-mode"); this._dataGrid.showColumn("method"); this._dataGrid.showColumn("status"); this._dataGrid.showColumn("type"); this._dataGrid.showColumn("initiator"); this._dataGrid.showColumn("size"); this._dataGrid.showColumn("time"); this._dataGrid.showColumn("timeline"); var widths = {}; widths.name = 20; widths.method = 6; widths.status = 6; widths.type = 6; widths.initiator = 10; widths.size = 6; widths.time = 6; widths.timeline = 40; this._dataGrid.applyColumnWidthsMap(widths); }, switchToBriefView: function() { this.element.addStyleClass("brief-mode"); this._removeAllNodeHighlights(); this._dataGrid.hideColumn("method"); this._dataGrid.hideColumn("status"); this._dataGrid.hideColumn("type"); this._dataGrid.hideColumn("initiator"); this._dataGrid.hideColumn("size"); this._dataGrid.hideColumn("time"); this._dataGrid.hideColumn("timeline"); var widths = {}; widths.name = 100; this._dataGrid.applyColumnWidthsMap(widths); this._popoverHelper.hidePopover(); }, _toggleLargerRequests: function() { WebInspector.settings.resourcesLargeRows.set(!WebInspector.settings.resourcesLargeRows.get()); this._setLargerRequests(WebInspector.settings.resourcesLargeRows.get()); }, _setLargerRequests: function(enabled) { this._largerRequestsButton.toggled = enabled; if (!enabled) { this._largerRequestsButton.title = WebInspector.UIString("Use large resource rows."); this._dataGrid.element.addStyleClass("small"); this._timelineGrid.element.addStyleClass("small"); } else { this._largerRequestsButton.title = WebInspector.UIString("Use small resource rows."); this._dataGrid.element.removeStyleClass("small"); this._timelineGrid.element.removeStyleClass("small"); } this.dispatchEventToListeners(WebInspector.NetworkLogView.EventTypes.RowSizeChanged, { largeRows: enabled }); this._updateOffscreenRows(); }, _getPopoverAnchor: function(element) { if (!this._allowPopover) return; var anchor = element.enclosingNodeOrSelfWithClass("network-graph-bar") || element.enclosingNodeOrSelfWithClass("network-graph-label"); if (anchor && anchor.parentElement.request && anchor.parentElement.request.timing) return anchor; anchor = element.enclosingNodeOrSelfWithClass("network-script-initiated"); if (anchor && anchor.request && anchor.request.initiator) return anchor; return null; }, _showPopover: function(anchor, popover) { var content; if (anchor.hasStyleClass("network-script-initiated")) content = this._generateScriptInitiatedPopoverContent(anchor.request); else content = WebInspector.RequestTimingView.createTimingTable(anchor.parentElement.request); popover.show(content, anchor); }, _generateScriptInitiatedPopoverContent: function(request) { var stackTrace = request.initiator.stackTrace; var framesTable = document.createElement("table"); for (var i = 0; i < stackTrace.length; ++i) { var stackFrame = stackTrace[i]; var row = document.createElement("tr"); row.createChild("td").textContent = stackFrame.functionName ? stackFrame.functionName : WebInspector.UIString("(anonymous function)"); row.createChild("td").textContent = " @ "; row.createChild("td").appendChild(this._linkifier.linkifyLocation(stackFrame.url, stackFrame.lineNumber - 1, 0)); framesTable.appendChild(row); } return framesTable; }, _contextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); var gridNode = this._dataGrid.dataGridNodeFromNode(event.target); var request = gridNode && gridNode._request; if (request) { contextMenu.appendItem(WebInspector.openLinkExternallyLabel(), WebInspector.openResource.bind(WebInspector, request.url, false)); contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.copyLinkAddressLabel(), this._copyLocation.bind(this, request)); if (request.requestHeadersText) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy request headers" : "Copy Request Headers"), this._copyRequestHeaders.bind(this, request)); if (request.responseHeadersText) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy response headers" : "Copy Response Headers"), this._copyResponseHeaders.bind(this, request)); } contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy all as HAR" : "Copy All as HAR"), this._copyAll.bind(this)); if (InspectorFrontendHost.canSave()) { contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Save as HAR with content" : "Save as HAR with Content"), this._exportAll.bind(this)); } if (this._canClearBrowserCache || this._canClearBrowserCookies) contextMenu.appendSeparator(); if (this._canClearBrowserCache) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear browser cache" : "Clear Browser Cache"), this._clearBrowserCache.bind(this)); if (this._canClearBrowserCookies) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear browser cookies" : "Clear Browser Cookies"), this._clearBrowserCookies.bind(this)); if (request && request.type === WebInspector.resourceTypes.XHR) { contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString("Replay XHR"), this._replayXHR.bind(this, request.requestId)); contextMenu.appendSeparator(); } contextMenu.show(); }, _replayXHR: function(requestId) { NetworkAgent.replayXHR(requestId); }, _copyAll: function() { var harArchive = { log: (new WebInspector.HARLog(this._requests)).build() }; InspectorFrontendHost.copyText(JSON.stringify(harArchive, null, 2)); }, _copyLocation: function(request) { InspectorFrontendHost.copyText(request.url); }, _copyRequestHeaders: function(request) { InspectorFrontendHost.copyText(request.requestHeadersText); }, _copyResponseHeaders: function(request) { InspectorFrontendHost.copyText(request.responseHeadersText); }, _exportAll: function() { var filename = WebInspector.inspectedPageDomain + ".har"; var stream = new WebInspector.FileOutputStream(); stream.open(filename, openCallback.bind(this)); function openCallback() { var progressIndicator = new WebInspector.ProgressIndicator(); this._progressBarContainer.appendChild(progressIndicator.element); var harWriter = new WebInspector.HARWriter(); harWriter.write(stream, this._requests, progressIndicator); } }, _clearBrowserCache: function(event) { if (confirm(WebInspector.UIString("Are you sure you want to clear browser cache?"))) NetworkAgent.clearBrowserCache(); }, _clearBrowserCookies: function(event) { if (confirm(WebInspector.UIString("Are you sure you want to clear browser cookies?"))) NetworkAgent.clearBrowserCookies(); }, _updateOffscreenRows: function() { var dataTableBody = this._dataGrid.dataTableBody; var rows = dataTableBody.children; var recordsCount = rows.length; if (recordsCount < 2) return; var visibleTop = this._dataGrid.scrollContainer.scrollTop; var visibleBottom = visibleTop + this._dataGrid.scrollContainer.offsetHeight; var rowHeight = 0; var unfilteredRowIndex = 0; for (var i = 0; i < recordsCount - 1; ++i) { var row = rows[i]; var dataGridNode = this._dataGrid.dataGridNodeFromNode(row); if (dataGridNode.isFilteredOut()) { row.removeStyleClass("offscreen"); continue; } if (!rowHeight) rowHeight = row.offsetHeight; var rowIsVisible = unfilteredRowIndex * rowHeight < visibleBottom && (unfilteredRowIndex + 1) * rowHeight > visibleTop; if (rowIsVisible !== row.rowIsVisible) { if (rowIsVisible) row.removeStyleClass("offscreen"); else row.addStyleClass("offscreen"); row.rowIsVisible = rowIsVisible; } unfilteredRowIndex++; } }, _matchRequest: function(request) { if (!this._searchRegExp) return -1; if (!request.name().match(this._searchRegExp) && !request.path().match(this._searchRegExp)) return -1; if (request.requestId in this._matchedRequestsMap) return this._matchedRequestsMap[request.requestId]; var matchedRequestIndex = this._matchedRequests.length; this._matchedRequestsMap[request.requestId] = matchedRequestIndex; this._matchedRequests.push(request.requestId); return matchedRequestIndex; }, _clearSearchMatchedList: function() { delete this._searchRegExp; this._matchedRequests = []; this._matchedRequestsMap = {}; this._removeAllHighlights(); }, _updateSearchMatchedListAfterRequestIdChanged: function(oldRequestId, newRequestId) { var requestIndex = this._matchedRequestsMap[oldRequestId]; if (requestIndex) { delete this._matchedRequestsMap[oldRequestId]; this._matchedRequestsMap[newRequestId] = requestIndex; this._matchedRequests[requestIndex] = newRequestId; } }, _updateHighlightIfMatched: function(request) { var matchedRequestIndex = this._matchRequest(request); if (matchedRequestIndex === -1) return; this.dispatchEventToListeners(WebInspector.NetworkLogView.EventTypes.SearchCountUpdated, this._matchedRequests.length); if (this._currentMatchedRequestIndex !== -1 && this._currentMatchedRequestIndex !== matchedRequestIndex) return; this._highlightNthMatchedRequestForSearch(matchedRequestIndex, false); }, _removeAllHighlights: function() { for (var i = 0; i < this._highlightedSubstringChanges.length; ++i) WebInspector.revertDomChanges(this._highlightedSubstringChanges[i]); this._highlightedSubstringChanges = []; }, _highlightMatchedRequest: function(request, reveal, regExp) { var node = this._requestGridNode(request); if (!node) return; var nameMatched = request.name().match(regExp); var pathMatched = request.path().match(regExp); if (!nameMatched && pathMatched && !this._largerRequestsButton.toggled) this._toggleLargerRequests(); var highlightedSubstringChanges = node._highlightMatchedSubstring(regExp); this._highlightedSubstringChanges.push(highlightedSubstringChanges); if (reveal) node.reveal(); }, _highlightNthMatchedRequestForSearch: function(matchedRequestIndex, reveal) { var request = this.requestById(this._matchedRequests[matchedRequestIndex]); if (!request) return; this._removeAllHighlights(); this._highlightMatchedRequest(request, reveal, this._searchRegExp); var node = this._requestGridNode(request); if (node) this._currentMatchedRequestIndex = matchedRequestIndex; this.dispatchEventToListeners(WebInspector.NetworkLogView.EventTypes.SearchIndexUpdated, this._currentMatchedRequestIndex); }, performSearch: function(searchQuery) { var newMatchedRequestIndex = 0; var currentMatchedRequestId; if (this._currentMatchedRequestIndex !== -1) currentMatchedRequestId = this._matchedRequests[this._currentMatchedRequestIndex]; this._clearSearchMatchedList(); this._searchRegExp = createPlainTextSearchRegex(searchQuery, "i"); var childNodes = this._dataGrid.dataTableBody.childNodes; var requestNodes = Array.prototype.slice.call(childNodes, 0, childNodes.length - 1); for (var i = 0; i < requestNodes.length; ++i) { var dataGridNode = this._dataGrid.dataGridNodeFromNode(requestNodes[i]); if (dataGridNode.isFilteredOut()) continue; if (this._matchRequest(dataGridNode._request) !== -1 && dataGridNode._request.requestId === currentMatchedRequestId) newMatchedRequestIndex = this._matchedRequests.length - 1; } this.dispatchEventToListeners(WebInspector.NetworkLogView.EventTypes.SearchCountUpdated, this._matchedRequests.length); this._highlightNthMatchedRequestForSearch(newMatchedRequestIndex, false); }, _applyFilter: function(node) { var filter = this._filterRegExp; var request = node._request; if (!filter) return; if (filter.test(request.name()) || filter.test(request.path())) this._highlightMatchedRequest(request, false, filter); else { node.element.addStyleClass("filtered-out"); this._filteredOutRequests.put(request, true); } }, performFilter: function(query) { this._removeAllHighlights(); this._filteredOutRequests.clear(); delete this._filterRegExp; if (query) this._filterRegExp = createPlainTextSearchRegex(query, "i"); var nodes = this._dataGrid.rootNode().children; for (var i = 0; i < nodes.length; ++i) { nodes[i].element.removeStyleClass("filtered-out"); this._applyFilter(nodes[i]); } this._updateSummaryBar(); this._updateOffscreenRows(); }, jumpToPreviousSearchResult: function() { if (!this._matchedRequests.length) return; this._highlightNthMatchedRequestForSearch((this._currentMatchedRequestIndex + this._matchedRequests.length - 1) % this._matchedRequests.length, true); }, jumpToNextSearchResult: function() { if (!this._matchedRequests.length) return; this._highlightNthMatchedRequestForSearch((this._currentMatchedRequestIndex + 1) % this._matchedRequests.length, true); }, searchCanceled: function() { this._clearSearchMatchedList(); this.dispatchEventToListeners(WebInspector.NetworkLogView.EventTypes.SearchCountUpdated, 0); }, revealAndHighlightRequest: function(request) { this._removeAllNodeHighlights(); var node = this._requestGridNode(request); if (node) { this._dataGrid.element.focus(); node.reveal(); this._highlightNode(node); } }, _removeAllNodeHighlights: function() { if (this._highlightedNode) { this._highlightedNode.element.removeStyleClass("highlighted-row"); delete this._highlightedNode; } }, _highlightNode: function(node) { node.element.addStyleClass("highlighted-row"); this._highlightedNode = node; }, __proto__: WebInspector.View.prototype } WebInspector.NetworkLogView.EventTypes = { ViewCleared: "ViewCleared", RowSizeChanged: "RowSizeChanged", RequestSelected: "RequestSelected", SearchCountUpdated: "SearchCountUpdated", SearchIndexUpdated: "SearchIndexUpdated" }; WebInspector.NetworkPanel = function() { WebInspector.Panel.call(this, "network"); this.registerRequiredCSS("networkPanel.css"); this.createSidebarView(); this.splitView.hideMainElement(); this._networkLogView = new WebInspector.NetworkLogView(); this._networkLogView.show(this.sidebarElement); this._viewsContainerElement = this.splitView.mainElement; this._viewsContainerElement.id = "network-views"; this._viewsContainerElement.addStyleClass("hidden"); if (!this._networkLogView.useLargeRows) this._viewsContainerElement.addStyleClass("small"); this._networkLogView.addEventListener(WebInspector.NetworkLogView.EventTypes.ViewCleared, this._onViewCleared, this); this._networkLogView.addEventListener(WebInspector.NetworkLogView.EventTypes.RowSizeChanged, this._onRowSizeChanged, this); this._networkLogView.addEventListener(WebInspector.NetworkLogView.EventTypes.RequestSelected, this._onRequestSelected, this); this._networkLogView.addEventListener(WebInspector.NetworkLogView.EventTypes.SearchCountUpdated, this._onSearchCountUpdated, this); this._networkLogView.addEventListener(WebInspector.NetworkLogView.EventTypes.SearchIndexUpdated, this._onSearchIndexUpdated, this); this._closeButtonElement = document.createElement("button"); this._closeButtonElement.id = "network-close-button"; this._closeButtonElement.addEventListener("click", this._toggleGridMode.bind(this), false); this._viewsContainerElement.appendChild(this._closeButtonElement); function viewGetter() { return this.visibleView; } WebInspector.GoToLineDialog.install(this, viewGetter.bind(this)); } WebInspector.NetworkPanel.prototype = { get statusBarItems() { return this._networkLogView.statusBarItems; }, elementsToRestoreScrollPositionsFor: function() { return this._networkLogView.elementsToRestoreScrollPositionsFor(); }, _reset: function() { this._networkLogView._reset(); }, handleShortcut: function(event) { if (this._viewingRequestMode && event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) { this._toggleGridMode(); event.handled = true; return; } WebInspector.Panel.prototype.handleShortcut.call(this, event); }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); }, get requests() { return this._networkLogView.requests; }, requestById: function(id) { return this._networkLogView.requestById(id); }, _requestByAnchor: function(anchor) { return anchor.requestId ? this.requestById(anchor.requestId) : this._networkLogView._requestsByURL[anchor.href]; }, canShowAnchorLocation: function(anchor) { return !!this._requestByAnchor(anchor); }, showAnchorLocation: function(anchor) { var request = this._requestByAnchor(anchor); this.revealAndHighlightRequest(request) }, revealAndHighlightRequest: function(request) { this._toggleGridMode(); if (request) this._networkLogView.revealAndHighlightRequest(request); }, _onViewCleared: function(event) { this._closeVisibleRequest(); this._toggleGridMode(); this._viewsContainerElement.removeChildren(); this._viewsContainerElement.appendChild(this._closeButtonElement); }, _onRowSizeChanged: function(event) { if (event.data.largeRows) this._viewsContainerElement.removeStyleClass("small"); else this._viewsContainerElement.addStyleClass("small"); }, _onSearchCountUpdated: function(event) { WebInspector.searchController.updateSearchMatchesCount(event.data, this); }, _onSearchIndexUpdated: function(event) { WebInspector.searchController.updateCurrentMatchIndex(event.data, this); }, _onRequestSelected: function(event) { this._showRequest(event.data); }, _showRequest: function(request) { if (!request) return; this._toggleViewingRequestMode(); if (this.visibleView) { this.visibleView.detach(); delete this.visibleView; } var view = new WebInspector.NetworkItemView(request); view.show(this._viewsContainerElement); this.visibleView = view; }, _closeVisibleRequest: function() { this.element.removeStyleClass("viewing-resource"); if (this.visibleView) { this.visibleView.detach(); delete this.visibleView; } }, _toggleGridMode: function() { if (this._viewingRequestMode) { this._viewingRequestMode = false; this.element.removeStyleClass("viewing-resource"); this.splitView.hideMainElement(); } this._networkLogView.switchToDetailedView(); this._networkLogView.allowPopover = true; this._networkLogView._allowRequestSelection = false; }, _toggleViewingRequestMode: function() { if (this._viewingRequestMode) return; this._viewingRequestMode = true; this.element.addStyleClass("viewing-resource"); this.splitView.showMainElement(); this._networkLogView.allowPopover = false; this._networkLogView._allowRequestSelection = true; this._networkLogView.switchToBriefView(); }, performSearch: function(searchQuery) { this._networkLogView.performSearch(searchQuery); }, canFilter: function() { return true; }, performFilter: function(query) { this._networkLogView.performFilter(query); }, jumpToPreviousSearchResult: function() { this._networkLogView.jumpToPreviousSearchResult(); }, jumpToNextSearchResult: function() { this._networkLogView.jumpToNextSearchResult(); }, searchCanceled: function() { this._networkLogView.searchCanceled(); }, appendApplicableItems: function(event, contextMenu, target) { if (!(target instanceof WebInspector.NetworkRequest)) return; if (this.visibleView && this.visibleView.isShowing() && this.visibleView.request() === target) return; function reveal() { WebInspector.inspectorView.setCurrentPanel(this); this.revealAndHighlightRequest( (target)); } contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Reveal in network panel" : "Reveal in Network Panel"), reveal.bind(this)); }, __proto__: WebInspector.Panel.prototype } WebInspector.NetworkBaseCalculator = function() { } WebInspector.NetworkBaseCalculator.prototype = { computePosition: function(time) { return (time - this._minimumBoundary) / this.boundarySpan() * this._workingArea; }, computeBarGraphPercentages: function(item) { return {start: 0, middle: 0, end: (this._value(item) / this.boundarySpan()) * 100}; }, computeBarGraphLabels: function(item) { const label = this.formatTime(this._value(item)); return {left: label, right: label, tooltip: label}; }, boundarySpan: function() { return this._maximumBoundary - this._minimumBoundary; }, updateBoundaries: function(item) { this._minimumBoundary = 0; var value = this._value(item); if (typeof this._maximumBoundary === "undefined" || value > this._maximumBoundary) { this._maximumBoundary = value; return true; } return false; }, reset: function() { delete this._minimumBoundary; delete this._maximumBoundary; }, maximumBoundary: function() { return this._maximumBoundary; }, minimumBoundary: function() { return this._minimumBoundary; }, _value: function(item) { return 0; }, formatTime: function(value) { return value.toString(); }, setDisplayWindow: function(clientWidth) { this._workingArea = clientWidth; this.paddingLeft = 0; } } WebInspector.NetworkTimeCalculator = function(startAtZero) { WebInspector.NetworkBaseCalculator.call(this); this.startAtZero = startAtZero; } WebInspector.NetworkTimeCalculator.prototype = { computeBarGraphPercentages: function(request) { if (request.startTime !== -1) var start = ((request.startTime - this._minimumBoundary) / this.boundarySpan()) * 100; else var start = 0; if (request.responseReceivedTime !== -1) var middle = ((request.responseReceivedTime - this._minimumBoundary) / this.boundarySpan()) * 100; else var middle = (this.startAtZero ? start : 100); if (request.endTime !== -1) var end = ((request.endTime - this._minimumBoundary) / this.boundarySpan()) * 100; else var end = (this.startAtZero ? middle : 100); if (this.startAtZero) { end -= start; middle -= start; start = 0; } return {start: start, middle: middle, end: end}; }, computePercentageFromEventTime: function(eventTime) { if (eventTime !== -1 && !this.startAtZero) return ((eventTime - this._minimumBoundary) / this.boundarySpan()) * 100; return 0; }, updateBoundariesForEventTime: function(eventTime) { if (eventTime === -1 || this.startAtZero) return false; if (typeof this._maximumBoundary === "undefined" || eventTime > this._maximumBoundary) { this._maximumBoundary = eventTime; return true; } return false; }, computeBarGraphLabels: function(request) { var rightLabel = ""; if (request.responseReceivedTime !== -1 && request.endTime !== -1) rightLabel = this.formatTime(request.endTime - request.responseReceivedTime); var hasLatency = request.latency > 0; if (hasLatency) var leftLabel = this.formatTime(request.latency); else var leftLabel = rightLabel; if (request.timing) return {left: leftLabel, right: rightLabel}; if (hasLatency && rightLabel) { var total = this.formatTime(request.duration); var tooltip = WebInspector.UIString("%s latency, %s download (%s total)", leftLabel, rightLabel, total); } else if (hasLatency) var tooltip = WebInspector.UIString("%s latency", leftLabel); else if (rightLabel) var tooltip = WebInspector.UIString("%s download", rightLabel); if (request.cached) tooltip = WebInspector.UIString("%s (from cache)", tooltip); return {left: leftLabel, right: rightLabel, tooltip: tooltip}; }, updateBoundaries: function(request) { var didChange = false; var lowerBound; if (this.startAtZero) lowerBound = 0; else lowerBound = this._lowerBound(request); if (lowerBound !== -1 && (typeof this._minimumBoundary === "undefined" || lowerBound < this._minimumBoundary)) { this._minimumBoundary = lowerBound; didChange = true; } var upperBound = this._upperBound(request); if (upperBound !== -1 && (typeof this._maximumBoundary === "undefined" || upperBound > this._maximumBoundary)) { this._maximumBoundary = upperBound; didChange = true; } return didChange; }, formatTime: function(value) { return Number.secondsToString(value); }, _lowerBound: function(request) { return 0; }, _upperBound: function(request) { return 0; }, __proto__: WebInspector.NetworkBaseCalculator.prototype } WebInspector.NetworkTransferTimeCalculator = function() { WebInspector.NetworkTimeCalculator.call(this, false); } WebInspector.NetworkTransferTimeCalculator.prototype = { formatTime: function(value) { return Number.secondsToString(value); }, _lowerBound: function(request) { return request.startTime; }, _upperBound: function(request) { return request.endTime; }, __proto__: WebInspector.NetworkTimeCalculator.prototype } WebInspector.NetworkTransferDurationCalculator = function() { WebInspector.NetworkTimeCalculator.call(this, true); } WebInspector.NetworkTransferDurationCalculator.prototype = { formatTime: function(value) { return Number.secondsToString(value); }, _upperBound: function(request) { return request.duration; }, __proto__: WebInspector.NetworkTimeCalculator.prototype } WebInspector.NetworkDataGridNode = function(parentView, request) { WebInspector.DataGridNode.call(this, {}); this._parentView = parentView; this._request = request; } WebInspector.NetworkDataGridNode.prototype = { createCells: function() { this._element.addStyleClass("offscreen"); this._nameCell = this._createDivInTD("name"); this._methodCell = this._createDivInTD("method"); this._statusCell = this._createDivInTD("status"); this._typeCell = this._createDivInTD("type"); this._initiatorCell = this._createDivInTD("initiator"); this._sizeCell = this._createDivInTD("size"); this._timeCell = this._createDivInTD("time"); this._createTimelineCell(); this._nameCell.addEventListener("click", this._onClick.bind(this), false); this._nameCell.addEventListener("dblclick", this._openInNewTab.bind(this), false); }, isFilteredOut: function() { if (this._parentView._filteredOutRequests.get(this._request)) return true; if (!this._parentView._hiddenCategories.all) return false; return this._request.type.name() in this._parentView._hiddenCategories; }, _onClick: function() { if (!this._parentView._allowRequestSelection) this.select(); }, select: function() { this._parentView.dispatchEventToListeners(WebInspector.NetworkLogView.EventTypes.RequestSelected, this._request); WebInspector.DataGridNode.prototype.select.apply(this, arguments); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.NetworkRequestSelected, url: this._request.url }); }, _highlightMatchedSubstring: function(regexp) { var domChanges = []; var matchInfo = this._element.textContent.match(regexp); if (matchInfo) WebInspector.highlightSearchResult(this._nameCell, matchInfo.index, matchInfo[0].length, domChanges); return domChanges; }, _openInNewTab: function() { InspectorFrontendHost.openInNewTab(this._request.url); }, get selectable() { return this._parentView._allowRequestSelection && !this.isFilteredOut(); }, _createDivInTD: function(columnIdentifier) { var td = document.createElement("td"); td.className = columnIdentifier + "-column"; var div = document.createElement("div"); td.appendChild(div); this._element.appendChild(td); return div; }, _createTimelineCell: function() { this._graphElement = document.createElement("div"); this._graphElement.className = "network-graph-side"; this._barAreaElement = document.createElement("div"); this._barAreaElement.className = "network-graph-bar-area"; this._barAreaElement.request = this._request; this._graphElement.appendChild(this._barAreaElement); this._barLeftElement = document.createElement("div"); this._barLeftElement.className = "network-graph-bar waiting"; this._barAreaElement.appendChild(this._barLeftElement); this._barRightElement = document.createElement("div"); this._barRightElement.className = "network-graph-bar"; this._barAreaElement.appendChild(this._barRightElement); this._labelLeftElement = document.createElement("div"); this._labelLeftElement.className = "network-graph-label waiting"; this._barAreaElement.appendChild(this._labelLeftElement); this._labelRightElement = document.createElement("div"); this._labelRightElement.className = "network-graph-label"; this._barAreaElement.appendChild(this._labelRightElement); this._graphElement.addEventListener("mouseover", this._refreshLabelPositions.bind(this), false); this._timelineCell = document.createElement("td"); this._timelineCell.className = "timeline-column"; this._element.appendChild(this._timelineCell); this._timelineCell.appendChild(this._graphElement); }, refreshRequest: function() { this._refreshNameCell(); this._methodCell.setTextAndTitle(this._request.requestMethod); this._refreshStatusCell(); this._refreshTypeCell(); this._refreshInitiatorCell(); this._refreshSizeCell(); this._refreshTimeCell(); if (this._request.cached) this._graphElement.addStyleClass("resource-cached"); this._element.addStyleClass("network-item"); if (!this._element.hasStyleClass("network-type-" + this._request.type.name())) { this._element.removeMatchingStyleClasses("network-type-\\w+"); this._element.addStyleClass("network-type-" + this._request.type.name()); } }, _refreshNameCell: function() { this._nameCell.removeChildren(); if (this._request.type === WebInspector.resourceTypes.Image) { var previewImage = document.createElement("img"); previewImage.className = "image-network-icon-preview"; this._request.populateImageSource(previewImage); var iconElement = document.createElement("div"); iconElement.className = "icon"; iconElement.appendChild(previewImage); } else { var iconElement = document.createElement("img"); iconElement.className = "icon"; } this._nameCell.appendChild(iconElement); this._nameCell.appendChild(document.createTextNode(this._request.name())); this._appendSubtitle(this._nameCell, this._request.path()); this._nameCell.title = this._request.url; }, _refreshStatusCell: function() { this._statusCell.removeChildren(); if (this._request.failed) { var failText = this._request.canceled ? WebInspector.UIString("(canceled)") : WebInspector.UIString("(failed)"); if (this._request.localizedFailDescription) { this._statusCell.appendChild(document.createTextNode(failText)); this._appendSubtitle(this._statusCell, this._request.localizedFailDescription); this._statusCell.title = failText + " " + this._request.localizedFailDescription; } else { this._statusCell.setTextAndTitle(failText); } this._statusCell.addStyleClass("network-dim-cell"); this.element.addStyleClass("network-error-row"); return; } this._statusCell.removeStyleClass("network-dim-cell"); this.element.removeStyleClass("network-error-row"); if (this._request.statusCode) { this._statusCell.appendChild(document.createTextNode(this._request.statusCode)); this._appendSubtitle(this._statusCell, this._request.statusText); this._statusCell.title = this._request.statusCode + " " + this._request.statusText; if (this._request.statusCode >= 400) this.element.addStyleClass("network-error-row"); if (this._request.cached) this._statusCell.addStyleClass("network-dim-cell"); } else { if (!this._request.isHttpFamily() && this._request.finished) this._statusCell.setTextAndTitle(WebInspector.UIString("Success")); else if (this._request.isPingRequest()) this._statusCell.setTextAndTitle(WebInspector.UIString("(ping)")); else this._statusCell.setTextAndTitle(WebInspector.UIString("(pending)")); this._statusCell.addStyleClass("network-dim-cell"); } }, _refreshTypeCell: function() { if (this._request.mimeType) { this._typeCell.removeStyleClass("network-dim-cell"); this._typeCell.setTextAndTitle(this._request.mimeType); } else if (this._request.isPingRequest()) { this._typeCell.removeStyleClass("network-dim-cell"); this._typeCell.setTextAndTitle(this._request.requestContentType()); } else { this._typeCell.addStyleClass("network-dim-cell"); this._typeCell.setTextAndTitle(WebInspector.UIString("Pending")); } }, _refreshInitiatorCell: function() { this._initiatorCell.removeStyleClass("network-dim-cell"); this._initiatorCell.removeStyleClass("network-script-initiated"); delete this._initiatorCell.request; this._initiatorCell.title = null; var initiator = this._request.initiator; if ((initiator && initiator.type !== "other") || this._request.redirectSource) { this._initiatorCell.removeChildren(); if (this._request.redirectSource) { var redirectSource = this._request.redirectSource; this._initiatorCell.title = redirectSource.url; this._initiatorCell.appendChild(WebInspector.linkifyRequestAsNode(redirectSource)); this._appendSubtitle(this._initiatorCell, WebInspector.UIString("Redirect")); } else if (initiator.type === "script") { var topFrame = initiator.stackTrace[0]; if (!topFrame.url) { this._initiatorCell.addStyleClass("network-dim-cell"); this._initiatorCell.setTextAndTitle(WebInspector.UIString("Other")); return; } var urlElement = this._parentView._linkifier.linkifyLocation(topFrame.url, topFrame.lineNumber - 1, 0); urlElement.title = null; this._initiatorCell.appendChild(urlElement); this._appendSubtitle(this._initiatorCell, WebInspector.UIString("Script")); this._initiatorCell.addStyleClass("network-script-initiated"); this._initiatorCell.request = this._request; } else { this._initiatorCell.title = initiator.url + ":" + initiator.lineNumber; this._initiatorCell.appendChild(WebInspector.linkifyResourceAsNode(initiator.url, initiator.lineNumber - 1)); this._appendSubtitle(this._initiatorCell, WebInspector.UIString("Parser")); } } else { this._initiatorCell.addStyleClass("network-dim-cell"); this._initiatorCell.setTextAndTitle(WebInspector.UIString("Other")); } }, _refreshSizeCell: function() { if (this._request.cached) { this._sizeCell.setTextAndTitle(WebInspector.UIString("(from cache)")); this._sizeCell.addStyleClass("network-dim-cell"); } else { var resourceSize = typeof this._request.resourceSize === "number" ? Number.bytesToString(this._request.resourceSize) : "?"; var transferSize = typeof this._request.transferSize === "number" ? Number.bytesToString(this._request.transferSize) : "?"; this._sizeCell.setTextAndTitle(transferSize); this._sizeCell.removeStyleClass("network-dim-cell"); this._appendSubtitle(this._sizeCell, resourceSize); } }, _refreshTimeCell: function() { if (this._request.duration > 0) { this._timeCell.removeStyleClass("network-dim-cell"); this._timeCell.setTextAndTitle(Number.secondsToString(this._request.duration)); this._appendSubtitle(this._timeCell, Number.secondsToString(this._request.latency)); } else { this._timeCell.addStyleClass("network-dim-cell"); this._timeCell.setTextAndTitle(WebInspector.UIString("Pending")); } }, _appendSubtitle: function(cellElement, subtitleText) { var subtitleElement = document.createElement("div"); subtitleElement.className = "network-cell-subtitle"; subtitleElement.textContent = subtitleText; cellElement.appendChild(subtitleElement); }, refreshGraph: function(calculator) { var percentages = calculator.computeBarGraphPercentages(this._request); this._percentages = percentages; this._barAreaElement.removeStyleClass("hidden"); if (!this._graphElement.hasStyleClass("network-type-" + this._request.type.name())) { this._graphElement.removeMatchingStyleClasses("network-type-\\w+"); this._graphElement.addStyleClass("network-type-" + this._request.type.name()); } this._barLeftElement.style.setProperty("left", percentages.start + "%"); this._barRightElement.style.setProperty("right", (100 - percentages.end) + "%"); this._barLeftElement.style.setProperty("right", (100 - percentages.end) + "%"); this._barRightElement.style.setProperty("left", percentages.middle + "%"); var labels = calculator.computeBarGraphLabels(this._request); this._labelLeftElement.textContent = labels.left; this._labelRightElement.textContent = labels.right; var tooltip = (labels.tooltip || ""); this._barLeftElement.title = tooltip; this._labelLeftElement.title = tooltip; this._labelRightElement.title = tooltip; this._barRightElement.title = tooltip; }, _refreshLabelPositions: function() { if (!this._percentages) return; this._labelLeftElement.style.removeProperty("left"); this._labelLeftElement.style.removeProperty("right"); this._labelLeftElement.removeStyleClass("before"); this._labelLeftElement.removeStyleClass("hidden"); this._labelRightElement.style.removeProperty("left"); this._labelRightElement.style.removeProperty("right"); this._labelRightElement.removeStyleClass("after"); this._labelRightElement.removeStyleClass("hidden"); const labelPadding = 10; const barRightElementOffsetWidth = this._barRightElement.offsetWidth; const barLeftElementOffsetWidth = this._barLeftElement.offsetWidth; if (this._barLeftElement) { var leftBarWidth = barLeftElementOffsetWidth - labelPadding; var rightBarWidth = (barRightElementOffsetWidth - barLeftElementOffsetWidth) - labelPadding; } else { var leftBarWidth = (barLeftElementOffsetWidth - barRightElementOffsetWidth) - labelPadding; var rightBarWidth = barRightElementOffsetWidth - labelPadding; } const labelLeftElementOffsetWidth = this._labelLeftElement.offsetWidth; const labelRightElementOffsetWidth = this._labelRightElement.offsetWidth; const labelBefore = (labelLeftElementOffsetWidth > leftBarWidth); const labelAfter = (labelRightElementOffsetWidth > rightBarWidth); const graphElementOffsetWidth = this._graphElement.offsetWidth; if (labelBefore && (graphElementOffsetWidth * (this._percentages.start / 100)) < (labelLeftElementOffsetWidth + 10)) var leftHidden = true; if (labelAfter && (graphElementOffsetWidth * ((100 - this._percentages.end) / 100)) < (labelRightElementOffsetWidth + 10)) var rightHidden = true; if (barLeftElementOffsetWidth == barRightElementOffsetWidth) { if (labelBefore && !labelAfter) leftHidden = true; else if (labelAfter && !labelBefore) rightHidden = true; } if (labelBefore) { if (leftHidden) this._labelLeftElement.addStyleClass("hidden"); this._labelLeftElement.style.setProperty("right", (100 - this._percentages.start) + "%"); this._labelLeftElement.addStyleClass("before"); } else { this._labelLeftElement.style.setProperty("left", this._percentages.start + "%"); this._labelLeftElement.style.setProperty("right", (100 - this._percentages.middle) + "%"); } if (labelAfter) { if (rightHidden) this._labelRightElement.addStyleClass("hidden"); this._labelRightElement.style.setProperty("left", this._percentages.end + "%"); this._labelRightElement.addStyleClass("after"); } else { this._labelRightElement.style.setProperty("left", this._percentages.middle + "%"); this._labelRightElement.style.setProperty("right", (100 - this._percentages.end) + "%"); } }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.NetworkDataGridNode.NameComparator = function(a, b) { var aFileName = a._request.name(); var bFileName = b._request.name(); if (aFileName > bFileName) return 1; if (bFileName > aFileName) return -1; return 0; } WebInspector.NetworkDataGridNode.SizeComparator = function(a, b) { if (b._request.cached && !a._request.cached) return 1; if (a._request.cached && !b._request.cached) return -1; if (a._request.resourceSize === b._request.resourceSize) return 0; return a._request.resourceSize - b._request.resourceSize; } WebInspector.NetworkDataGridNode.InitiatorComparator = function(a, b) { if (!a._request.initiator || a._request.initiator.type === "Other") return -1; if (!b._request.initiator || b._request.initiator.type === "Other") return 1; if (a._request.initiator.url < b._request.initiator.url) return -1; if (a._request.initiator.url > b._request.initiator.url) return 1; return a._request.initiator.lineNumber - b._request.initiator.lineNumber; } WebInspector.NetworkDataGridNode.RequestPropertyComparator = function(propertyName, revert, a, b) { var aValue = a._request[propertyName]; var bValue = b._request[propertyName]; if (aValue > bValue) return revert ? -1 : 1; if (bValue > aValue) return revert ? 1 : -1; return 0; }
JavaScript
WebInspector.ApplicationCacheItemsView = function(model, frameId) { WebInspector.View.call(this); this._model = model; this.element.addStyleClass("storage-view"); this.element.addStyleClass("table"); this.deleteButton = new WebInspector.StatusBarButton(WebInspector.UIString("Delete"), "delete-storage-status-bar-item"); this.deleteButton.visible = false; this.deleteButton.addEventListener("click", this._deleteButtonClicked, this); this.connectivityIcon = document.createElement("img"); this.connectivityIcon.className = "storage-application-cache-connectivity-icon"; this.connectivityIcon.src = ""; this.connectivityMessage = document.createElement("span"); this.connectivityMessage.className = "storage-application-cache-connectivity"; this.connectivityMessage.textContent = ""; this.divider = document.createElement("span"); this.divider.className = "status-bar-item status-bar-divider"; this.statusIcon = document.createElement("img"); this.statusIcon.className = "storage-application-cache-status-icon"; this.statusIcon.src = ""; this.statusMessage = document.createElement("span"); this.statusMessage.className = "storage-application-cache-status"; this.statusMessage.textContent = ""; this._frameId = frameId; this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("No Application Cache information available.")); this._emptyView.show(this.element); this._markDirty(); var status = this._model.frameManifestStatus(frameId); this.updateStatus(status); this.updateNetworkState(this._model.onLine); this.deleteButton.element.style.display = "none"; } WebInspector.ApplicationCacheItemsView.prototype = { get statusBarItems() { return [ this.deleteButton.element, this.connectivityIcon, this.connectivityMessage, this.divider, this.statusIcon, this.statusMessage ]; }, wasShown: function() { this._maybeUpdate(); }, willHide: function() { this.deleteButton.visible = false; }, _maybeUpdate: function() { if (!this.isShowing() || !this._viewDirty) return; this._update(); this._viewDirty = false; }, _markDirty: function() { this._viewDirty = true; }, updateStatus: function(status) { var oldStatus = this._status; this._status = status; var statusInformation = {}; statusInformation[applicationCache.UNCACHED] = { src: "Images/errorRedDot.png", text: "UNCACHED" }; statusInformation[applicationCache.IDLE] = { src: "Images/successGreenDot.png", text: "IDLE" }; statusInformation[applicationCache.CHECKING] = { src: "Images/warningOrangeDot.png", text: "CHECKING" }; statusInformation[applicationCache.DOWNLOADING] = { src: "Images/warningOrangeDot.png", text: "DOWNLOADING" }; statusInformation[applicationCache.UPDATEREADY] = { src: "Images/successGreenDot.png", text: "UPDATEREADY" }; statusInformation[applicationCache.OBSOLETE] = { src: "Images/errorRedDot.png", text: "OBSOLETE" }; var info = statusInformation[status] || statusInformation[applicationCache.UNCACHED]; this.statusIcon.src = info.src; this.statusMessage.textContent = info.text; if (this.isShowing() && this._status === applicationCache.IDLE && (oldStatus === applicationCache.UPDATEREADY || !this._resources)) this._markDirty(); this._maybeUpdate(); }, updateNetworkState: function(isNowOnline) { if (isNowOnline) { this.connectivityIcon.src = "Images/successGreenDot.png"; this.connectivityMessage.textContent = WebInspector.UIString("Online"); } else { this.connectivityIcon.src = "Images/errorRedDot.png"; this.connectivityMessage.textContent = WebInspector.UIString("Offline"); } }, _update: function() { this._model.requestApplicationCache(this._frameId, this._updateCallback.bind(this)); }, _updateCallback: function(applicationCache) { if (!applicationCache || !applicationCache.manifestURL) { delete this._manifest; delete this._creationTime; delete this._updateTime; delete this._size; delete this._resources; this._emptyView.show(this.element); this.deleteButton.visible = false; if (this._dataGrid) this._dataGrid.element.addStyleClass("hidden"); return; } this._manifest = applicationCache.manifestURL; this._creationTime = applicationCache.creationTime; this._updateTime = applicationCache.updateTime; this._size = applicationCache.size; this._resources = applicationCache.resources; if (!this._dataGrid) this._createDataGrid(); this._populateDataGrid(); this._dataGrid.autoSizeColumns(20, 80); this._dataGrid.element.removeStyleClass("hidden"); this._emptyView.detach(); this.deleteButton.visible = true; }, _createDataGrid: function() { var columns = { 0: {}, 1: {}, 2: {} }; columns[0].title = WebInspector.UIString("Resource"); columns[0].sort = "ascending"; columns[0].sortable = true; columns[1].title = WebInspector.UIString("Type"); columns[1].sortable = true; columns[2].title = WebInspector.UIString("Size"); columns[2].aligned = "right"; columns[2].sortable = true; this._dataGrid = new WebInspector.DataGrid(columns); this._dataGrid.show(this.element); this._dataGrid.addEventListener("sorting changed", this._populateDataGrid, this); }, _populateDataGrid: function() { var selectedResource = this._dataGrid.selectedNode ? this._dataGrid.selectedNode.resource : null; var sortDirection = this._dataGrid.sortOrder === "ascending" ? 1 : -1; function numberCompare(field, resource1, resource2) { return sortDirection * (resource1[field] - resource2[field]); } function localeCompare(field, resource1, resource2) { return sortDirection * (resource1[field] + "").localeCompare(resource2[field] + "") } var comparator; switch (parseInt(this._dataGrid.sortColumnIdentifier, 10)) { case 0: comparator = localeCompare.bind(this, "name"); break; case 1: comparator = localeCompare.bind(this, "type"); break; case 2: comparator = numberCompare.bind(this, "size"); break; default: localeCompare.bind(this, "resource"); } this._resources.sort(comparator); this._dataGrid.rootNode().removeChildren(); var nodeToSelect; for (var i = 0; i < this._resources.length; ++i) { var data = {}; var resource = this._resources[i]; data[0] = resource.url; data[1] = resource.type; data[2] = Number.bytesToString(resource.size); var node = new WebInspector.DataGridNode(data); node.resource = resource; node.selectable = true; this._dataGrid.rootNode().appendChild(node); if (resource === selectedResource) { nodeToSelect = node; nodeToSelect.selected = true; } } if (!nodeToSelect && this._dataGrid.rootNode().children.length) this._dataGrid.rootNode().children[0].selected = true; }, _deleteButtonClicked: function(event) { if (!this._dataGrid || !this._dataGrid.selectedNode) return; this._deleteCallback(this._dataGrid.selectedNode); }, _deleteCallback: function(node) { }, __proto__: WebInspector.View.prototype } ; WebInspector.DOMStorageItemsView = function(domStorage) { WebInspector.View.call(this); this.domStorage = domStorage; this.element.addStyleClass("storage-view"); this.element.addStyleClass("table"); this.deleteButton = new WebInspector.StatusBarButton(WebInspector.UIString("Delete"), "delete-storage-status-bar-item"); this.deleteButton.visible = false; this.deleteButton.addEventListener("click", this._deleteButtonClicked, this); this.refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item"); this.refreshButton.addEventListener("click", this._refreshButtonClicked, this); } WebInspector.DOMStorageItemsView.prototype = { get statusBarItems() { return [this.refreshButton.element, this.deleteButton.element]; }, wasShown: function() { this.update(); }, willHide: function() { this.deleteButton.visible = false; }, update: function() { this.detachChildViews(); this.domStorage.getEntries(this._showDOMStorageEntries.bind(this)); }, _showDOMStorageEntries: function(error, entries) { if (error) return; this._dataGrid = this._dataGridForDOMStorageEntries(entries); this._dataGrid.show(this.element); this._dataGrid.autoSizeColumns(10); this.deleteButton.visible = true; }, _dataGridForDOMStorageEntries: function(entries) { var columns = {}; columns[0] = {}; columns[1] = {}; columns[0].title = WebInspector.UIString("Key"); columns[1].title = WebInspector.UIString("Value"); var nodes = []; var keys = []; var length = entries.length; for (var i = 0; i < entries.length; i++) { var data = {}; var key = entries[i][0]; data[0] = key; var value = entries[i][1]; data[1] = value; var node = new WebInspector.DataGridNode(data, false); node.selectable = true; nodes.push(node); keys.push(key); } var dataGrid = new WebInspector.DataGrid(columns, this._editingCallback.bind(this), this._deleteCallback.bind(this)); length = nodes.length; for (var i = 0; i < length; ++i) dataGrid.rootNode().appendChild(nodes[i]); dataGrid.addCreationNode(false); if (length > 0) nodes[0].selected = true; return dataGrid; }, _deleteButtonClicked: function(event) { if (!this._dataGrid || !this._dataGrid.selectedNode) return; this._deleteCallback(this._dataGrid.selectedNode); }, _refreshButtonClicked: function(event) { this.update(); }, _editingCallback: function(editingNode, columnIdentifier, oldText, newText) { var domStorage = this.domStorage; if (columnIdentifier === 0) { if (oldText) domStorage.removeItem(oldText); domStorage.setItem(newText, editingNode.data[1]); } else { domStorage.setItem(editingNode.data[0], newText); } this.update(); }, _deleteCallback: function(node) { if (!node || node.isCreationNode) return; if (this.domStorage) this.domStorage.removeItem(node.data[0]); this.update(); }, __proto__: WebInspector.View.prototype } ; WebInspector.DatabaseQueryView = function(database) { WebInspector.View.call(this); this.database = database; this.element.addStyleClass("storage-view"); this.element.addStyleClass("query"); this.element.addStyleClass("monospace"); this.element.addEventListener("selectstart", this._selectStart.bind(this), false); this._promptElement = document.createElement("div"); this._promptElement.className = "database-query-prompt"; this._promptElement.appendChild(document.createElement("br")); this._promptElement.addEventListener("keydown", this._promptKeyDown.bind(this), true); this.element.appendChild(this._promptElement); this.prompt = new WebInspector.TextPromptWithHistory(this.completions.bind(this), " "); this.prompt.attach(this._promptElement); this.element.addEventListener("click", this._messagesClicked.bind(this), true); } WebInspector.DatabaseQueryView.Events = { SchemaUpdated: "SchemaUpdated" } WebInspector.DatabaseQueryView.prototype = { _messagesClicked: function() { if (!this.prompt.isCaretInsidePrompt() && window.getSelection().isCollapsed) this.prompt.moveCaretToEndOfPrompt(); }, completions: function(proxyElement, wordRange, force, completionsReadyCallback) { var prefix = wordRange.toString().toLowerCase(); if (!prefix.length && !force) return; var results = []; function accumulateMatches(textArray) { for (var i = 0; i < textArray.length; ++i) { var text = textArray[i].toLowerCase(); if (text.length < prefix.length) continue; if (!text.startsWith(prefix)) continue; results.push(textArray[i]); } } function tableNamesCallback(tableNames) { accumulateMatches(tableNames.map(function(name) { return name + " " })); accumulateMatches(["SELECT ", "FROM ", "WHERE ", "LIMIT ", "DELETE FROM ", "CREATE ", "DROP ", "TABLE ", "INDEX ", "UPDATE ", "INSERT INTO ", "VALUES ("]); completionsReadyCallback(results); } this.database.getTableNames(tableNamesCallback); }, _selectStart: function(event) { if (this._selectionTimeout) clearTimeout(this._selectionTimeout); this.prompt.clearAutoComplete(); function moveBackIfOutside() { delete this._selectionTimeout; if (!this.prompt.isCaretInsidePrompt() && window.getSelection().isCollapsed) this.prompt.moveCaretToEndOfPrompt(); this.prompt.autoCompleteSoon(); } this._selectionTimeout = setTimeout(moveBackIfOutside.bind(this), 100); }, _promptKeyDown: function(event) { if (isEnterKey(event)) { this._enterKeyPressed(event); return; } }, _enterKeyPressed: function(event) { event.consume(true); this.prompt.clearAutoComplete(true); var query = this.prompt.text; if (!query.length) return; this.prompt.pushHistoryItem(query); this.prompt.text = ""; this.database.executeSql(query, this._queryFinished.bind(this, query), this._queryError.bind(this, query)); }, _queryFinished: function(query, columnNames, values) { var dataGrid = WebInspector.DataGrid.createSortableDataGrid(columnNames, values); var trimmedQuery = query.trim(); if (dataGrid) { dataGrid.element.addStyleClass("inline"); this._appendViewQueryResult(trimmedQuery, dataGrid); dataGrid.autoSizeColumns(5); } if (trimmedQuery.match(/^create /i) || trimmedQuery.match(/^drop table /i)) this.dispatchEventToListeners(WebInspector.DatabaseQueryView.Events.SchemaUpdated, this.database); }, _queryError: function(query, errorMessage) { this._appendErrorQueryResult(query, errorMessage); }, _appendViewQueryResult: function(query, view) { var resultElement = this._appendQueryResult(query); view.show(resultElement); this._promptElement.scrollIntoView(false); }, _appendErrorQueryResult: function(query, errorText) { var resultElement = this._appendQueryResult(query); resultElement.addStyleClass("error") resultElement.textContent = errorText; this._promptElement.scrollIntoView(false); }, _appendQueryResult: function(query) { var element = document.createElement("div"); element.className = "database-user-query"; this.element.insertBefore(element, this.prompt.proxyElement); var commandTextElement = document.createElement("span"); commandTextElement.className = "database-query-text"; commandTextElement.textContent = query; element.appendChild(commandTextElement); var resultElement = document.createElement("div"); resultElement.className = "database-query-result"; element.appendChild(resultElement); return resultElement; }, __proto__: WebInspector.View.prototype } ; WebInspector.DatabaseTableView = function(database, tableName) { WebInspector.View.call(this); this.database = database; this.tableName = tableName; this.element.addStyleClass("storage-view"); this.element.addStyleClass("table"); this.refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item"); this.refreshButton.addEventListener("click", this._refreshButtonClicked, this); } WebInspector.DatabaseTableView.prototype = { wasShown: function() { this.update(); }, get statusBarItems() { return [this.refreshButton.element]; }, _escapeTableName: function(tableName) { return tableName.replace(/\"/g, "\"\""); }, update: function() { this.database.executeSql("SELECT * FROM \"" + this._escapeTableName(this.tableName) + "\"", this._queryFinished.bind(this), this._queryError.bind(this)); }, _queryFinished: function(columnNames, values) { this.detachChildViews(); this.element.removeChildren(); var dataGrid = WebInspector.DataGrid.createSortableDataGrid(columnNames, values); if (!dataGrid) { this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("The “%s”\ntable is empty.", this.tableName)); this._emptyView.show(this.element); return; } dataGrid.show(this.element); dataGrid.autoSizeColumns(5); }, _queryError: function(error) { this.detachChildViews(); this.element.removeChildren(); var errorMsgElement = document.createElement("div"); errorMsgElement.className = "storage-table-error"; errorMsgElement.textContent = WebInspector.UIString("An error occurred trying to\nread the “%s” table.", this.tableName); this.element.appendChild(errorMsgElement); }, _refreshButtonClicked: function(event) { this.update(); }, __proto__: WebInspector.View.prototype } ; WebInspector.DirectoryContentView = function() { const indexes = WebInspector.DirectoryContentView.columnIndexes; var columns = {}; columns[indexes.Name] = {}; columns[indexes.Name].title = WebInspector.UIString("Name"); columns[indexes.Name].sort = "ascending"; columns[indexes.Name].sortable = true; columns[indexes.Name].width = "20%"; columns[indexes.URL] = {}; columns[indexes.URL].title = WebInspector.UIString("URL"); columns[indexes.URL].sortable = true; columns[indexes.URL].width = "20%"; columns[indexes.Type] = {}; columns[indexes.Type].title = WebInspector.UIString("Type"); columns[indexes.Type].sortable = true; columns[indexes.Type].width = "15%"; columns[indexes.Size] = {}; columns[indexes.Size].title = WebInspector.UIString("Size"); columns[indexes.Size].sortable = true; columns[indexes.Size].width = "10%"; columns[indexes.ModificationTime] = {}; columns[indexes.ModificationTime].title = WebInspector.UIString("Modification Time"); columns[indexes.ModificationTime].sortable = true; columns[indexes.ModificationTime].width = "25%"; WebInspector.DataGrid.call(this, columns); this.addEventListener("sorting changed", this._sort, this); } WebInspector.DirectoryContentView.columnIndexes = { Name: "0", URL: "1", Type: "2", Size: "3", ModificationTime: "4" } WebInspector.DirectoryContentView.prototype = { showEntries: function(entries) { const indexes = WebInspector.DirectoryContentView.columnIndexes; this.rootNode().removeChildren(); for (var i = 0; i < entries.length; ++i) this.rootNode().appendChild(new WebInspector.DirectoryContentView.Node(entries[i])); }, _sort: function() { var column = (this.sortColumnIdentifier); this.sortNodes(WebInspector.DirectoryContentView.Node.comparator(column, this.sortOrder === "descending"), false); }, __proto__: WebInspector.DataGrid.prototype } WebInspector.DirectoryContentView.Node = function(entry) { const indexes = WebInspector.DirectoryContentView.columnIndexes; var data = {}; data[indexes.Name] = entry.name; data[indexes.URL] = entry.url; data[indexes.Type] = entry.isDirectory ? WebInspector.UIString("Directory") : entry.mimeType; data[indexes.Size] = ""; data[indexes.ModificationTime] = ""; WebInspector.DataGridNode.call(this, data); this._entry = entry; this._metadata = null; this._entry.requestMetadata(this._metadataReceived.bind(this)); } WebInspector.DirectoryContentView.Node.comparator = function(column, reverse) { var reverseFactor = reverse ? -1 : 1; const indexes = WebInspector.DirectoryContentView.columnIndexes; switch (column) { case indexes.Name: case indexes.URL: return function(x, y) { return isDirectoryCompare(x, y) || nameCompare(x, y); }; case indexes.Type: return function(x, y) { return isDirectoryCompare(x ,y) || typeCompare(x, y) || nameCompare(x, y); }; case indexes.Size: return function(x, y) { return isDirectoryCompare(x, y) || sizeCompare(x, y) || nameCompare(x, y); }; case indexes.ModificationTime: return function(x, y) { return isDirectoryCompare(x, y) || modificationTimeCompare(x, y) || nameCompare(x, y); }; } function isDirectoryCompare(x, y) { if (x._entry.isDirectory != y._entry.isDirectory) return y._entry.isDirectory ? 1 : -1; return 0; } function nameCompare(x, y) { return reverseFactor * x._entry.name.localeCompare(y._entry.name); } function typeCompare(x, y) { return reverseFactor * (x._entry.mimeType || "").localeCompare(y._entry.mimeType || ""); } function sizeCompare(x, y) { return reverseFactor * ((x._metadata ? x._metadata.size : 0) - (y._metadata ? y._metadata.size : 0)); } function modificationTimeCompare(x, y) { return reverseFactor * ((x._metadata ? x._metadata.modificationTime : 0) - (y._metadata ? y._metadata.modificationTime : 0)); } } WebInspector.DirectoryContentView.Node.prototype = { _metadataReceived: function(errorCode, metadata) { const indexes = WebInspector.DirectoryContentView.columnIndexes; if (errorCode !== 0) return; this._metadata = metadata; var data = this.data; if (this._entry.isDirectory) data[indexes.Size] = WebInspector.UIString("-"); else data[indexes.Size] = Number.bytesToString(metadata.size); data[indexes.ModificationTime] = new Date(metadata.modificationTime).toGMTString(); this.data = data; }, __proto__: WebInspector.DataGridNode.prototype } ; WebInspector.IDBDatabaseView = function(database) { WebInspector.View.call(this); this.registerRequiredCSS("indexedDBViews.css"); this.element.addStyleClass("fill"); this.element.addStyleClass("indexed-db-database-view"); this._headersListElement = this.element.createChild("ol", "outline-disclosure"); this._headersTreeOutline = new TreeOutline(this._headersListElement); this._headersTreeOutline.expandTreeElementsWhenArrowing = true; this._securityOriginTreeElement = new TreeElement("", null, false); this._securityOriginTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._securityOriginTreeElement); this._nameTreeElement = new TreeElement("", null, false); this._nameTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._nameTreeElement); this._intVersionTreeElement = new TreeElement("", null, false); this._intVersionTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._intVersionTreeElement); this._stringVersionTreeElement = new TreeElement("", null, false); this._stringVersionTreeElement.selectable = false; this._headersTreeOutline.appendChild(this._stringVersionTreeElement); this.update(database); } WebInspector.IDBDatabaseView.prototype = { _formatHeader: function(name, value) { var fragment = document.createDocumentFragment(); fragment.createChild("div", "attribute-name").textContent = name + ":"; fragment.createChild("div", "attribute-value source-code").textContent = value; return fragment; }, _refreshDatabase: function() { this._securityOriginTreeElement.title = this._formatHeader(WebInspector.UIString("Security origin"), this._database.databaseId.securityOrigin); this._nameTreeElement.title = this._formatHeader(WebInspector.UIString("Name"), this._database.databaseId.name); this._stringVersionTreeElement.title = this._formatHeader(WebInspector.UIString("String Version"), this._database.version); this._intVersionTreeElement.title = this._formatHeader(WebInspector.UIString("Integer Version"), this._database.intVersion); }, update: function(database) { this._database = database; this._refreshDatabase(); }, __proto__: WebInspector.View.prototype } WebInspector.IDBDataView = function(model, databaseId, objectStore, index) { WebInspector.View.call(this); this.registerRequiredCSS("indexedDBViews.css"); this._model = model; this._databaseId = databaseId; this._isIndex = !!index; this.element.addStyleClass("indexed-db-data-view"); var editorToolbar = this._createEditorToolbar(); this.element.appendChild(editorToolbar); this._dataGridContainer = this.element.createChild("div", "fill"); this._dataGridContainer.addStyleClass("data-grid-container"); this._refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item"); this._refreshButton.addEventListener("click", this._refreshButtonClicked, this); this._pageSize = 50; this._skipCount = 0; this.update(objectStore, index); this._entries = []; } WebInspector.IDBDataView.prototype = { _createDataGrid: function() { var columns = {}; columns["number"] = {}; columns["number"].title = WebInspector.UIString("#"); columns["number"].width = "50px"; var keyPath = this._isIndex ? this._index.keyPath : this._objectStore.keyPath; columns["key"] = {}; columns["key"].titleDOMFragment = this._keyColumnHeaderFragment(WebInspector.UIString("Key"), keyPath); if (this._isIndex) { columns["primaryKey"] = {}; columns["primaryKey"].titleDOMFragment = this._keyColumnHeaderFragment(WebInspector.UIString("Primary key"), this._objectStore.keyPath); } columns["value"] = {}; columns["value"].title = WebInspector.UIString("Value"); var dataGrid = new WebInspector.DataGrid(columns); return dataGrid; }, _keyColumnHeaderFragment: function(prefix, keyPath) { var keyColumnHeaderFragment = document.createDocumentFragment(); keyColumnHeaderFragment.appendChild(document.createTextNode(prefix)); if (keyPath === null) return keyColumnHeaderFragment; keyColumnHeaderFragment.appendChild(document.createTextNode(" (" + WebInspector.UIString("Key path: "))); if (keyPath instanceof Array) { keyColumnHeaderFragment.appendChild(document.createTextNode("[")); for (var i = 0; i < keyPath.length; ++i) { if (i != 0) keyColumnHeaderFragment.appendChild(document.createTextNode(", ")); keyColumnHeaderFragment.appendChild(this._keyPathStringFragment(keyPath[i])); } keyColumnHeaderFragment.appendChild(document.createTextNode("]")); } else { var keyPathString = (keyPath); keyColumnHeaderFragment.appendChild(this._keyPathStringFragment(keyPathString)); } keyColumnHeaderFragment.appendChild(document.createTextNode(")")); return keyColumnHeaderFragment; }, _keyPathStringFragment: function(keyPathString) { var keyPathStringFragment = document.createDocumentFragment(); keyPathStringFragment.appendChild(document.createTextNode("\"")); var keyPathSpan = keyPathStringFragment.createChild("span", "source-code console-formatted-string"); keyPathSpan.textContent = keyPathString; keyPathStringFragment.appendChild(document.createTextNode("\"")); return keyPathStringFragment; }, _createEditorToolbar: function() { var editorToolbar = document.createElement("div"); editorToolbar.addStyleClass("status-bar"); editorToolbar.addStyleClass("data-view-toolbar"); this._pageBackButton = editorToolbar.createChild("button", "back-button"); this._pageBackButton.addStyleClass("status-bar-item"); this._pageBackButton.title = WebInspector.UIString("Show previous page."); this._pageBackButton.disabled = true; this._pageBackButton.appendChild(document.createElement("img")); this._pageBackButton.addEventListener("click", this._pageBackButtonClicked.bind(this), false); editorToolbar.appendChild(this._pageBackButton); this._pageForwardButton = editorToolbar.createChild("button", "forward-button"); this._pageForwardButton.addStyleClass("status-bar-item"); this._pageForwardButton.title = WebInspector.UIString("Show next page."); this._pageForwardButton.disabled = true; this._pageForwardButton.appendChild(document.createElement("img")); this._pageForwardButton.addEventListener("click", this._pageForwardButtonClicked.bind(this), false); editorToolbar.appendChild(this._pageForwardButton); this._keyInputElement = editorToolbar.createChild("input", "key-input"); this._keyInputElement.placeholder = WebInspector.UIString("Start from key"); this._keyInputElement.addEventListener("paste", this._keyInputChanged.bind(this)); this._keyInputElement.addEventListener("cut", this._keyInputChanged.bind(this)); this._keyInputElement.addEventListener("keypress", this._keyInputChanged.bind(this)); this._keyInputElement.addEventListener("keydown", this._keyInputChanged.bind(this)); return editorToolbar; }, _pageBackButtonClicked: function() { this._skipCount = Math.max(0, this._skipCount - this._pageSize); this._updateData(false); }, _pageForwardButtonClicked: function() { this._skipCount = this._skipCount + this._pageSize; this._updateData(false); }, _keyInputChanged: function() { window.setTimeout(this._updateData.bind(this, false), 0); }, update: function(objectStore, index) { this._objectStore = objectStore; this._index = index; if (this._dataGrid) this._dataGrid.detach(); this._dataGrid = this._createDataGrid(); this._dataGrid.show(this._dataGridContainer); this._skipCount = 0; this._updateData(true); }, _parseKey: function(keyString) { var result; try { result = JSON.parse(keyString); } catch (e) { result = keyString; } return result; }, _stringifyKey: function(key) { if (typeof(key) === "string") return key; return JSON.stringify(key); }, _updateData: function(force) { var key = this._parseKey(this._keyInputElement.value); var pageSize = this._pageSize; var skipCount = this._skipCount; if (!force && this._lastKey === key && this._lastPageSize === pageSize && this._lastSkipCount === skipCount) return; if (this._lastKey !== key || this._lastPageSize !== pageSize) { skipCount = 0; this._skipCount = 0; } this._lastKey = key; this._lastPageSize = pageSize; this._lastSkipCount = skipCount; function callback(entries, hasMore) { this.clear(); this._entries = entries; for (var i = 0; i < entries.length; ++i) { var data = {}; data["number"] = i + skipCount; data["key"] = entries[i].key; data["primaryKey"] = entries[i].primaryKey; data["value"] = entries[i].value; var primaryKey = JSON.stringify(this._isIndex ? entries[i].primaryKey : entries[i].key); var node = new WebInspector.IDBDataGridNode(data); this._dataGrid.rootNode().appendChild(node); } this._pageBackButton.disabled = skipCount === 0; this._pageForwardButton.disabled = !hasMore; } var idbKeyRange = key ? window.webkitIDBKeyRange.lowerBound(key) : null; if (this._isIndex) this._model.loadIndexData(this._databaseId, this._objectStore.name, this._index.name, idbKeyRange, skipCount, pageSize, callback.bind(this)); else this._model.loadObjectStoreData(this._databaseId, this._objectStore.name, idbKeyRange, skipCount, pageSize, callback.bind(this)); }, _refreshButtonClicked: function(event) { this._updateData(true); }, get statusBarItems() { return [this._refreshButton.element]; }, clear: function() { this._dataGrid.rootNode().removeChildren(); for (var i = 0; i < this._entries.length; ++i) { this._entries[i].key.release(); this._entries[i].primaryKey.release(); this._entries[i].value.release(); } this._entries = []; }, __proto__: WebInspector.View.prototype } WebInspector.IDBDataGridNode = function(data) { WebInspector.DataGridNode.call(this, data, false); this.selectable = false; } WebInspector.IDBDataGridNode.prototype = { createCell: function(columnIdentifier) { var cell = WebInspector.DataGridNode.prototype.createCell.call(this, columnIdentifier); var value = this.data[columnIdentifier]; switch (columnIdentifier) { case "value": case "key": case "primaryKey": cell.removeChildren(); this._formatValue(cell, value); break; default: } return cell; }, _formatValue: function(cell, value) { var type = value.subtype || value.type; var contents = cell.createChild("div", "source-code console-formatted-" + type); switch (type) { case "object": case "array": var section = new WebInspector.ObjectPropertiesSection(value, value.description) section.editable = false; section.skipProto = true; contents.appendChild(section.element); break; case "string": contents.addStyleClass("primitive-value"); contents.appendChild(document.createTextNode("\"" + value.description + "\"")); break; default: contents.addStyleClass("primitive-value"); contents.appendChild(document.createTextNode(value.description)); } }, __proto__: WebInspector.DataGridNode.prototype } ; WebInspector.FileContentView = function(file) { WebInspector.View.call(this); this._innerView = null; this._file = file; this._content = null; } WebInspector.FileContentView.prototype = { wasShown: function() { if (!this._innerView) { if (this._file.isTextFile) this._innerView = new WebInspector.EmptyView(""); else this._innerView = new WebInspector.EmptyView(WebInspector.UIString("Binary File")); this.refresh(); } this._innerView.show(this.element); }, _metadataReceived: function(errorCode, metadata) { if (errorCode || !metadata) return; if (this._content) { if (!this._content.updateMetadata(metadata)) return; var sourceFrame = (this._innerView); this._content.requestContent(sourceFrame.setContent.bind(sourceFrame)); } else { this._innerView.detach(); this._content = new WebInspector.FileContentView.FileContentProvider(this._file, metadata); this._innerView = new WebInspector.SourceFrame(this._content); this._innerView.show(this.element); } }, refresh: function() { if (!this._innerView) return; if (this._file.isTextFile) this._file.requestMetadata(this._metadataReceived.bind(this)); }, __proto__: WebInspector.View.prototype } WebInspector.FileContentView.FileContentProvider = function(file, metadata) { this._file = file; this._metadata = metadata; } WebInspector.FileContentView.FileContentProvider.prototype = { contentURL: function() { return this._file.url; }, contentType: function() { return this._file.resourceType; }, requestContent: function(callback) { var size = (this._metadata.size); this._file.requestFileContent(true, 0, size, this._charset || "", this._fileContentReceived.bind(this, callback)); }, _fileContentReceived: function(callback, errorCode, content, base64Encoded, charset) { if (errorCode || !content) { callback(null, false, ""); return; } this._charset = charset; callback(content, false, this.contentType().canonicalMimeType()); }, searchInContent: function(query, caseSensitive, isRegex, callback) { setTimeout(callback.bind(null, []), 0); }, updateMetadata: function(metadata) { if (this._metadata.modificationTime >= metadata.modificationTime) return false; this._metadata = metadata.modificationTime; return true; } } ; WebInspector.FileSystemView = function(fileSystem) { WebInspector.SidebarView.call(this, WebInspector.SidebarView.SidebarPosition.Left, "FileSystemViewSidebarWidth"); this.element.addStyleClass("file-system-view"); this.element.addStyleClass("storage-view"); var directoryTreeElement = this.element.createChild("ol", "filesystem-directory-tree"); this._directoryTree = new TreeOutline(directoryTreeElement); this.sidebarElement.appendChild(directoryTreeElement); this.sidebarElement.addStyleClass("outline-disclosure"); this.sidebarElement.addStyleClass("sidebar"); var rootItem = new WebInspector.FileSystemView.EntryTreeElement(this, fileSystem.root); rootItem.expanded = true; this._directoryTree.appendChild(rootItem); this._visibleView = null; this._refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item"); this._refreshButton.visible = true; this._refreshButton.addEventListener("click", this._refresh, this); this._deleteButton = new WebInspector.StatusBarButton(WebInspector.UIString("Delete"), "delete-storage-status-bar-item"); this._deleteButton.visible = true; this._deleteButton.addEventListener("click", this._confirmDelete, this); } WebInspector.FileSystemView.prototype = { get statusBarItems() { return [this._refreshButton.element, this._deleteButton.element]; }, get visibleView() { return this._visibleView; }, showView: function(view) { if (this._visibleView === view) return; if (this._visibleView) this._visibleView.detach(); this._visibleView = view; view.show(this.mainElement); }, _refresh: function() { this._directoryTree.children[0].refresh(); }, _confirmDelete: function() { if (confirm(WebInspector.UIString("Are you sure you want to delete the selected entry?"))) this._delete(); }, _delete: function() { this._directoryTree.selectedTreeElement.deleteEntry(); }, __proto__: WebInspector.SidebarView.prototype } WebInspector.FileSystemView.EntryTreeElement = function(fileSystemView, entry) { TreeElement.call(this, entry.name, null, entry.isDirectory); this._entry = entry; this._fileSystemView = fileSystemView; } WebInspector.FileSystemView.EntryTreeElement.prototype = { onattach: function() { var selection = this.listItemElement.createChild("div", "selection"); this.listItemElement.insertBefore(selection, this.listItemElement.firstChild); }, onselect: function() { if (!this._view) { if (this._entry.isDirectory) this._view = new WebInspector.DirectoryContentView(); else { var file = (this._entry); this._view = new WebInspector.FileContentView(file); } } this._fileSystemView.showView(this._view); this.refresh(); }, onpopulate: function() { this.refresh(); }, _directoryContentReceived: function(errorCode, entries) { if (errorCode === FileError.NOT_FOUND_ERR) { if (this.parent !== this.treeOutline) this.parent.refresh(); return; } if (errorCode !== 0 || !entries) { console.error("Failed to read directory: " + errorCode); return; } entries.sort(WebInspector.FileSystemModel.Entry.compare); if (this._view) this._view.showEntries(entries); var oldChildren = this.children.slice(0); var newEntryIndex = 0; var oldChildIndex = 0; var currentTreeItem = 0; while (newEntryIndex < entries.length && oldChildIndex < oldChildren.length) { var newEntry = entries[newEntryIndex]; var oldChild = oldChildren[oldChildIndex]; var order = newEntry.name.localeCompare(oldChild._entry.name); if (order === 0) { if (oldChild._entry.isDirectory) oldChild.shouldRefreshChildren = true; else oldChild.refresh(); ++newEntryIndex; ++oldChildIndex; ++currentTreeItem; continue; } if (order < 0) { this.insertChild(new WebInspector.FileSystemView.EntryTreeElement(this._fileSystemView, newEntry), currentTreeItem); ++newEntryIndex; ++currentTreeItem; continue; } this.removeChildAtIndex(currentTreeItem); ++oldChildIndex; } for (; newEntryIndex < entries.length; ++newEntryIndex) this.appendChild(new WebInspector.FileSystemView.EntryTreeElement(this._fileSystemView, entries[newEntryIndex])); for (; oldChildIndex < oldChildren.length; ++oldChildIndex) this.removeChild(oldChildren[oldChildIndex]); }, refresh: function() { if (!this._entry.isDirectory) { if (this._view && this._view === this._fileSystemView.visibleView) { var fileContentView = (this._view); fileContentView.refresh(); } } else this._entry.requestDirectoryContent(this._directoryContentReceived.bind(this)); }, deleteEntry: function() { this._entry.deleteEntry(this._deletionCompleted.bind(this)); }, _deletionCompleted: function() { if (this._entry != this._entry.fileSystem.root) this.parent.refresh(); }, __proto__: TreeElement.prototype } ; WebInspector.ResourcesPanel = function(database) { WebInspector.Panel.call(this, "resources"); this.registerRequiredCSS("resourcesPanel.css"); WebInspector.settings.resourcesLastSelectedItem = WebInspector.settings.createSetting("resourcesLastSelectedItem", {}); this.createSidebarViewWithTree(); this.sidebarElement.addStyleClass("outline-disclosure"); this.sidebarElement.addStyleClass("filter-all"); this.sidebarElement.addStyleClass("children"); this.sidebarElement.addStyleClass("small"); this.sidebarTreeElement.removeStyleClass("sidebar-tree"); this.resourcesListTreeElement = new WebInspector.StorageCategoryTreeElement(this, WebInspector.UIString("Frames"), "Frames", ["frame-storage-tree-item"]); this.sidebarTree.appendChild(this.resourcesListTreeElement); this.databasesListTreeElement = new WebInspector.StorageCategoryTreeElement(this, WebInspector.UIString("Web SQL"), "Databases", ["database-storage-tree-item"]); this.sidebarTree.appendChild(this.databasesListTreeElement); this.indexedDBListTreeElement = new WebInspector.IndexedDBTreeElement(this); this.sidebarTree.appendChild(this.indexedDBListTreeElement); this.localStorageListTreeElement = new WebInspector.StorageCategoryTreeElement(this, WebInspector.UIString("Local Storage"), "LocalStorage", ["domstorage-storage-tree-item", "local-storage"]); this.sidebarTree.appendChild(this.localStorageListTreeElement); this.sessionStorageListTreeElement = new WebInspector.StorageCategoryTreeElement(this, WebInspector.UIString("Session Storage"), "SessionStorage", ["domstorage-storage-tree-item", "session-storage"]); this.sidebarTree.appendChild(this.sessionStorageListTreeElement); this.cookieListTreeElement = new WebInspector.StorageCategoryTreeElement(this, WebInspector.UIString("Cookies"), "Cookies", ["cookie-storage-tree-item"]); this.sidebarTree.appendChild(this.cookieListTreeElement); this.applicationCacheListTreeElement = new WebInspector.StorageCategoryTreeElement(this, WebInspector.UIString("Application Cache"), "ApplicationCache", ["application-cache-storage-tree-item"]); this.sidebarTree.appendChild(this.applicationCacheListTreeElement); if (Preferences.exposeFileSystemInspection && WebInspector.experimentsSettings.fileSystemInspection.isEnabled()) { this.fileSystemListTreeElement = new WebInspector.FileSystemListTreeElement(this); this.sidebarTree.appendChild(this.fileSystemListTreeElement); } this.storageViews = this.splitView.mainElement; this.storageViews.addStyleClass("diff-container"); this.storageViewStatusBarItemsContainer = document.createElement("div"); this.storageViewStatusBarItemsContainer.className = "status-bar-items"; this._databaseTableViews = new Map(); this._databaseQueryViews = new Map(); this._databaseTreeElements = new Map(); this._domStorageViews = new Map(); this._domStorageTreeElements = new Map(); this._cookieViews = {}; this._origins = {}; this._domains = {}; this.sidebarElement.addEventListener("mousemove", this._onmousemove.bind(this), false); this.sidebarElement.addEventListener("mouseout", this._onmouseout.bind(this), false); function viewGetter() { return this.visibleView; } WebInspector.GoToLineDialog.install(this, viewGetter.bind(this)); if (WebInspector.resourceTreeModel.cachedResourcesLoaded()) this._cachedResourcesLoaded(); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.OnLoad, this._onLoadEventFired, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, this._cachedResourcesLoaded, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.WillLoadCachedResources, this._resetWithFrames, this); WebInspector.databaseModel.databases().forEach(this._addDatabase.bind(this)); WebInspector.databaseModel.addEventListener(WebInspector.DatabaseModel.Events.DatabaseAdded, this._databaseAdded, this); WebInspector.domStorageModel.storages().forEach(this._addDOMStorage.bind(this)); WebInspector.domStorageModel.addEventListener(WebInspector.DOMStorageModel.Events.DOMStorageAdded, this._domStorageAdded, this); WebInspector.domStorageModel.addEventListener(WebInspector.DOMStorageModel.Events.DOMStorageUpdated, this._domStorageUpdated, this); } WebInspector.ResourcesPanel.prototype = { get statusBarItems() { return [this.storageViewStatusBarItemsContainer]; }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); this._initialize(); }, _initialize: function() { if (!this._initialized && this.isShowing() && this._cachedResourcesWereLoaded) { this._populateResourceTree(); this._populateApplicationCacheTree(); this._initDefaultSelection(); this._initialized = true; } }, _onLoadEventFired: function() { this._initDefaultSelection(); }, _initDefaultSelection: function() { if (!this._initialized) return; var itemURL = WebInspector.settings.resourcesLastSelectedItem.get(); if (itemURL) { for (var treeElement = this.sidebarTree.children[0]; treeElement; treeElement = treeElement.traverseNextTreeElement(false, this.sidebarTree, true)) { if (treeElement.itemURL === itemURL) { treeElement.revealAndSelect(true); return; } } } var mainResource = WebInspector.inspectedPageURL && this.resourcesListTreeElement && this.resourcesListTreeElement.expanded && WebInspector.resourceTreeModel.resourceForURL(WebInspector.inspectedPageURL); if (mainResource) this.showResource(mainResource); }, _resetWithFrames: function() { this.resourcesListTreeElement.removeChildren(); this._treeElementForFrameId = {}; this._reset(); }, _reset: function() { this._origins = {}; this._domains = {}; var queryViews = this._databaseQueryViews.values(); for (var i = 0; i < queryViews.length; ++i) queryViews[i].removeEventListener(WebInspector.DatabaseQueryView.Events.SchemaUpdated, this._updateDatabaseTables, this); this._databaseTableViews.clear(); this._databaseQueryViews.clear(); this._databaseTreeElements.clear(); this._domStorageViews.clear(); this._domStorageTreeElements.clear(); this._cookieViews = {}; this.databasesListTreeElement.removeChildren(); this.localStorageListTreeElement.removeChildren(); this.sessionStorageListTreeElement.removeChildren(); this.cookieListTreeElement.removeChildren(); if (this.visibleView) this.visibleView.detach(); this.storageViewStatusBarItemsContainer.removeChildren(); if (this.sidebarTree.selectedTreeElement) this.sidebarTree.selectedTreeElement.deselect(); }, _populateResourceTree: function() { this._treeElementForFrameId = {}; WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, this._resourceAdded, this); function populateFrame(frame) { this._frameAdded({data:frame}); for (var i = 0; i < frame.childFrames.length; ++i) populateFrame.call(this, frame.childFrames[i]); var resources = frame.resources(); for (var i = 0; i < resources.length; ++i) this._resourceAdded({data:resources[i]}); } populateFrame.call(this, WebInspector.resourceTreeModel.mainFrame); }, _frameAdded: function(event) { var frame = event.data; var parentFrame = frame.parentFrame; var parentTreeElement = parentFrame ? this._treeElementForFrameId[parentFrame.id] : this.resourcesListTreeElement; if (!parentTreeElement) { console.warn("No frame to route " + frame.url + " to.") return; } var frameTreeElement = new WebInspector.FrameTreeElement(this, frame); this._treeElementForFrameId[frame.id] = frameTreeElement; parentTreeElement.appendChild(frameTreeElement); }, _frameDetached: function(event) { var frame = event.data; var frameTreeElement = this._treeElementForFrameId[frame.id]; if (!frameTreeElement) return; delete this._treeElementForFrameId[frame.id]; if (frameTreeElement.parent) frameTreeElement.parent.removeChild(frameTreeElement); }, _resourceAdded: function(event) { var resource = event.data; var frameId = resource.frameId; if (resource.statusCode >= 301 && resource.statusCode <= 303) return; var frameTreeElement = this._treeElementForFrameId[frameId]; if (!frameTreeElement) { return; } frameTreeElement.appendResource(resource); }, _frameNavigated: function(event) { var frame = event.data; if (!frame.parentFrame) this._reset(); var frameId = frame.id; var frameTreeElement = this._treeElementForFrameId[frameId]; if (frameTreeElement) frameTreeElement.frameNavigated(frame); var applicationCacheFrameTreeElement = this._applicationCacheFrameElements[frameId]; if (applicationCacheFrameTreeElement) applicationCacheFrameTreeElement.frameNavigated(frame); }, _cachedResourcesLoaded: function() { this._cachedResourcesWereLoaded = true; this._initialize(); }, _databaseAdded: function(event) { var database = (event.data); this._addDatabase(database); }, _addDatabase: function(database) { var databaseTreeElement = new WebInspector.DatabaseTreeElement(this, database); this._databaseTreeElements.put(database, databaseTreeElement); this.databasesListTreeElement.appendChild(databaseTreeElement); }, addDocumentURL: function(url) { var parsedURL = url.asParsedURL(); if (!parsedURL) return; var domain = parsedURL.host; if (!this._domains[domain]) { this._domains[domain] = true; var cookieDomainTreeElement = new WebInspector.CookieTreeElement(this, domain); this.cookieListTreeElement.appendChild(cookieDomainTreeElement); } }, _domStorageAdded: function(event) { var domStorage = (event.data); this._addDOMStorage(domStorage); }, _addDOMStorage: function(domStorage) { var domStorageTreeElement = new WebInspector.DOMStorageTreeElement(this, domStorage, (domStorage.isLocalStorage ? "local-storage" : "session-storage")); this._domStorageTreeElements.put(domStorage, domStorageTreeElement); if (domStorage.isLocalStorage) this.localStorageListTreeElement.appendChild(domStorageTreeElement); else this.sessionStorageListTreeElement.appendChild(domStorageTreeElement); }, selectDatabase: function(database) { if (database) { this._showDatabase(database); this._databaseTreeElements.get(database).select(); } }, selectDOMStorage: function(domStorage) { if (domStorage) { this._showDOMStorage(domStorage); this._domStorageTreeElements.get(domStorage).select(); } }, canShowAnchorLocation: function(anchor) { return !!WebInspector.resourceForURL(anchor.href); }, showAnchorLocation: function(anchor) { var resource = WebInspector.resourceForURL(anchor.href); this.showResource(resource, anchor.lineNumber); }, showResource: function(resource, line) { var resourceTreeElement = this._findTreeElementForResource(resource); if (resourceTreeElement) resourceTreeElement.revealAndSelect(); if (typeof line === "number") { var view = this._resourceViewForResource(resource); if (view.canHighlightLine()) view.highlightLine(line); } return true; }, _showResourceView: function(resource) { var view = this._resourceViewForResource(resource); if (!view) { this.visibleView.detach(); return; } if (view.searchCanceled) view.searchCanceled(); this._innerShowView(view); }, _resourceViewForResource: function(resource) { if (WebInspector.ResourceView.hasTextContent(resource)) { var treeElement = this._findTreeElementForResource(resource); if (!treeElement) return null; return treeElement.sourceView(); } return WebInspector.ResourceView.nonSourceViewForResource(resource); }, _showDatabase: function(database, tableName) { if (!database) return; var view; if (tableName) { var tableViews = this._databaseTableViews.get(database); if (!tableViews) { tableViews = {}; this._databaseTableViews.put(database, tableViews); } view = tableViews[tableName]; if (!view) { view = new WebInspector.DatabaseTableView(database, tableName); tableViews[tableName] = view; } } else { view = this._databaseQueryViews.get(database); if (!view) { view = new WebInspector.DatabaseQueryView(database); this._databaseQueryViews.put(database, view); view.addEventListener(WebInspector.DatabaseQueryView.Events.SchemaUpdated, this._updateDatabaseTables, this); } } this._innerShowView(view); }, showIndexedDB: function(view) { this._innerShowView(view); }, _showDOMStorage: function(domStorage) { if (!domStorage) return; var view; view = this._domStorageViews.get(domStorage); if (!view) { view = new WebInspector.DOMStorageItemsView(domStorage); this._domStorageViews.put(domStorage, view); } this._innerShowView(view); }, showCookies: function(treeElement, cookieDomain) { var view = this._cookieViews[cookieDomain]; if (!view) { view = new WebInspector.CookieItemsView(treeElement, cookieDomain); this._cookieViews[cookieDomain] = view; } this._innerShowView(view); }, showApplicationCache: function(frameId) { if (!this._applicationCacheViews[frameId]) this._applicationCacheViews[frameId] = new WebInspector.ApplicationCacheItemsView(this._applicationCacheModel, frameId); this._innerShowView(this._applicationCacheViews[frameId]); }, showFileSystem: function(view) { this._innerShowView(view); }, showCategoryView: function(categoryName) { if (!this._categoryView) this._categoryView = new WebInspector.StorageCategoryView(); this._categoryView.setText(categoryName); this._innerShowView(this._categoryView); }, _innerShowView: function(view) { if (this.visibleView === view) return; if (this.visibleView) this.visibleView.detach(); view.show(this.storageViews); this.visibleView = view; this.storageViewStatusBarItemsContainer.removeChildren(); var statusBarItems = view.statusBarItems || []; for (var i = 0; i < statusBarItems.length; ++i) this.storageViewStatusBarItemsContainer.appendChild(statusBarItems[i]); }, closeVisibleView: function() { if (!this.visibleView) return; this.visibleView.detach(); delete this.visibleView; }, _updateDatabaseTables: function(event) { var database = event.data; if (!database) return; var databasesTreeElement = this._databaseTreeElements.get(database); if (!databasesTreeElement) return; databasesTreeElement.shouldRefreshChildren = true; var tableViews = this._databaseTableViews.get(database); if (!tableViews) return; var tableNamesHash = {}; var self = this; function tableNamesCallback(tableNames) { var tableNamesLength = tableNames.length; for (var i = 0; i < tableNamesLength; ++i) tableNamesHash[tableNames[i]] = true; for (var tableName in tableViews) { if (!(tableName in tableNamesHash)) { if (self.visibleView === tableViews[tableName]) self.closeVisibleView(); delete tableViews[tableName]; } } } database.getTableNames(tableNamesCallback); }, _domStorageUpdated: function(event) { var storage = (event.data); var view = this._domStorageViews.get(storage); if (this.visibleView && view === this.visibleView) view.update(); }, _populateApplicationCacheTree: function() { this._applicationCacheModel = new WebInspector.ApplicationCacheModel(); this._applicationCacheViews = {}; this._applicationCacheFrameElements = {}; this._applicationCacheManifestElements = {}; this._applicationCacheModel.addEventListener(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestAdded, this._applicationCacheFrameManifestAdded, this); this._applicationCacheModel.addEventListener(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestRemoved, this._applicationCacheFrameManifestRemoved, this); this._applicationCacheModel.addEventListener(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestStatusUpdated, this._applicationCacheFrameManifestStatusChanged, this); this._applicationCacheModel.addEventListener(WebInspector.ApplicationCacheModel.EventTypes.NetworkStateChanged, this._applicationCacheNetworkStateChanged, this); }, _applicationCacheFrameManifestAdded: function(event) { var frameId = event.data; var manifestURL = this._applicationCacheModel.frameManifestURL(frameId); var status = this._applicationCacheModel.frameManifestStatus(frameId) var manifestTreeElement = this._applicationCacheManifestElements[manifestURL] if (!manifestTreeElement) { manifestTreeElement = new WebInspector.ApplicationCacheManifestTreeElement(this, manifestURL); this.applicationCacheListTreeElement.appendChild(manifestTreeElement); this._applicationCacheManifestElements[manifestURL] = manifestTreeElement; } var frameTreeElement = new WebInspector.ApplicationCacheFrameTreeElement(this, frameId, manifestURL); manifestTreeElement.appendChild(frameTreeElement); manifestTreeElement.expand(); this._applicationCacheFrameElements[frameId] = frameTreeElement; }, _applicationCacheFrameManifestRemoved: function(event) { var frameId = event.data; var frameTreeElement = this._applicationCacheFrameElements[frameId]; if (!frameTreeElement) return; var manifestURL = frameTreeElement.manifestURL; delete this._applicationCacheFrameElements[frameId]; delete this._applicationCacheViews[frameId]; frameTreeElement.parent.removeChild(frameTreeElement); var manifestTreeElement = this._applicationCacheManifestElements[manifestURL]; if (manifestTreeElement.children.length !== 0) return; delete this._applicationCacheManifestElements[manifestURL]; manifestTreeElement.parent.removeChild(manifestTreeElement); }, _applicationCacheFrameManifestStatusChanged: function(event) { var frameId = event.data; var status = this._applicationCacheModel.frameManifestStatus(frameId) if (this._applicationCacheViews[frameId]) this._applicationCacheViews[frameId].updateStatus(status); }, _applicationCacheNetworkStateChanged: function(event) { var isNowOnline = event.data; for (var manifestURL in this._applicationCacheViews) this._applicationCacheViews[manifestURL].updateNetworkState(isNowOnline); }, sidebarResized: function(event) { var width = event.data; this.storageViewStatusBarItemsContainer.style.left = width + "px"; }, performSearch: function(query) { this._resetSearchResults(); var regex = WebInspector.SourceFrame.createSearchRegex(query); var totalMatchesCount = 0; function callback(error, result) { if (!error) { for (var i = 0; i < result.length; i++) { var searchResult = result[i]; var frameTreeElement = this._treeElementForFrameId[searchResult.frameId]; if (!frameTreeElement) continue; var resource = frameTreeElement.resourceByURL(searchResult.url); if (!resource) continue; this._findTreeElementForResource(resource).searchMatchesFound(searchResult.matchesCount); totalMatchesCount += searchResult.matchesCount; } } WebInspector.searchController.updateSearchMatchesCount(totalMatchesCount, this); this._searchController = new WebInspector.ResourcesSearchController(this.resourcesListTreeElement, totalMatchesCount); if (this.sidebarTree.selectedTreeElement && this.sidebarTree.selectedTreeElement.searchMatchesCount) this.jumpToNextSearchResult(); } PageAgent.searchInResources(regex.source, !regex.ignoreCase, true, callback.bind(this)); }, _ensureViewSearchPerformed: function(callback) { function viewSearchPerformedCallback(searchId) { if (searchId !== this._lastViewSearchId) return; this._viewSearchInProgress = false; callback(); } if (!this._viewSearchInProgress) { if (!this.visibleView.hasSearchResults()) { this._lastViewSearchId = this._lastViewSearchId ? this._lastViewSearchId + 1 : 0; this._viewSearchInProgress = true; this.visibleView.performSearch(this.currentQuery, viewSearchPerformedCallback.bind(this, this._lastViewSearchId)); } else callback(); } }, _showSearchResult: function(searchResult) { this._lastSearchResultIndex = searchResult.index; this._lastSearchResultTreeElement = searchResult.treeElement; if (searchResult.treeElement !== this.sidebarTree.selectedTreeElement) { this.showResource(searchResult.treeElement.representedObject); WebInspector.searchController.showSearchField(); } function callback(searchId) { if (this.sidebarTree.selectedTreeElement !== this._lastSearchResultTreeElement) return; if (this._lastSearchResultIndex != -1) this.visibleView.jumpToSearchResult(this._lastSearchResultIndex); WebInspector.searchController.updateCurrentMatchIndex(searchResult.currentMatchIndex - 1, this); } this._ensureViewSearchPerformed(callback.bind(this)); }, _resetSearchResults: function() { function callback(resourceTreeElement) { resourceTreeElement._resetSearchResults(); } this._forAllResourceTreeElements(callback); if (this.visibleView && this.visibleView.searchCanceled) this.visibleView.searchCanceled(); this._lastSearchResultTreeElement = null; this._lastSearchResultIndex = -1; this._viewSearchInProgress = false; }, searchCanceled: function() { function callback(resourceTreeElement) { resourceTreeElement._updateErrorsAndWarningsBubbles(); } WebInspector.searchController.updateSearchMatchesCount(0, this); this._resetSearchResults(); this._forAllResourceTreeElements(callback); }, jumpToNextSearchResult: function() { if (!this.currentSearchMatches) return; var currentTreeElement = this.sidebarTree.selectedTreeElement; var nextSearchResult = this._searchController.nextSearchResult(currentTreeElement); this._showSearchResult(nextSearchResult); }, jumpToPreviousSearchResult: function() { if (!this.currentSearchMatches) return; var currentTreeElement = this.sidebarTree.selectedTreeElement; var previousSearchResult = this._searchController.previousSearchResult(currentTreeElement); this._showSearchResult(previousSearchResult); }, _forAllResourceTreeElements: function(callback) { var stop = false; for (var treeElement = this.resourcesListTreeElement; !stop && treeElement; treeElement = treeElement.traverseNextTreeElement(false, this.resourcesListTreeElement, true)) { if (treeElement instanceof WebInspector.FrameResourceTreeElement) stop = callback(treeElement); } }, _findTreeElementForResource: function(resource) { function isAncestor(ancestor, object) { return false; } function getParent(object) { return null; } return this.sidebarTree.findTreeElement(resource, isAncestor, getParent); }, showView: function(view) { if (view) this.showResource(view.resource); }, _onmousemove: function(event) { var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); if (!nodeUnderMouse) return; var listNode = nodeUnderMouse.enclosingNodeOrSelfWithNodeName("li"); if (!listNode) return; var element = listNode.treeElement; if (this._previousHoveredElement === element) return; if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; delete this._previousHoveredElement; } if (element instanceof WebInspector.FrameTreeElement) { this._previousHoveredElement = element; element.hovered = true; } }, _onmouseout: function(event) { if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; delete this._previousHoveredElement; } }, __proto__: WebInspector.Panel.prototype } WebInspector.BaseStorageTreeElement = function(storagePanel, representedObject, title, iconClasses, hasChildren, noIcon) { TreeElement.call(this, "", representedObject, hasChildren); this._storagePanel = storagePanel; this._titleText = title; this._iconClasses = iconClasses; this._noIcon = noIcon; } WebInspector.BaseStorageTreeElement.prototype = { onattach: function() { this.listItemElement.removeChildren(); if (this._iconClasses) { for (var i = 0; i < this._iconClasses.length; ++i) this.listItemElement.addStyleClass(this._iconClasses[i]); } var selectionElement = document.createElement("div"); selectionElement.className = "selection"; this.listItemElement.appendChild(selectionElement); if (!this._noIcon) { this.imageElement = document.createElement("img"); this.imageElement.className = "icon"; this.listItemElement.appendChild(this.imageElement); } this.titleElement = document.createElement("div"); this.titleElement.className = "base-storage-tree-element-title"; this._titleTextNode = document.createTextNode(""); this.titleElement.appendChild(this._titleTextNode); this._updateTitle(); this._updateSubtitle(); this.listItemElement.appendChild(this.titleElement); }, get displayName() { return this._displayName; }, _updateDisplayName: function() { this._displayName = this._titleText || ""; if (this._subtitleText) this._displayName += " (" + this._subtitleText + ")"; }, _updateTitle: function() { this._updateDisplayName(); if (!this.titleElement) return; this._titleTextNode.textContent = this._titleText || ""; }, _updateSubtitle: function() { this._updateDisplayName(); if (!this.titleElement) return; if (this._subtitleText) { if (!this._subtitleElement) { this._subtitleElement = document.createElement("span"); this._subtitleElement.className = "base-storage-tree-element-subtitle"; this.titleElement.appendChild(this._subtitleElement); } this._subtitleElement.textContent = "(" + this._subtitleText + ")"; } else if (this._subtitleElement) { this.titleElement.removeChild(this._subtitleElement); delete this._subtitleElement; } }, onselect: function() { var itemURL = this.itemURL; if (itemURL) WebInspector.settings.resourcesLastSelectedItem.set(itemURL); }, onreveal: function() { if (this.listItemElement) this.listItemElement.scrollIntoViewIfNeeded(false); }, get titleText() { return this._titleText; }, set titleText(titleText) { this._titleText = titleText; this._updateTitle(); }, get subtitleText() { return this._subtitleText; }, set subtitleText(subtitleText) { this._subtitleText = subtitleText; this._updateSubtitle(); }, get searchMatchesCount() { return 0; }, __proto__: TreeElement.prototype } WebInspector.StorageCategoryTreeElement = function(storagePanel, categoryName, settingsKey, iconClasses, noIcon) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, categoryName, iconClasses, true, noIcon); this._expandedSettingKey = "resources" + settingsKey + "Expanded"; WebInspector.settings[this._expandedSettingKey] = WebInspector.settings.createSetting(this._expandedSettingKey, settingsKey === "Frames"); this._categoryName = categoryName; } WebInspector.StorageCategoryTreeElement.prototype = { get itemURL() { return "category://" + this._categoryName; }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel.showCategoryView(this._categoryName); }, onattach: function() { WebInspector.BaseStorageTreeElement.prototype.onattach.call(this); if (WebInspector.settings[this._expandedSettingKey].get()) this.expand(); }, onexpand: function() { WebInspector.settings[this._expandedSettingKey].set(true); }, oncollapse: function() { WebInspector.settings[this._expandedSettingKey].set(false); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.FrameTreeElement = function(storagePanel, frame) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, "", ["frame-storage-tree-item"]); this._frame = frame; this.frameNavigated(frame); } WebInspector.FrameTreeElement.prototype = { frameNavigated: function(frame) { this.removeChildren(); this._frameId = frame.id; this.titleText = frame.name; this.subtitleText = new WebInspector.ParsedURL(frame.url).displayName; this._categoryElements = {}; this._treeElementForResource = {}; this._storagePanel.addDocumentURL(frame.url); }, get itemURL() { return "frame://" + encodeURI(this.displayName); }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel.showCategoryView(this.displayName); this.listItemElement.removeStyleClass("hovered"); DOMAgent.hideHighlight(); }, set hovered(hovered) { if (hovered) { this.listItemElement.addStyleClass("hovered"); DOMAgent.highlightFrame(this._frameId, WebInspector.Color.PageHighlight.Content.toProtocolRGBA(), WebInspector.Color.PageHighlight.ContentOutline.toProtocolRGBA()); } else { this.listItemElement.removeStyleClass("hovered"); DOMAgent.hideHighlight(); } }, appendResource: function(resource) { if (resource.isHidden()) return; var categoryName = resource.type.name(); var categoryElement = resource.type === WebInspector.resourceTypes.Document ? this : this._categoryElements[categoryName]; if (!categoryElement) { categoryElement = new WebInspector.StorageCategoryTreeElement(this._storagePanel, resource.type.categoryTitle(), categoryName, null, true); this._categoryElements[resource.type.name()] = categoryElement; this._insertInPresentationOrder(this, categoryElement); } var resourceTreeElement = new WebInspector.FrameResourceTreeElement(this._storagePanel, resource); this._insertInPresentationOrder(categoryElement, resourceTreeElement); this._treeElementForResource[resource.url] = resourceTreeElement; }, resourceByURL: function(url) { var treeElement = this._treeElementForResource[url]; return treeElement ? treeElement.representedObject : null; }, appendChild: function(treeElement) { this._insertInPresentationOrder(this, treeElement); }, _insertInPresentationOrder: function(parentTreeElement, childTreeElement) { function typeWeight(treeElement) { if (treeElement instanceof WebInspector.StorageCategoryTreeElement) return 2; if (treeElement instanceof WebInspector.FrameTreeElement) return 1; return 3; } function compare(treeElement1, treeElement2) { var typeWeight1 = typeWeight(treeElement1); var typeWeight2 = typeWeight(treeElement2); var result; if (typeWeight1 > typeWeight2) result = 1; else if (typeWeight1 < typeWeight2) result = -1; else { var title1 = treeElement1.displayName || treeElement1.titleText; var title2 = treeElement2.displayName || treeElement2.titleText; result = title1.localeCompare(title2); } return result; } var children = parentTreeElement.children; var i; for (i = 0; i < children.length; ++i) { if (compare(childTreeElement, children[i]) < 0) break; } parentTreeElement.insertChild(childTreeElement, i); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.FrameResourceTreeElement = function(storagePanel, resource) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, resource, resource.displayName, ["resource-sidebar-tree-item", "resources-type-" + resource.type.name()]); this._resource = resource; this._resource.addEventListener(WebInspector.Resource.Events.MessageAdded, this._consoleMessageAdded, this); this._resource.addEventListener(WebInspector.Resource.Events.MessagesCleared, this._consoleMessagesCleared, this); this.tooltip = resource.url; } WebInspector.FrameResourceTreeElement.prototype = { get itemURL() { return this._resource.url; }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel._showResourceView(this._resource); }, ondblclick: function(event) { InspectorFrontendHost.openInNewTab(this._resource.url); }, onattach: function() { WebInspector.BaseStorageTreeElement.prototype.onattach.call(this); if (this._resource.type === WebInspector.resourceTypes.Image) { var previewImage = document.createElement("img"); previewImage.className = "image-resource-icon-preview"; this._resource.populateImageSource(previewImage); var iconElement = document.createElement("div"); iconElement.className = "icon"; iconElement.appendChild(previewImage); this.listItemElement.replaceChild(iconElement, this.imageElement); } this._statusElement = document.createElement("div"); this._statusElement.className = "status"; this.listItemElement.insertBefore(this._statusElement, this.titleElement); this.listItemElement.draggable = true; this.listItemElement.addEventListener("dragstart", this._ondragstart.bind(this), false); this.listItemElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); this._updateErrorsAndWarningsBubbles(); }, _ondragstart: function(event) { event.dataTransfer.setData("text/plain", this._resource.content); event.dataTransfer.effectAllowed = "copy"; return true; }, _handleContextMenuEvent: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendApplicableItems(this._resource); if (this._resource.request) contextMenu.appendApplicableItems(this._resource.request); contextMenu.show(); }, _setBubbleText: function(x) { if (!this._bubbleElement) { this._bubbleElement = document.createElement("div"); this._bubbleElement.className = "bubble"; this._statusElement.appendChild(this._bubbleElement); } this._bubbleElement.textContent = x; }, _resetBubble: function() { if (this._bubbleElement) { this._bubbleElement.textContent = ""; this._bubbleElement.removeStyleClass("search-matches"); this._bubbleElement.removeStyleClass("warning"); this._bubbleElement.removeStyleClass("error"); } }, _resetSearchResults: function() { this._resetBubble(); this._searchMatchesCount = 0; }, get searchMatchesCount() { return this._searchMatchesCount; }, searchMatchesFound: function(matchesCount) { this._resetSearchResults(); this._searchMatchesCount = matchesCount; this._setBubbleText(matchesCount); this._bubbleElement.addStyleClass("search-matches"); var currentAncestor = this.parent; while (currentAncestor && !currentAncestor.root) { if (!currentAncestor.expanded) currentAncestor.expand(); currentAncestor = currentAncestor.parent; } }, _updateErrorsAndWarningsBubbles: function() { if (this._storagePanel.currentQuery) return; this._resetBubble(); if (this._resource.warnings || this._resource.errors) this._setBubbleText(this._resource.warnings + this._resource.errors); if (this._resource.warnings) this._bubbleElement.addStyleClass("warning"); if (this._resource.errors) this._bubbleElement.addStyleClass("error"); }, _consoleMessagesCleared: function() { if (this._sourceView) this._sourceView.clearMessages(); this._updateErrorsAndWarningsBubbles(); }, _consoleMessageAdded: function(event) { var msg = event.data; if (this._sourceView) this._sourceView.addMessage(msg); this._updateErrorsAndWarningsBubbles(); }, sourceView: function() { if (!this._sourceView) { this._sourceView = new WebInspector.ResourceSourceFrame(this._resource); if (this._resource.messages) { for (var i = 0; i < this._resource.messages.length; i++) this._sourceView.addMessage(this._resource.messages[i]); } } return this._sourceView; }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.DatabaseTreeElement = function(storagePanel, database) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, database.name, ["database-storage-tree-item"], true); this._database = database; } WebInspector.DatabaseTreeElement.prototype = { get itemURL() { return "database://" + encodeURI(this._database.name); }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel._showDatabase(this._database); }, onexpand: function() { this._updateChildren(); }, _updateChildren: function() { this.removeChildren(); function tableNamesCallback(tableNames) { var tableNamesLength = tableNames.length; for (var i = 0; i < tableNamesLength; ++i) this.appendChild(new WebInspector.DatabaseTableTreeElement(this._storagePanel, this._database, tableNames[i])); } this._database.getTableNames(tableNamesCallback.bind(this)); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.DatabaseTableTreeElement = function(storagePanel, database, tableName) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, tableName, ["database-storage-tree-item"]); this._database = database; this._tableName = tableName; } WebInspector.DatabaseTableTreeElement.prototype = { get itemURL() { return "database://" + encodeURI(this._database.name) + "/" + encodeURI(this._tableName); }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel._showDatabase(this._database, this._tableName); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.IndexedDBTreeElement = function(storagePanel) { WebInspector.StorageCategoryTreeElement.call(this, storagePanel, WebInspector.UIString("IndexedDB"), "IndexedDB", ["indexed-db-storage-tree-item"]); } WebInspector.IndexedDBTreeElement.prototype = { onexpand: function() { WebInspector.StorageCategoryTreeElement.prototype.onexpand.call(this); if (!this._indexedDBModel) this._createIndexedDBModel(); }, onattach: function() { WebInspector.StorageCategoryTreeElement.prototype.onattach.call(this); this.listItemElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); }, _handleContextMenuEvent: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Refresh IndexedDB"), this.refreshIndexedDB.bind(this)); contextMenu.show(); }, _createIndexedDBModel: function() { this._indexedDBModel = new WebInspector.IndexedDBModel(); this._idbDatabaseTreeElements = []; this._indexedDBModel.addEventListener(WebInspector.IndexedDBModel.EventTypes.DatabaseAdded, this._indexedDBAdded, this); this._indexedDBModel.addEventListener(WebInspector.IndexedDBModel.EventTypes.DatabaseRemoved, this._indexedDBRemoved, this); this._indexedDBModel.addEventListener(WebInspector.IndexedDBModel.EventTypes.DatabaseLoaded, this._indexedDBLoaded, this); }, refreshIndexedDB: function() { if (!this._indexedDBModel) { this._createIndexedDBModel(); return; } this._indexedDBModel.refreshDatabaseNames(); }, _indexedDBAdded: function(event) { var databaseId = (event.data); var idbDatabaseTreeElement = new WebInspector.IDBDatabaseTreeElement(this._storagePanel, this._indexedDBModel, databaseId); this._idbDatabaseTreeElements.push(idbDatabaseTreeElement); this.appendChild(idbDatabaseTreeElement); this._indexedDBModel.refreshDatabase(databaseId); }, _indexedDBRemoved: function(event) { var databaseId = (event.data); var idbDatabaseTreeElement = this._idbDatabaseTreeElement(databaseId) if (!idbDatabaseTreeElement) return; idbDatabaseTreeElement.clear(); this.removeChild(idbDatabaseTreeElement); this._idbDatabaseTreeElements.remove(idbDatabaseTreeElement); }, _indexedDBLoaded: function(event) { var database = (event.data); var idbDatabaseTreeElement = this._idbDatabaseTreeElement(database.databaseId) if (!idbDatabaseTreeElement) return; idbDatabaseTreeElement.update(database); }, _idbDatabaseTreeElement: function(databaseId) { var index = -1; for (var i = 0; i < this._idbDatabaseTreeElements.length; ++i) { if (this._idbDatabaseTreeElements[i]._databaseId.equals(databaseId)) { index = i; break; } } if (index !== -1) return this._idbDatabaseTreeElements[i]; return null; }, __proto__: WebInspector.StorageCategoryTreeElement.prototype } WebInspector.FileSystemListTreeElement = function(storagePanel) { WebInspector.StorageCategoryTreeElement.call(this, storagePanel, WebInspector.UIString("FileSystem"), "FileSystem", ["file-system-storage-tree-item"]); } WebInspector.FileSystemListTreeElement.prototype = { onexpand: function() { WebInspector.StorageCategoryTreeElement.prototype.onexpand.call(this); this._refreshFileSystem(); }, onattach: function() { WebInspector.StorageCategoryTreeElement.prototype.onattach.call(this); this.listItemElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); }, _handleContextMenuEvent: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Refresh FileSystem List"), this._refreshFileSystem.bind(this)); contextMenu.show(); }, _fileSystemAdded: function(event) { var fileSystem = (event.data); var fileSystemTreeElement = new WebInspector.FileSystemTreeElement(this._storagePanel, fileSystem); this.appendChild(fileSystemTreeElement); }, _fileSystemRemoved: function(event) { var fileSystem = (event.data); var fileSystemTreeElement = this._fileSystemTreeElementByName(fileSystem.name); if (!fileSystemTreeElement) return; fileSystemTreeElement.clear(); this.removeChild(fileSystemTreeElement); }, _fileSystemTreeElementByName: function(fileSystemName) { for (var i = 0; i < this.children.length; ++i) { var child = (this.children[i]); if (child.fileSystemName === fileSystemName) return this.children[i]; } return null; }, _refreshFileSystem: function() { if (!this._fileSystemModel) { this._fileSystemModel = new WebInspector.FileSystemModel(); this._fileSystemModel.addEventListener(WebInspector.FileSystemModel.EventTypes.FileSystemAdded, this._fileSystemAdded, this); this._fileSystemModel.addEventListener(WebInspector.FileSystemModel.EventTypes.FileSystemRemoved, this._fileSystemRemoved, this); } this._fileSystemModel.refreshFileSystemList(); }, __proto__: WebInspector.StorageCategoryTreeElement.prototype } WebInspector.IDBDatabaseTreeElement = function(storagePanel, model, databaseId) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, databaseId.name + " - " + databaseId.securityOrigin, ["indexed-db-storage-tree-item"]); this._model = model; this._databaseId = databaseId; this._idbObjectStoreTreeElements = {}; } WebInspector.IDBDatabaseTreeElement.prototype = { get itemURL() { return "indexedDB://" + this._databaseId.securityOrigin + "/" + this._databaseId.name; }, onattach: function() { WebInspector.BaseStorageTreeElement.prototype.onattach.call(this); this.listItemElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); }, _handleContextMenuEvent: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Refresh IndexedDB"), this._refreshIndexedDB.bind(this)); contextMenu.show(); }, _refreshIndexedDB: function(event) { this._model.refreshDatabaseNames(); }, update: function(database) { this._database = database; var objectStoreNames = {}; for (var objectStoreName in this._database.objectStores) { var objectStore = this._database.objectStores[objectStoreName]; objectStoreNames[objectStore.name] = true; if (!this._idbObjectStoreTreeElements[objectStore.name]) { var idbObjectStoreTreeElement = new WebInspector.IDBObjectStoreTreeElement(this._storagePanel, this._model, this._databaseId, objectStore); this._idbObjectStoreTreeElements[objectStore.name] = idbObjectStoreTreeElement; this.appendChild(idbObjectStoreTreeElement); } this._idbObjectStoreTreeElements[objectStore.name].update(objectStore); } for (var objectStoreName in this._idbObjectStoreTreeElements) { if (!objectStoreNames[objectStoreName]) this._objectStoreRemoved(objectStoreName); } if (this.children.length) { this.hasChildren = true; this.expand(); } if (this._view) this._view.update(database); this._updateTooltip(); }, _updateTooltip: function() { this.tooltip = WebInspector.UIString("Version") + ": " + this._database.version; }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); if (!this._view) this._view = new WebInspector.IDBDatabaseView(this._database); this._storagePanel.showIndexedDB(this._view); }, _objectStoreRemoved: function(objectStoreName) { var objectStoreTreeElement = this._idbObjectStoreTreeElements[objectStoreName]; objectStoreTreeElement.clear(); this.removeChild(objectStoreTreeElement); delete this._idbObjectStoreTreeElements[objectStoreName]; }, clear: function() { for (var objectStoreName in this._idbObjectStoreTreeElements) this._objectStoreRemoved(objectStoreName); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.IDBObjectStoreTreeElement = function(storagePanel, model, databaseId, objectStore) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, objectStore.name, ["indexed-db-object-store-storage-tree-item"]); this._model = model; this._databaseId = databaseId; this._idbIndexTreeElements = {}; } WebInspector.IDBObjectStoreTreeElement.prototype = { get itemURL() { return "indexedDB://" + this._databaseId.securityOrigin + "/" + this._databaseId.name + "/" + this._objectStore.name; }, update: function(objectStore) { this._objectStore = objectStore; var indexNames = {}; for (var indexName in this._objectStore.indexes) { var index = this._objectStore.indexes[indexName]; indexNames[index.name] = true; if (!this._idbIndexTreeElements[index.name]) { var idbIndexTreeElement = new WebInspector.IDBIndexTreeElement(this._storagePanel, this._model, this._databaseId, this._objectStore, index); this._idbIndexTreeElements[index.name] = idbIndexTreeElement; this.appendChild(idbIndexTreeElement); } this._idbIndexTreeElements[index.name].update(index); } for (var indexName in this._idbIndexTreeElements) { if (!indexNames[indexName]) this._indexRemoved(indexName); } for (var indexName in this._idbIndexTreeElements) { if (!indexNames[indexName]) { this.removeChild(this._idbIndexTreeElements[indexName]); delete this._idbIndexTreeElements[indexName]; } } if (this.children.length) { this.hasChildren = true; this.expand(); } if (this._view) this._view.update(this._objectStore); this._updateTooltip(); }, _updateTooltip: function() { var keyPathString = this._objectStore.keyPathString; var tooltipString = keyPathString !== null ? (WebInspector.UIString("Key path: ") + keyPathString) : ""; if (this._objectStore.autoIncrement) tooltipString += "\n" + WebInspector.UIString("autoIncrement"); this.tooltip = tooltipString }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); if (!this._view) this._view = new WebInspector.IDBDataView(this._model, this._databaseId, this._objectStore, null); this._storagePanel.showIndexedDB(this._view); }, _indexRemoved: function(indexName) { var indexTreeElement = this._idbIndexTreeElements[indexName]; indexTreeElement.clear(); this.removeChild(indexTreeElement); delete this._idbIndexTreeElements[indexName]; }, clear: function() { for (var indexName in this._idbIndexTreeElements) this._indexRemoved(indexName); if (this._view) this._view.clear(); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.IDBIndexTreeElement = function(storagePanel, model, databaseId, objectStore, index) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, index.name, ["indexed-db-index-storage-tree-item"]); this._model = model; this._databaseId = databaseId; this._objectStore = objectStore; this._index = index; } WebInspector.IDBIndexTreeElement.prototype = { get itemURL() { return "indexedDB://" + this._databaseId.securityOrigin + "/" + this._databaseId.name + "/" + this._objectStore.name + "/" + this._index.name; }, update: function(index) { this._index = index; if (this._view) this._view.update(this._index); this._updateTooltip(); }, _updateTooltip: function() { var tooltipLines = []; var keyPathString = this._index.keyPathString; tooltipLines.push(WebInspector.UIString("Key path: ") + keyPathString); if (this._index.unique) tooltipLines.push(WebInspector.UIString("unique")); if (this._index.multiEntry) tooltipLines.push(WebInspector.UIString("multiEntry")); this.tooltip = tooltipLines.join("\n"); }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); if (!this._view) this._view = new WebInspector.IDBDataView(this._model, this._databaseId, this._objectStore, this._index); this._storagePanel.showIndexedDB(this._view); }, clear: function() { if (this._view) this._view.clear(); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.DOMStorageTreeElement = function(storagePanel, domStorage, className) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, domStorage.domain ? domStorage.domain : WebInspector.UIString("Local Files"), ["domstorage-storage-tree-item", className]); this._domStorage = domStorage; } WebInspector.DOMStorageTreeElement.prototype = { get itemURL() { return "storage://" + this._domStorage.domain + "/" + (this._domStorage.isLocalStorage ? "local" : "session"); }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel._showDOMStorage(this._domStorage); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.CookieTreeElement = function(storagePanel, cookieDomain) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, cookieDomain ? cookieDomain : WebInspector.UIString("Local Files"), ["cookie-storage-tree-item"]); this._cookieDomain = cookieDomain; } WebInspector.CookieTreeElement.prototype = { get itemURL() { return "cookies://" + this._cookieDomain; }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel.showCookies(this, this._cookieDomain); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.ApplicationCacheManifestTreeElement = function(storagePanel, manifestURL) { var title = new WebInspector.ParsedURL(manifestURL).displayName; WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, title, ["application-cache-storage-tree-item"]); this.tooltip = manifestURL; this._manifestURL = manifestURL; } WebInspector.ApplicationCacheManifestTreeElement.prototype = { get itemURL() { return "appcache://" + this._manifestURL; }, get manifestURL() { return this._manifestURL; }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel.showCategoryView(this._manifestURL); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.ApplicationCacheFrameTreeElement = function(storagePanel, frameId, manifestURL) { WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, "", ["frame-storage-tree-item"]); this._frameId = frameId; this._manifestURL = manifestURL; this._refreshTitles(); } WebInspector.ApplicationCacheFrameTreeElement.prototype = { get itemURL() { return "appcache://" + this._manifestURL + "/" + encodeURI(this.displayName); }, get frameId() { return this._frameId; }, get manifestURL() { return this._manifestURL; }, _refreshTitles: function() { var frame = WebInspector.resourceTreeModel.frameForId(this._frameId); if (!frame) { this.subtitleText = WebInspector.UIString("new frame"); return; } this.titleText = frame.name; this.subtitleText = new WebInspector.ParsedURL(frame.url).displayName; }, frameNavigated: function() { this._refreshTitles(); }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._storagePanel.showApplicationCache(this._frameId); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.FileSystemTreeElement = function(storagePanel, fileSystem) { var displayName = fileSystem.type + " - " + fileSystem.origin; WebInspector.BaseStorageTreeElement.call(this, storagePanel, null, displayName, ["file-system-storage-tree-item"]); this._fileSystem = fileSystem; } WebInspector.FileSystemTreeElement.prototype = { get fileSystemName() { return this._fileSystem.name; }, get itemURL() { return "filesystem://" + this._fileSystem.name; }, onselect: function() { WebInspector.BaseStorageTreeElement.prototype.onselect.call(this); this._fileSystemView = new WebInspector.FileSystemView(this._fileSystem); this._storagePanel.showFileSystem(this._fileSystemView); }, clear: function() { if (this.fileSystemView && this._storagePanel.visibleView == this.fileSystemView) this._storagePanel.closeVisibleView(); }, __proto__: WebInspector.BaseStorageTreeElement.prototype } WebInspector.StorageCategoryView = function() { WebInspector.View.call(this); this.element.addStyleClass("storage-view"); this._emptyView = new WebInspector.EmptyView(""); this._emptyView.show(this.element); } WebInspector.StorageCategoryView.prototype = { setText: function(text) { this._emptyView.text = text; }, __proto__: WebInspector.View.prototype } WebInspector.ResourcesSearchController = function(rootElement, matchesCount) { this._root = rootElement; this._matchesCount = matchesCount; this._traverser = new WebInspector.SearchResultsTreeElementsTraverser(rootElement); this._lastTreeElement = null; this._lastIndex = -1; } WebInspector.ResourcesSearchController.prototype = { nextSearchResult: function(currentTreeElement) { if (!currentTreeElement) return this._searchResult(this._traverser.first(), 0, 1); if (!currentTreeElement.searchMatchesCount) return this._searchResult(this._traverser.next(currentTreeElement), 0); if (this._lastTreeElement !== currentTreeElement || this._lastIndex === -1) return this._searchResult(currentTreeElement, 0); if (this._lastIndex == currentTreeElement.searchMatchesCount - 1) return this._searchResult(this._traverser.next(currentTreeElement), 0, this._currentMatchIndex % this._matchesCount + 1); return this._searchResult(currentTreeElement, this._lastIndex + 1, this._currentMatchIndex + 1); }, previousSearchResult: function(currentTreeElement) { if (!currentTreeElement) { var treeElement = this._traverser.last(); return this._searchResult(treeElement, treeElement.searchMatchesCount - 1, this._matchesCount); } if (currentTreeElement.searchMatchesCount && this._lastTreeElement === currentTreeElement) { if (this._lastIndex > 0) return this._searchResult(currentTreeElement, this._lastIndex - 1, this._currentMatchIndex - 1); else { var treeElement = this._traverser.previous(currentTreeElement); var currentMatchIndex = this._currentMatchIndex - 1 ? this._currentMatchIndex - 1 : this._matchesCount; return this._searchResult(treeElement, treeElement.searchMatchesCount - 1, currentMatchIndex); } } var treeElement = this._traverser.previous(currentTreeElement) return this._searchResult(treeElement, treeElement.searchMatchesCount - 1); }, _searchResult: function(treeElement, index, currentMatchIndex) { this._lastTreeElement = treeElement; this._lastIndex = index; if (!currentMatchIndex) currentMatchIndex = this._traverser.matchIndex(treeElement, index); this._currentMatchIndex = currentMatchIndex; return {treeElement: treeElement, index: index, currentMatchIndex: currentMatchIndex}; } } WebInspector.SearchResultsTreeElementsTraverser = function(rootElement) { this._root = rootElement; } WebInspector.SearchResultsTreeElementsTraverser.prototype = { first: function() { return this.next(this._root); }, last: function() { return this.previous(this._root); }, next: function(startTreeElement) { var treeElement = startTreeElement; do { treeElement = this._traverseNext(treeElement) || this._root; } while (treeElement != startTreeElement && !this._elementSearchMatchesCount(treeElement)); return treeElement; }, previous: function(startTreeElement) { var treeElement = startTreeElement; do { treeElement = this._traversePrevious(treeElement) || this._lastTreeElement(); } while (treeElement != startTreeElement && !this._elementSearchMatchesCount(treeElement)); return treeElement; }, matchIndex: function(startTreeElement, index) { var matchIndex = 1; var treeElement = this._root; while (treeElement != startTreeElement) { matchIndex += this._elementSearchMatchesCount(treeElement); treeElement = this._traverseNext(treeElement) || this._root; if (treeElement === this._root) return 0; } return matchIndex + index; }, _elementSearchMatchesCount: function(treeElement) { return treeElement.searchMatchesCount; }, _traverseNext: function(treeElement) { return (treeElement.traverseNextTreeElement(false, this._root, true)); }, _traversePrevious: function(treeElement) { return (treeElement.traversePreviousTreeElement(false, true)); }, _lastTreeElement: function() { var treeElement = this._root; var nextTreeElement; while (nextTreeElement = this._traverseNext(treeElement)) treeElement = nextTreeElement; return treeElement; } }
JavaScript
const UserInitiatedProfileName = "org.webkit.profiles.user-initiated"; WebInspector.ProfileType = function(id, name) { this._id = id; this._name = name; this.treeElement = null; } WebInspector.ProfileType.prototype = { get buttonTooltip() { return ""; }, get id() { return this._id; }, get treeItemTitle() { return this._name; }, get name() { return this._name; }, buttonClicked: function(profilesPanel) { return false; }, reset: function() { }, get description() { return ""; }, createTemporaryProfile: function(title) { throw new Error("Needs implemented."); }, createProfile: function(profile) { throw new Error("Not supported for " + this._name + " profiles."); } } WebInspector.ProfileHeader = function(profileType, title, uid) { this._profileType = profileType; this.title = title; if (uid === undefined) { this.uid = -1; this.isTemporary = true; } else { this.uid = uid; this.isTemporary = false; } this._fromFile = false; } WebInspector.ProfileHeader.prototype = { profileType: function() { return this._profileType; }, createSidebarTreeElement: function() { throw new Error("Needs implemented."); }, existingView: function() { return this._view; }, view: function() { if (!this._view) this._view = this.createView(WebInspector.ProfilesPanel._instance); return this._view; }, createView: function(profilesPanel) { throw new Error("Not implemented."); }, load: function(callback) { }, canSaveToFile: function() { return false; }, saveToFile: function() { throw new Error("Needs implemented"); }, canLoadFromFile: function() { return false; }, loadFromFile: function(file) { throw new Error("Needs implemented"); }, fromFile: function() { return this._fromFile; } } WebInspector.ProfilesPanel = function() { WebInspector.Panel.call(this, "profiles"); WebInspector.ProfilesPanel._instance = this; this.registerRequiredCSS("panelEnablerView.css"); this.registerRequiredCSS("heapProfiler.css"); this.registerRequiredCSS("profilesPanel.css"); this.createSidebarViewWithTree(); this.profilesItemTreeElement = new WebInspector.ProfilesSidebarTreeElement(this); this.sidebarTree.appendChild(this.profilesItemTreeElement); this._profileTypesByIdMap = {}; var panelEnablerHeading = WebInspector.UIString("You need to enable profiling before you can use the Profiles panel."); var panelEnablerDisclaimer = WebInspector.UIString("Enabling profiling will make scripts run slower."); var panelEnablerButton = WebInspector.UIString("Enable Profiling"); this.panelEnablerView = new WebInspector.PanelEnablerView("profiles", panelEnablerHeading, panelEnablerDisclaimer, panelEnablerButton); this.panelEnablerView.addEventListener("enable clicked", this.enableProfiler, this); this.profileViews = document.createElement("div"); this.profileViews.id = "profile-views"; this.splitView.mainElement.appendChild(this.profileViews); this._statusBarButtons = []; this.enableToggleButton = new WebInspector.StatusBarButton("", "enable-toggle-status-bar-item"); if (Capabilities.profilerCausesRecompilation) { this._statusBarButtons.push(this.enableToggleButton); this.enableToggleButton.addEventListener("click", this._onToggleProfiling, this); } this.recordButton = new WebInspector.StatusBarButton("", "record-profile-status-bar-item"); this.recordButton.addEventListener("click", this.toggleRecordButton, this); this._statusBarButtons.push(this.recordButton); this.clearResultsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear all profiles."), "clear-status-bar-item"); this.clearResultsButton.addEventListener("click", this._clearProfiles, this); this._statusBarButtons.push(this.clearResultsButton); if (WebInspector.experimentsSettings.liveNativeMemoryChart.isEnabled()) { this.garbageCollectButton = new WebInspector.StatusBarButton(WebInspector.UIString("Collect Garbage"), "garbage-collect-status-bar-item"); this.garbageCollectButton.addEventListener("click", this._garbageCollectButtonClicked, this); this._statusBarButtons.push(this.garbageCollectButton); } this.profileViewStatusBarItemsContainer = document.createElement("div"); this.profileViewStatusBarItemsContainer.className = "status-bar-items"; this._profiles = []; this._profilerEnabled = !Capabilities.profilerCausesRecompilation; this._launcherView = new WebInspector.ProfileLauncherView(this); this._launcherView.addEventListener(WebInspector.ProfileLauncherView.EventTypes.ProfileTypeSelected, this._onProfileTypeSelected, this); this._reset(); this._registerProfileType(new WebInspector.CPUProfileType()); if (!WebInspector.WorkerManager.isWorkerFrontend()) this._registerProfileType(new WebInspector.CSSSelectorProfileType()); if (Capabilities.heapProfilerPresent) this._registerProfileType(new WebInspector.HeapSnapshotProfileType()); if (WebInspector.experimentsSettings.nativeMemorySnapshots.isEnabled()) this._registerProfileType(new WebInspector.NativeMemoryProfileType()); if (WebInspector.experimentsSettings.canvasInspection.isEnabled()) this._registerProfileType(new WebInspector.CanvasProfileType()); InspectorBackend.registerProfilerDispatcher(new WebInspector.ProfilerDispatcher(this)); this._createFileSelectorElement(); this.element.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); WebInspector.ContextMenu.registerProvider(this); } WebInspector.ProfilesPanel.prototype = { _createFileSelectorElement: function() { if (this._fileSelectorElement) this.element.removeChild(this._fileSelectorElement); this._fileSelectorElement = WebInspector.createFileSelectorElement(this._loadFromFile.bind(this)); this.element.appendChild(this._fileSelectorElement); }, _loadFromFile: function(file) { if (!file.name.endsWith(".heapsnapshot")) { WebInspector.log(WebInspector.UIString("Only heap snapshots from files with extension '.heapsnapshot' can be loaded.")); return; } if (!!this.findTemporaryProfile(WebInspector.HeapSnapshotProfileType.TypeId)) { WebInspector.log(WebInspector.UIString("Can't load profile when other profile is recording.")); return; } var profileType = this.getProfileType(WebInspector.HeapSnapshotProfileType.TypeId); var temporaryProfile = profileType.createTemporaryProfile(UserInitiatedProfileName + "." + file.name); this.addProfileHeader(temporaryProfile); temporaryProfile._fromFile = true; temporaryProfile.loadFromFile(file); this._createFileSelectorElement(); }, get statusBarItems() { return this._statusBarButtons.select("element").concat([this.profileViewStatusBarItemsContainer]); }, toggleRecordButton: function() { var isProfiling = this._selectedProfileType.buttonClicked(this); this.recordButton.toggled = isProfiling; this.recordButton.title = this._selectedProfileType.buttonTooltip; if (isProfiling) this._launcherView.profileStarted(); else this._launcherView.profileFinished(); }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); this._populateProfiles(); }, _profilerWasEnabled: function() { if (this._profilerEnabled) return; this._profilerEnabled = true; this._reset(); if (this.isShowing()) this._populateProfiles(); }, _profilerWasDisabled: function() { if (!this._profilerEnabled) return; this._profilerEnabled = false; this._reset(); }, _onProfileTypeSelected: function(event) { this._selectedProfileType = (event.data); this.recordButton.title = this._selectedProfileType.buttonTooltip; }, _reset: function() { WebInspector.Panel.prototype.reset.call(this); for (var i = 0; i < this._profiles.length; ++i) { var view = this._profiles[i].existingView(); if (view) { view.detach(); if ("dispose" in view) view.dispose(); } } delete this.visibleView; delete this.currentQuery; this.searchCanceled(); for (var id in this._profileTypesByIdMap) { var profileType = this._profileTypesByIdMap[id]; var treeElement = profileType.treeElement; treeElement.removeChildren(); treeElement.hidden = true; profileType.reset(); } this._profiles = []; this._profilesIdMap = {}; this._profileGroups = {}; this._profileGroupsForLinks = {}; this._profilesWereRequested = false; this.recordButton.toggled = false; if (this._selectedProfileType) this.recordButton.title = this._selectedProfileType.buttonTooltip; this._launcherView.profileFinished(); this.sidebarTreeElement.removeStyleClass("some-expandable"); this.profileViews.removeChildren(); this.profileViewStatusBarItemsContainer.removeChildren(); this.removeAllListeners(); this._updateInterface(); this.profilesItemTreeElement.select(); this._showLauncherView(); }, _showLauncherView: function() { this.closeVisibleView(); this.profileViewStatusBarItemsContainer.removeChildren(); this._launcherView.show(this.splitView.mainElement); this.visibleView = this._launcherView; }, _clearProfiles: function() { ProfilerAgent.clearProfiles(); this._reset(); }, _garbageCollectButtonClicked: function() { ProfilerAgent.collectGarbage(); }, _registerProfileType: function(profileType) { this._profileTypesByIdMap[profileType.id] = profileType; this._launcherView.addProfileType(profileType); profileType.treeElement = new WebInspector.SidebarSectionTreeElement(profileType.treeItemTitle, null, true); profileType.treeElement.hidden = true; this.sidebarTree.appendChild(profileType.treeElement); profileType.treeElement.childrenListElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); }, _handleContextMenuEvent: function(event) { var element = event.srcElement; while (element && !element.treeElement && element !== this.element) element = element.parentElement; if (!element) return; if (element.treeElement && element.treeElement.handleContextMenuEvent) { element.treeElement.handleContextMenuEvent(event); return; } if (element !== this.element || event.srcElement === this.sidebarElement) { var contextMenu = new WebInspector.ContextMenu(event); if (this.visibleView instanceof WebInspector.HeapSnapshotView) this.visibleView.populateContextMenu(contextMenu, event); contextMenu.appendItem(WebInspector.UIString("Load Heap Snapshot\u2026"), this._fileSelectorElement.click.bind(this._fileSelectorElement)); contextMenu.show(); } }, _makeTitleKey: function(text, profileTypeId) { return escape(text) + '/' + escape(profileTypeId); }, _makeKey: function(id, profileTypeId) { return id + '/' + escape(profileTypeId); }, addProfileHeader: function(profile) { this._removeTemporaryProfile(profile.profileType().id); var profileType = profile.profileType(); var typeId = profileType.id; var sidebarParent = profileType.treeElement; sidebarParent.hidden = false; var small = false; var alternateTitle; this._profiles.push(profile); this._profilesIdMap[this._makeKey(profile.uid, typeId)] = profile; if (!profile.title.startsWith(UserInitiatedProfileName)) { var profileTitleKey = this._makeTitleKey(profile.title, typeId); if (!(profileTitleKey in this._profileGroups)) this._profileGroups[profileTitleKey] = []; var group = this._profileGroups[profileTitleKey]; group.push(profile); if (group.length === 2) { group._profilesTreeElement = new WebInspector.ProfileGroupSidebarTreeElement(profile.title); var index = sidebarParent.children.indexOf(group[0]._profilesTreeElement); sidebarParent.insertChild(group._profilesTreeElement, index); var selected = group[0]._profilesTreeElement.selected; sidebarParent.removeChild(group[0]._profilesTreeElement); group._profilesTreeElement.appendChild(group[0]._profilesTreeElement); if (selected) group[0]._profilesTreeElement.revealAndSelect(); group[0]._profilesTreeElement.small = true; group[0]._profilesTreeElement.mainTitle = WebInspector.UIString("Run %d", 1); this.sidebarTreeElement.addStyleClass("some-expandable"); } if (group.length >= 2) { sidebarParent = group._profilesTreeElement; alternateTitle = WebInspector.UIString("Run %d", group.length); small = true; } } var profileTreeElement = profile.createSidebarTreeElement(); profile.sidebarElement = profileTreeElement; profileTreeElement.small = small; if (alternateTitle) profileTreeElement.mainTitle = alternateTitle; profile._profilesTreeElement = profileTreeElement; sidebarParent.appendChild(profileTreeElement); if (!profile.isTemporary) { if (!this.visibleView) this.showProfile(profile); this.dispatchEventToListeners("profile added", { type: typeId }); } }, _removeProfileHeader: function(profile) { var sidebarParent = profile.profileType().treeElement; for (var i = 0; i < this._profiles.length; ++i) { if (this._profiles[i].uid === profile.uid) { profile = this._profiles[i]; this._profiles.splice(i, 1); break; } } delete this._profilesIdMap[this._makeKey(profile.uid, profile.profileType().id)]; var profileTitleKey = this._makeTitleKey(profile.title, profile.profileType().id); delete this._profileGroups[profileTitleKey]; sidebarParent.removeChild(profile._profilesTreeElement); if (!profile.isTemporary) ProfilerAgent.removeProfile(profile.profileType().id, profile.uid); if (!this._profiles.length) this.closeVisibleView(); }, showProfile: function(profile) { if (!profile || profile.isTemporary) return; var view = profile.view(); if (view === this.visibleView) return; this.closeVisibleView(); view.show(this.profileViews); profile._profilesTreeElement._suppressOnSelect = true; profile._profilesTreeElement.revealAndSelect(); delete profile._profilesTreeElement._suppressOnSelect; this.visibleView = view; this.profileViewStatusBarItemsContainer.removeChildren(); var statusBarItems = view.statusBarItems; if (statusBarItems) for (var i = 0; i < statusBarItems.length; ++i) this.profileViewStatusBarItemsContainer.appendChild(statusBarItems[i]); }, getProfiles: function(typeId) { var result = []; var profilesCount = this._profiles.length; for (var i = 0; i < profilesCount; ++i) { var profile = this._profiles[i]; if (!profile.isTemporary && profile.profileType().id === typeId) result.push(profile); } return result; }, showObject: function(snapshotObjectId, viewName) { var heapProfiles = this.getProfiles(WebInspector.HeapSnapshotProfileType.TypeId); for (var i = 0; i < heapProfiles.length; i++) { var profile = heapProfiles[i]; if (profile.maxJSObjectId >= snapshotObjectId) { this.showProfile(profile); profile.view().changeView(viewName, function() { profile.view().dataGrid.highlightObjectByHeapSnapshotId(snapshotObjectId); }); break; } } }, findTemporaryProfile: function(typeId) { var profilesCount = this._profiles.length; for (var i = 0; i < profilesCount; ++i) if (this._profiles[i].profileType().id === typeId && this._profiles[i].isTemporary) return this._profiles[i]; return null; }, _removeTemporaryProfile: function(typeId) { var temporaryProfile = this.findTemporaryProfile(typeId); if (temporaryProfile) this._removeProfileHeader(temporaryProfile); }, getProfile: function(typeId, uid) { return this._profilesIdMap[this._makeKey(uid, typeId)]; }, _addHeapSnapshotChunk: function(uid, chunk) { var profile = this._profilesIdMap[this._makeKey(uid, WebInspector.HeapSnapshotProfileType.TypeId)]; if (!profile) return; profile.transferChunk(chunk); }, _finishHeapSnapshot: function(uid) { var profile = this._profilesIdMap[this._makeKey(uid, WebInspector.HeapSnapshotProfileType.TypeId)]; if (!profile) return; profile.finishHeapSnapshot(); }, showView: function(view) { this.showProfile(view.profile); }, getProfileType: function(typeId) { return this._profileTypesByIdMap[typeId]; }, showProfileForURL: function(url) { var match = url.match(WebInspector.ProfileURLRegExp); if (!match) return; this.showProfile(this._profilesIdMap[this._makeKey(Number(match[3]), match[1])]); }, closeVisibleView: function() { if (this.visibleView) this.visibleView.detach(); delete this.visibleView; }, displayTitleForProfileLink: function(title, typeId) { title = unescape(title); if (title.startsWith(UserInitiatedProfileName)) { title = WebInspector.UIString("Profile %d", title.substring(UserInitiatedProfileName.length + 1)); } else { var titleKey = this._makeTitleKey(title, typeId); if (!(titleKey in this._profileGroupsForLinks)) this._profileGroupsForLinks[titleKey] = 0; var groupNumber = ++this._profileGroupsForLinks[titleKey]; if (groupNumber > 2) title += " " + WebInspector.UIString("Run %d", (groupNumber + 1) / 2); } return title; }, performSearch: function(query) { this.searchCanceled(); var searchableViews = this._searchableViews(); if (!searchableViews || !searchableViews.length) return; var visibleView = this.visibleView; var matchesCountUpdateTimeout = null; function updateMatchesCount() { WebInspector.searchController.updateSearchMatchesCount(this._totalSearchMatches, this); WebInspector.searchController.updateCurrentMatchIndex(this._currentSearchResultIndex, this); matchesCountUpdateTimeout = null; } function updateMatchesCountSoon() { if (matchesCountUpdateTimeout) return; matchesCountUpdateTimeout = setTimeout(updateMatchesCount.bind(this), 500); } function finishedCallback(view, searchMatches) { if (!searchMatches) return; this._totalSearchMatches += searchMatches; this._searchResults.push(view); if (this.searchMatchFound) this.searchMatchFound(view, searchMatches); updateMatchesCountSoon.call(this); if (view === visibleView) view.jumpToFirstSearchResult(); } var i = 0; var panel = this; var boundFinishedCallback = finishedCallback.bind(this); var chunkIntervalIdentifier = null; function processChunk() { var view = searchableViews[i]; if (++i >= searchableViews.length) { if (panel._currentSearchChunkIntervalIdentifier === chunkIntervalIdentifier) delete panel._currentSearchChunkIntervalIdentifier; clearInterval(chunkIntervalIdentifier); } if (!view) return; view.currentQuery = query; view.performSearch(query, boundFinishedCallback); } processChunk(); chunkIntervalIdentifier = setInterval(processChunk, 25); this._currentSearchChunkIntervalIdentifier = chunkIntervalIdentifier; }, jumpToNextSearchResult: function() { if (!this.showView || !this._searchResults || !this._searchResults.length) return; var showFirstResult = false; this._currentSearchResultIndex = this._searchResults.indexOf(this.visibleView); if (this._currentSearchResultIndex === -1) { this._currentSearchResultIndex = 0; showFirstResult = true; } var currentView = this._searchResults[this._currentSearchResultIndex]; if (currentView.showingLastSearchResult()) { if (++this._currentSearchResultIndex >= this._searchResults.length) this._currentSearchResultIndex = 0; currentView = this._searchResults[this._currentSearchResultIndex]; showFirstResult = true; } WebInspector.searchController.updateCurrentMatchIndex(this._currentSearchResultIndex, this); if (currentView !== this.visibleView) { this.showView(currentView); WebInspector.searchController.showSearchField(); } if (showFirstResult) currentView.jumpToFirstSearchResult(); else currentView.jumpToNextSearchResult(); }, jumpToPreviousSearchResult: function() { if (!this.showView || !this._searchResults || !this._searchResults.length) return; var showLastResult = false; this._currentSearchResultIndex = this._searchResults.indexOf(this.visibleView); if (this._currentSearchResultIndex === -1) { this._currentSearchResultIndex = 0; showLastResult = true; } var currentView = this._searchResults[this._currentSearchResultIndex]; if (currentView.showingFirstSearchResult()) { if (--this._currentSearchResultIndex < 0) this._currentSearchResultIndex = (this._searchResults.length - 1); currentView = this._searchResults[this._currentSearchResultIndex]; showLastResult = true; } WebInspector.searchController.updateCurrentMatchIndex(this._currentSearchResultIndex, this); if (currentView !== this.visibleView) { this.showView(currentView); WebInspector.searchController.showSearchField(); } if (showLastResult) currentView.jumpToLastSearchResult(); else currentView.jumpToPreviousSearchResult(); }, _searchableViews: function() { var views = []; const visibleView = this.visibleView; if (visibleView && visibleView.performSearch) views.push(visibleView); var profilesLength = this._profiles.length; for (var i = 0; i < profilesLength; ++i) { var profile = this._profiles[i]; var view = profile.view(); if (!view.performSearch || view === visibleView) continue; views.push(view); } return views; }, searchMatchFound: function(view, matches) { view.profile._profilesTreeElement.searchMatches = matches; }, searchCanceled: function() { if (this._searchResults) { for (var i = 0; i < this._searchResults.length; ++i) { var view = this._searchResults[i]; if (view.searchCanceled) view.searchCanceled(); delete view.currentQuery; } } WebInspector.Panel.prototype.searchCanceled.call(this); if (this._currentSearchChunkIntervalIdentifier) { clearInterval(this._currentSearchChunkIntervalIdentifier); delete this._currentSearchChunkIntervalIdentifier; } this._totalSearchMatches = 0; this._currentSearchResultIndex = 0; this._searchResults = []; if (!this._profiles) return; for (var i = 0; i < this._profiles.length; ++i) { var profile = this._profiles[i]; profile._profilesTreeElement.searchMatches = 0; } }, _updateInterface: function() { if (this._profilerEnabled) { this.enableToggleButton.title = WebInspector.UIString("Profiling enabled. Click to disable."); this.enableToggleButton.toggled = true; this.recordButton.visible = true; this.profileViewStatusBarItemsContainer.removeStyleClass("hidden"); this.clearResultsButton.element.removeStyleClass("hidden"); this.panelEnablerView.detach(); } else { this.enableToggleButton.title = WebInspector.UIString("Profiling disabled. Click to enable."); this.enableToggleButton.toggled = false; this.recordButton.visible = false; this.profileViewStatusBarItemsContainer.addStyleClass("hidden"); this.clearResultsButton.element.addStyleClass("hidden"); this.panelEnablerView.show(this.element); } }, get profilerEnabled() { return this._profilerEnabled; }, enableProfiler: function() { if (this._profilerEnabled) return; this._toggleProfiling(this.panelEnablerView.alwaysEnabled); }, disableProfiler: function() { if (!this._profilerEnabled) return; this._toggleProfiling(this.panelEnablerView.alwaysEnabled); }, _onToggleProfiling: function(event) { this._toggleProfiling(true); }, _toggleProfiling: function(always) { if (this._profilerEnabled) { WebInspector.settings.profilerEnabled.set(false); ProfilerAgent.disable(this._profilerWasDisabled.bind(this)); } else { WebInspector.settings.profilerEnabled.set(always); ProfilerAgent.enable(this._profilerWasEnabled.bind(this)); } }, _populateProfiles: function() { if (!this._profilerEnabled || this._profilesWereRequested) return; function populateCallback(error, profileHeaders) { if (error) return; profileHeaders.sort(function(a, b) { return a.uid - b.uid; }); var profileHeadersLength = profileHeaders.length; for (var i = 0; i < profileHeadersLength; ++i) { var profileHeader = profileHeaders[i]; var profileType = this.getProfileType(profileHeader.typeId); this.addProfileHeader(profileType.createProfile(profileHeader)); } } ProfilerAgent.getProfileHeaders(populateCallback.bind(this)); this._profilesWereRequested = true; }, sidebarResized: function(event) { var sidebarWidth = (event.data); this._resize(sidebarWidth); }, onResize: function() { this._resize(this.splitView.sidebarWidth()); }, _resize: function(sidebarWidth) { var lastItemElement = this._statusBarButtons[this._statusBarButtons.length - 1].element; var minFloatingStatusBarItemsOffset = lastItemElement.totalOffsetLeft() + lastItemElement.offsetWidth; this.profileViewStatusBarItemsContainer.style.left = Math.max(minFloatingStatusBarItemsOffset, sidebarWidth) + "px"; }, setRecordingProfile: function(profileType, isProfiling) { var profileTypeObject = this.getProfileType(profileType); profileTypeObject.setRecordingProfile(isProfiling); var temporaryProfile = this.findTemporaryProfile(profileType); if (!!temporaryProfile === isProfiling) return; if (!temporaryProfile) temporaryProfile = profileTypeObject.createTemporaryProfile(); if (isProfiling) this.addProfileHeader(temporaryProfile); else this._removeTemporaryProfile(profileType); this.recordButton.toggled = isProfiling; this.recordButton.title = profileTypeObject.buttonTooltip; if (isProfiling) this._launcherView.profileStarted(); else this._launcherView.profileFinished(); }, takeHeapSnapshot: function() { var temporaryRecordingProfile = this.findTemporaryProfile(WebInspector.HeapSnapshotProfileType.TypeId); if (!temporaryRecordingProfile) { var profileTypeObject = this.getProfileType(WebInspector.HeapSnapshotProfileType.TypeId); this.addProfileHeader(profileTypeObject.createTemporaryProfile()); } this._launcherView.profileStarted(); function done() { this._launcherView.profileFinished(); } ProfilerAgent.takeHeapSnapshot(done.bind(this)); WebInspector.userMetrics.ProfilesHeapProfileTaken.record(); }, _reportHeapSnapshotProgress: function(done, total) { var temporaryProfile = this.findTemporaryProfile(WebInspector.HeapSnapshotProfileType.TypeId); if (temporaryProfile) { temporaryProfile.sidebarElement.subtitle = WebInspector.UIString("%.2f%", (done / total) * 100); temporaryProfile.sidebarElement.wait = true; if (done >= total) this._removeTemporaryProfile(WebInspector.HeapSnapshotProfileType.TypeId); } }, appendApplicableItems: function(event, contextMenu, target) { if (WebInspector.inspectorView.currentPanel() !== this) return; var object = (target); var objectId = object.objectId; if (!objectId) return; var heapProfiles = this.getProfiles(WebInspector.HeapSnapshotProfileType.TypeId); if (!heapProfiles.length) return; function revealInView(viewName) { ProfilerAgent.getHeapObjectId(objectId, didReceiveHeapObjectId.bind(this, viewName)); } function didReceiveHeapObjectId(viewName, error, result) { if (WebInspector.inspectorView.currentPanel() !== this) return; if (!error) this.showObject(result, viewName); } contextMenu.appendItem(WebInspector.UIString("Reveal in Dominators View"), revealInView.bind(this, "Dominators")); contextMenu.appendItem(WebInspector.UIString("Reveal in Summary View"), revealInView.bind(this, "Summary")); }, __proto__: WebInspector.Panel.prototype } WebInspector.ProfilerDispatcher = function(profilesPanel) { this._profilesPanel = profilesPanel; } WebInspector.ProfilerDispatcher.prototype = { addProfileHeader: function(profile) { var profileType = this._profilesPanel.getProfileType(profile.typeId); this._profilesPanel.addProfileHeader(profileType.createProfile(profile)); }, addHeapSnapshotChunk: function(uid, chunk) { this._profilesPanel._addHeapSnapshotChunk(uid, chunk); }, finishHeapSnapshot: function(uid) { this._profilesPanel._finishHeapSnapshot(uid); }, setRecordingProfile: function(isProfiling) { this._profilesPanel.setRecordingProfile(WebInspector.CPUProfileType.TypeId, isProfiling); }, resetProfiles: function() { this._profilesPanel._reset(); }, reportHeapSnapshotProgress: function(done, total) { this._profilesPanel._reportHeapSnapshotProgress(done, total); } } WebInspector.ProfileSidebarTreeElement = function(profile, titleFormat, className) { this.profile = profile; this._titleFormat = titleFormat; if (this.profile.title.startsWith(UserInitiatedProfileName)) this._profileNumber = this.profile.title.substring(UserInitiatedProfileName.length + 1); WebInspector.SidebarTreeElement.call(this, className, "", "", profile, false); this.refreshTitles(); } WebInspector.ProfileSidebarTreeElement.prototype = { onselect: function() { if (!this._suppressOnSelect) this.treeOutline.panel.showProfile(this.profile); }, ondelete: function() { this.treeOutline.panel._removeProfileHeader(this.profile); return true; }, get mainTitle() { if (this._mainTitle) return this._mainTitle; if (this.profile.title.startsWith(UserInitiatedProfileName)) return WebInspector.UIString(this._titleFormat, this._profileNumber); return this.profile.title; }, set mainTitle(x) { this._mainTitle = x; this.refreshTitles(); }, set searchMatches(matches) { if (!matches) { if (!this.bubbleElement) return; this.bubbleElement.removeStyleClass("search-matches"); this.bubbleText = ""; return; } this.bubbleText = matches; this.bubbleElement.addStyleClass("search-matches"); }, handleContextMenuEvent: function(event) { var profile = this.profile; var contextMenu = new WebInspector.ContextMenu(event); var profilesPanel = WebInspector.ProfilesPanel._instance; if (profile.canSaveToFile()) { contextMenu.appendItem(WebInspector.UIString("Save Heap Snapshot\u2026"), profile.saveToFile.bind(profile)); contextMenu.appendItem(WebInspector.UIString("Load Heap Snapshot\u2026"), profilesPanel._fileSelectorElement.click.bind(profilesPanel._fileSelectorElement)); contextMenu.appendItem(WebInspector.UIString("Delete Heap Snapshot"), this.ondelete.bind(this)); } else { contextMenu.appendItem(WebInspector.UIString("Load Heap Snapshot\u2026"), profilesPanel._fileSelectorElement.click.bind(profilesPanel._fileSelectorElement)); contextMenu.appendItem(WebInspector.UIString("Delete profile"), this.ondelete.bind(this)); } contextMenu.show(); }, __proto__: WebInspector.SidebarTreeElement.prototype } WebInspector.ProfileGroupSidebarTreeElement = function(title, subtitle) { WebInspector.SidebarTreeElement.call(this, "profile-group-sidebar-tree-item", title, subtitle, null, true); } WebInspector.ProfileGroupSidebarTreeElement.prototype = { onselect: function() { if (this.children.length > 0) WebInspector.ProfilesPanel._instance.showProfile(this.children[this.children.length - 1].profile); }, __proto__: WebInspector.SidebarTreeElement.prototype } WebInspector.ProfilesSidebarTreeElement = function(panel) { this._panel = panel; this.small = false; WebInspector.SidebarTreeElement.call(this, "profile-launcher-view-tree-item", WebInspector.UIString("Profiles"), "", null, false); } WebInspector.ProfilesSidebarTreeElement.prototype = { onselect: function() { this._panel._showLauncherView(); }, get selectable() { return true; }, __proto__: WebInspector.SidebarTreeElement.prototype } WebInspector.ProfileDataGridNode = function(profileView, profileNode, owningTree, hasChildren) { this.profileView = profileView; this.profileNode = profileNode; WebInspector.DataGridNode.call(this, null, hasChildren); this.addEventListener("populate", this._populate, this); this.tree = owningTree; this.childrenByCallUID = {}; this.lastComparator = null; this.callUID = profileNode.callUID; this.selfTime = profileNode.selfTime; this.totalTime = profileNode.totalTime; this.functionName = profileNode.functionName; this.numberOfCalls = profileNode.numberOfCalls; this.url = profileNode.url; } WebInspector.ProfileDataGridNode.prototype = { get data() { function formatMilliseconds(time) { return Number.secondsToString(time / 1000, !Capabilities.samplingCPUProfiler); } var data = {}; data["function"] = this.functionName; data["calls"] = this.numberOfCalls; if (this.profileView.showSelfTimeAsPercent.get()) data["self"] = WebInspector.UIString("%.2f%", this.selfPercent); else data["self"] = formatMilliseconds(this.selfTime); if (this.profileView.showTotalTimeAsPercent.get()) data["total"] = WebInspector.UIString("%.2f%", this.totalPercent); else data["total"] = formatMilliseconds(this.totalTime); if (this.profileView.showAverageTimeAsPercent.get()) data["average"] = WebInspector.UIString("%.2f%", this.averagePercent); else data["average"] = formatMilliseconds(this.averageTime); return data; }, createCell: function(columnIdentifier) { var cell = WebInspector.DataGridNode.prototype.createCell.call(this, columnIdentifier); if (columnIdentifier === "self" && this._searchMatchedSelfColumn) cell.addStyleClass("highlight"); else if (columnIdentifier === "total" && this._searchMatchedTotalColumn) cell.addStyleClass("highlight"); else if (columnIdentifier === "average" && this._searchMatchedAverageColumn) cell.addStyleClass("highlight"); else if (columnIdentifier === "calls" && this._searchMatchedCallsColumn) cell.addStyleClass("highlight"); if (columnIdentifier !== "function") return cell; if (this.profileNode._searchMatchedFunctionColumn) cell.addStyleClass("highlight"); if (this.profileNode.url) { var lineNumber = this.profileNode.lineNumber ? this.profileNode.lineNumber - 1 : 0; var urlElement = this.profileView._linkifier.linkifyLocation(this.profileNode.url, lineNumber, 0, "profile-node-file"); urlElement.style.maxWidth = "75%"; cell.insertBefore(urlElement, cell.firstChild); } return cell; }, select: function(supressSelectedEvent) { WebInspector.DataGridNode.prototype.select.call(this, supressSelectedEvent); this.profileView._dataGridNodeSelected(this); }, deselect: function(supressDeselectedEvent) { WebInspector.DataGridNode.prototype.deselect.call(this, supressDeselectedEvent); this.profileView._dataGridNodeDeselected(this); }, sort: function( comparator, force) { var gridNodeGroups = [[this]]; for (var gridNodeGroupIndex = 0; gridNodeGroupIndex < gridNodeGroups.length; ++gridNodeGroupIndex) { var gridNodes = gridNodeGroups[gridNodeGroupIndex]; var count = gridNodes.length; for (var index = 0; index < count; ++index) { var gridNode = gridNodes[index]; if (!force && (!gridNode.expanded || gridNode.lastComparator === comparator)) { if (gridNode.children.length) gridNode.shouldRefreshChildren = true; continue; } gridNode.lastComparator = comparator; var children = gridNode.children; var childCount = children.length; if (childCount) { children.sort(comparator); for (var childIndex = 0; childIndex < childCount; ++childIndex) children[childIndex]._recalculateSiblings(childIndex); gridNodeGroups.push(children); } } } }, insertChild: function( profileDataGridNode, index) { WebInspector.DataGridNode.prototype.insertChild.call(this, profileDataGridNode, index); this.childrenByCallUID[profileDataGridNode.callUID] = profileDataGridNode; }, removeChild: function( profileDataGridNode) { WebInspector.DataGridNode.prototype.removeChild.call(this, profileDataGridNode); delete this.childrenByCallUID[profileDataGridNode.callUID]; }, removeChildren: function( profileDataGridNode) { WebInspector.DataGridNode.prototype.removeChildren.call(this); this.childrenByCallUID = {}; }, findChild: function( node) { if (!node) return null; return this.childrenByCallUID[node.callUID]; }, get averageTime() { return this.selfTime / Math.max(1, this.numberOfCalls); }, get averagePercent() { return this.averageTime / this.tree.totalTime * 100.0; }, get selfPercent() { return this.selfTime / this.tree.totalTime * 100.0; }, get totalPercent() { return this.totalTime / this.tree.totalTime * 100.0; }, get _parent() { return this.parent !== this.dataGrid ? this.parent : this.tree; }, _populate: function() { this._sharedPopulate(); if (this._parent) { var currentComparator = this._parent.lastComparator; if (currentComparator) this.sort(currentComparator, true); } if (this.removeEventListener) this.removeEventListener("populate", this._populate, this); }, _save: function() { if (this._savedChildren) return; this._savedSelfTime = this.selfTime; this._savedTotalTime = this.totalTime; this._savedNumberOfCalls = this.numberOfCalls; this._savedChildren = this.children.slice(); }, _restore: function() { if (!this._savedChildren) return; this.selfTime = this._savedSelfTime; this.totalTime = this._savedTotalTime; this.numberOfCalls = this._savedNumberOfCalls; this.removeChildren(); var children = this._savedChildren; var count = children.length; for (var index = 0; index < count; ++index) { children[index]._restore(); this.appendChild(children[index]); } }, _merge: function(child, shouldAbsorb) { this.selfTime += child.selfTime; if (!shouldAbsorb) { this.totalTime += child.totalTime; this.numberOfCalls += child.numberOfCalls; } var children = this.children.slice(); this.removeChildren(); var count = children.length; for (var index = 0; index < count; ++index) { if (!shouldAbsorb || children[index] !== child) this.appendChild(children[index]); } children = child.children.slice(); count = children.length; for (var index = 0; index < count; ++index) { var orphanedChild = children[index], existingChild = this.childrenByCallUID[orphanedChild.callUID]; if (existingChild) existingChild._merge(orphanedChild, false); else this.appendChild(orphanedChild); } }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.ProfileDataGridTree = function(profileView, profileNode) { this.tree = this; this.children = []; this.profileView = profileView; this.totalTime = profileNode.totalTime; this.lastComparator = null; this.childrenByCallUID = {}; } WebInspector.ProfileDataGridTree.prototype = { get expanded() { return true; }, appendChild: function(child) { this.insertChild(child, this.children.length); }, insertChild: function(child, index) { this.children.splice(index, 0, child); this.childrenByCallUID[child.callUID] = child; }, removeChildren: function() { this.children = []; this.childrenByCallUID = {}; }, findChild: WebInspector.ProfileDataGridNode.prototype.findChild, sort: WebInspector.ProfileDataGridNode.prototype.sort, _save: function() { if (this._savedChildren) return; this._savedTotalTime = this.totalTime; this._savedChildren = this.children.slice(); }, restore: function() { if (!this._savedChildren) return; this.children = this._savedChildren; this.totalTime = this._savedTotalTime; var children = this.children; var count = children.length; for (var index = 0; index < count; ++index) children[index]._restore(); this._savedChildren = null; } } WebInspector.ProfileDataGridTree.propertyComparators = [{}, {}]; WebInspector.ProfileDataGridTree.propertyComparator = function( property, isAscending) { var comparator = WebInspector.ProfileDataGridTree.propertyComparators[(isAscending ? 1 : 0)][property]; if (!comparator) { if (isAscending) { comparator = function(lhs, rhs) { if (lhs[property] < rhs[property]) return -1; if (lhs[property] > rhs[property]) return 1; return 0; } } else { comparator = function(lhs, rhs) { if (lhs[property] > rhs[property]) return -1; if (lhs[property] < rhs[property]) return 1; return 0; } } WebInspector.ProfileDataGridTree.propertyComparators[(isAscending ? 1 : 0)][property] = comparator; } return comparator; } ; WebInspector.BottomUpProfileDataGridNode = function( profileView, profileNode, owningTree) { WebInspector.ProfileDataGridNode.call(this, profileView, profileNode, owningTree, this._willHaveChildren(profileNode)); this._remainingNodeInfos = []; } WebInspector.BottomUpProfileDataGridNode.prototype = { _takePropertiesFromProfileDataGridNode: function( profileDataGridNode) { this._save(); this.selfTime = profileDataGridNode.selfTime; this.totalTime = profileDataGridNode.totalTime; this.numberOfCalls = profileDataGridNode.numberOfCalls; }, _keepOnlyChild: function( child) { this._save(); this.removeChildren(); this.appendChild(child); }, _exclude: function(aCallUID) { if (this._remainingNodeInfos) this._populate(); this._save(); var children = this.children; var index = this.children.length; while (index--) children[index]._exclude(aCallUID); var child = this.childrenByCallUID[aCallUID]; if (child) this._merge(child, true); }, _restore: function() { WebInspector.ProfileDataGridNode.prototype._restore(); if (!this.children.length) this.hasChildren = this._willHaveChildren(this.profileNode); }, _merge: function( child, shouldAbsorb) { this.selfTime -= child.selfTime; WebInspector.ProfileDataGridNode.prototype._merge.call(this, child, shouldAbsorb); }, _sharedPopulate: function() { var remainingNodeInfos = this._remainingNodeInfos; var count = remainingNodeInfos.length; for (var index = 0; index < count; ++index) { var nodeInfo = remainingNodeInfos[index]; var ancestor = nodeInfo.ancestor; var focusNode = nodeInfo.focusNode; var child = this.findChild(ancestor); if (child) { var totalTimeAccountedFor = nodeInfo.totalTimeAccountedFor; child.selfTime += focusNode.selfTime; child.numberOfCalls += focusNode.numberOfCalls; if (!totalTimeAccountedFor) child.totalTime += focusNode.totalTime; } else { child = new WebInspector.BottomUpProfileDataGridNode(this.profileView, ancestor, this.tree); if (ancestor !== focusNode) { child.selfTime = focusNode.selfTime; child.totalTime = focusNode.totalTime; child.numberOfCalls = focusNode.numberOfCalls; } this.appendChild(child); } var parent = ancestor.parent; if (parent && parent.parent) { nodeInfo.ancestor = parent; child._remainingNodeInfos.push(nodeInfo); } } delete this._remainingNodeInfos; }, _willHaveChildren: function(profileNode) { return !!(profileNode.parent && profileNode.parent.parent); }, __proto__: WebInspector.ProfileDataGridNode.prototype } WebInspector.BottomUpProfileDataGridTree = function( aProfileView, aProfileNode) { WebInspector.ProfileDataGridTree.call(this, aProfileView, aProfileNode); var profileNodeUIDs = 0; var profileNodeGroups = [[], [aProfileNode]]; var visitedProfileNodesForCallUID = {}; this._remainingNodeInfos = []; for (var profileNodeGroupIndex = 0; profileNodeGroupIndex < profileNodeGroups.length; ++profileNodeGroupIndex) { var parentProfileNodes = profileNodeGroups[profileNodeGroupIndex]; var profileNodes = profileNodeGroups[++profileNodeGroupIndex]; var count = profileNodes.length; for (var index = 0; index < count; ++index) { var profileNode = profileNodes[index]; if (!profileNode.UID) profileNode.UID = ++profileNodeUIDs; if (profileNode.head && profileNode !== profileNode.head) { var visitedNodes = visitedProfileNodesForCallUID[profileNode.callUID]; var totalTimeAccountedFor = false; if (!visitedNodes) { visitedNodes = {} visitedProfileNodesForCallUID[profileNode.callUID] = visitedNodes; } else { var parentCount = parentProfileNodes.length; for (var parentIndex = 0; parentIndex < parentCount; ++parentIndex) { if (visitedNodes[parentProfileNodes[parentIndex].UID]) { totalTimeAccountedFor = true; break; } } } visitedNodes[profileNode.UID] = true; this._remainingNodeInfos.push({ ancestor:profileNode, focusNode:profileNode, totalTimeAccountedFor:totalTimeAccountedFor }); } var children = profileNode.children; if (children.length) { profileNodeGroups.push(parentProfileNodes.concat([profileNode])) profileNodeGroups.push(children); } } } var any = this; var node = any; WebInspector.BottomUpProfileDataGridNode.prototype._populate.call(node); return this; } WebInspector.BottomUpProfileDataGridTree.prototype = { focus: function( profileDataGridNode) { if (!profileDataGridNode) return; this._save(); var currentNode = profileDataGridNode; var focusNode = profileDataGridNode; while (currentNode.parent && (currentNode instanceof WebInspector.ProfileDataGridNode)) { currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode); focusNode = currentNode; currentNode = currentNode.parent; if (currentNode instanceof WebInspector.ProfileDataGridNode) currentNode._keepOnlyChild(focusNode); } this.children = [focusNode]; this.totalTime = profileDataGridNode.totalTime; }, exclude: function( profileDataGridNode) { if (!profileDataGridNode) return; this._save(); var excludedCallUID = profileDataGridNode.callUID; var excludedTopLevelChild = this.childrenByCallUID[excludedCallUID]; if (excludedTopLevelChild) this.children.remove(excludedTopLevelChild); var children = this.children; var count = children.length; for (var index = 0; index < count; ++index) children[index]._exclude(excludedCallUID); if (this.lastComparator) this.sort(this.lastComparator, true); }, _sharedPopulate: WebInspector.BottomUpProfileDataGridNode.prototype._sharedPopulate, __proto__: WebInspector.ProfileDataGridTree.prototype } ; WebInspector.CPUProfileView = function(profile) { WebInspector.View.call(this); this.element.addStyleClass("profile-view"); this.showSelfTimeAsPercent = WebInspector.settings.createSetting("cpuProfilerShowSelfTimeAsPercent", true); this.showTotalTimeAsPercent = WebInspector.settings.createSetting("cpuProfilerShowTotalTimeAsPercent", true); this.showAverageTimeAsPercent = WebInspector.settings.createSetting("cpuProfilerShowAverageTimeAsPercent", true); this._viewType = WebInspector.settings.createSetting("cpuProfilerView", WebInspector.CPUProfileView._TypeHeavy); var columns = { "self": { title: WebInspector.UIString("Self"), width: "72px", sort: "descending", sortable: true }, "total": { title: WebInspector.UIString("Total"), width: "72px", sortable: true }, "average": { title: WebInspector.UIString("Average"), width: "72px", sortable: true }, "calls": { title: WebInspector.UIString("Calls"), width: "54px", sortable: true }, "function": { title: WebInspector.UIString("Function"), disclosure: true, sortable: true } }; if (Capabilities.samplingCPUProfiler) { delete columns.average; delete columns.calls; } this.dataGrid = new WebInspector.DataGrid(columns); this.dataGrid.addEventListener("sorting changed", this._sortProfile, this); this.dataGrid.element.addEventListener("mousedown", this._mouseDownInDataGrid.bind(this), true); this.dataGrid.show(this.element); this.viewSelectComboBox = new WebInspector.StatusBarComboBox(this._changeView.bind(this)); var heavyViewOption = document.createElement("option"); heavyViewOption.label = WebInspector.UIString("Heavy (Bottom Up)"); heavyViewOption.value = WebInspector.CPUProfileView._TypeHeavy; var treeViewOption = document.createElement("option"); treeViewOption.label = WebInspector.UIString("Tree (Top Down)"); treeViewOption.value = WebInspector.CPUProfileView._TypeTree; this.viewSelectComboBox.addOption(heavyViewOption); this.viewSelectComboBox.addOption(treeViewOption); this.viewSelectComboBox.select(this._viewType.get() === WebInspector.CPUProfileView._TypeHeavy ? heavyViewOption : treeViewOption); this.percentButton = new WebInspector.StatusBarButton("", "percent-time-status-bar-item"); this.percentButton.addEventListener("click", this._percentClicked, this); this.focusButton = new WebInspector.StatusBarButton(WebInspector.UIString("Focus selected function."), "focus-profile-node-status-bar-item"); this.focusButton.setEnabled(false); this.focusButton.addEventListener("click", this._focusClicked, this); this.excludeButton = new WebInspector.StatusBarButton(WebInspector.UIString("Exclude selected function."), "exclude-profile-node-status-bar-item"); this.excludeButton.setEnabled(false); this.excludeButton.addEventListener("click", this._excludeClicked, this); this.resetButton = new WebInspector.StatusBarButton(WebInspector.UIString("Restore all functions."), "reset-profile-status-bar-item"); this.resetButton.visible = false; this.resetButton.addEventListener("click", this._resetClicked, this); this.profile = profile; function profileCallback(error, profile) { if (error) return; if (!profile.head) { return; } this.profile.head = profile.head; if (profile.idleTime) this._injectIdleTimeNode(profile); this._assignParentsInProfile(); this._changeView(); this._updatePercentButton(); } this._linkifier = new WebInspector.Linkifier(new WebInspector.Linkifier.DefaultFormatter(30)); ProfilerAgent.getProfile(this.profile.profileType().id, this.profile.uid, profileCallback.bind(this)); } WebInspector.CPUProfileView._TypeTree = "Tree"; WebInspector.CPUProfileView._TypeHeavy = "Heavy"; WebInspector.CPUProfileView.prototype = { get statusBarItems() { return [this.viewSelectComboBox.element, this.percentButton.element, this.focusButton.element, this.excludeButton.element, this.resetButton.element]; }, get bottomUpProfileDataGridTree() { if (!this._bottomUpProfileDataGridTree) { if (this.profile.bottomUpHead) this._bottomUpProfileDataGridTree = new WebInspector.TopDownProfileDataGridTree(this, this.profile.bottomUpHead); else this._bottomUpProfileDataGridTree = new WebInspector.BottomUpProfileDataGridTree(this, this.profile.head); } return this._bottomUpProfileDataGridTree; }, get topDownProfileDataGridTree() { if (!this._topDownProfileDataGridTree) this._topDownProfileDataGridTree = new WebInspector.TopDownProfileDataGridTree(this, this.profile.head); return this._topDownProfileDataGridTree; }, get currentTree() { return this._currentTree; }, set currentTree(tree) { this._currentTree = tree; this.refresh(); }, willHide: function() { this._currentSearchResultIndex = -1; }, refresh: function() { var selectedProfileNode = this.dataGrid.selectedNode ? this.dataGrid.selectedNode.profileNode : null; this.dataGrid.rootNode().removeChildren(); var children = this.profileDataGridTree.children; var count = children.length; for (var index = 0; index < count; ++index) this.dataGrid.rootNode().appendChild(children[index]); if (selectedProfileNode) selectedProfileNode.selected = true; }, refreshVisibleData: function() { var child = this.dataGrid.rootNode().children[0]; while (child) { child.refresh(); child = child.traverseNextNode(false, null, true); } }, refreshShowAsPercents: function() { this._updatePercentButton(); this.refreshVisibleData(); }, searchCanceled: function() { if (this._searchResults) { for (var i = 0; i < this._searchResults.length; ++i) { var profileNode = this._searchResults[i].profileNode; delete profileNode._searchMatchedSelfColumn; delete profileNode._searchMatchedTotalColumn; delete profileNode._searchMatchedAverageColumn; delete profileNode._searchMatchedCallsColumn; delete profileNode._searchMatchedFunctionColumn; profileNode.refresh(); } } delete this._searchFinishedCallback; this._currentSearchResultIndex = -1; this._searchResults = []; }, performSearch: function(query, finishedCallback) { this.searchCanceled(); query = query.trim(); if (!query.length) return; this._searchFinishedCallback = finishedCallback; var greaterThan = (query.startsWith(">")); var lessThan = (query.startsWith("<")); var equalTo = (query.startsWith("=") || ((greaterThan || lessThan) && query.indexOf("=") === 1)); var percentUnits = (query.lastIndexOf("%") === (query.length - 1)); var millisecondsUnits = (query.length > 2 && query.lastIndexOf("ms") === (query.length - 2)); var secondsUnits = (!millisecondsUnits && query.lastIndexOf("s") === (query.length - 1)); var queryNumber = parseFloat(query); if (greaterThan || lessThan || equalTo) { if (equalTo && (greaterThan || lessThan)) queryNumber = parseFloat(query.substring(2)); else queryNumber = parseFloat(query.substring(1)); } var queryNumberMilliseconds = (secondsUnits ? (queryNumber * 1000) : queryNumber); if (!isNaN(queryNumber) && !(greaterThan || lessThan)) equalTo = true; var matcher = new RegExp(query.escapeForRegExp(), "i"); function matchesQuery( profileDataGridNode) { delete profileDataGridNode._searchMatchedSelfColumn; delete profileDataGridNode._searchMatchedTotalColumn; delete profileDataGridNode._searchMatchedAverageColumn; delete profileDataGridNode._searchMatchedCallsColumn; delete profileDataGridNode._searchMatchedFunctionColumn; if (percentUnits) { if (lessThan) { if (profileDataGridNode.selfPercent < queryNumber) profileDataGridNode._searchMatchedSelfColumn = true; if (profileDataGridNode.totalPercent < queryNumber) profileDataGridNode._searchMatchedTotalColumn = true; if (profileDataGridNode.averagePercent < queryNumberMilliseconds) profileDataGridNode._searchMatchedAverageColumn = true; } else if (greaterThan) { if (profileDataGridNode.selfPercent > queryNumber) profileDataGridNode._searchMatchedSelfColumn = true; if (profileDataGridNode.totalPercent > queryNumber) profileDataGridNode._searchMatchedTotalColumn = true; if (profileDataGridNode.averagePercent < queryNumberMilliseconds) profileDataGridNode._searchMatchedAverageColumn = true; } if (equalTo) { if (profileDataGridNode.selfPercent == queryNumber) profileDataGridNode._searchMatchedSelfColumn = true; if (profileDataGridNode.totalPercent == queryNumber) profileDataGridNode._searchMatchedTotalColumn = true; if (profileDataGridNode.averagePercent < queryNumberMilliseconds) profileDataGridNode._searchMatchedAverageColumn = true; } } else if (millisecondsUnits || secondsUnits) { if (lessThan) { if (profileDataGridNode.selfTime < queryNumberMilliseconds) profileDataGridNode._searchMatchedSelfColumn = true; if (profileDataGridNode.totalTime < queryNumberMilliseconds) profileDataGridNode._searchMatchedTotalColumn = true; if (profileDataGridNode.averageTime < queryNumberMilliseconds) profileDataGridNode._searchMatchedAverageColumn = true; } else if (greaterThan) { if (profileDataGridNode.selfTime > queryNumberMilliseconds) profileDataGridNode._searchMatchedSelfColumn = true; if (profileDataGridNode.totalTime > queryNumberMilliseconds) profileDataGridNode._searchMatchedTotalColumn = true; if (profileDataGridNode.averageTime > queryNumberMilliseconds) profileDataGridNode._searchMatchedAverageColumn = true; } if (equalTo) { if (profileDataGridNode.selfTime == queryNumberMilliseconds) profileDataGridNode._searchMatchedSelfColumn = true; if (profileDataGridNode.totalTime == queryNumberMilliseconds) profileDataGridNode._searchMatchedTotalColumn = true; if (profileDataGridNode.averageTime == queryNumberMilliseconds) profileDataGridNode._searchMatchedAverageColumn = true; } } else { if (equalTo && profileDataGridNode.numberOfCalls == queryNumber) profileDataGridNode._searchMatchedCallsColumn = true; if (greaterThan && profileDataGridNode.numberOfCalls > queryNumber) profileDataGridNode._searchMatchedCallsColumn = true; if (lessThan && profileDataGridNode.numberOfCalls < queryNumber) profileDataGridNode._searchMatchedCallsColumn = true; } if (profileDataGridNode.functionName.match(matcher) || profileDataGridNode.url.match(matcher)) profileDataGridNode._searchMatchedFunctionColumn = true; if (profileDataGridNode._searchMatchedSelfColumn || profileDataGridNode._searchMatchedTotalColumn || profileDataGridNode._searchMatchedAverageColumn || profileDataGridNode._searchMatchedCallsColumn || profileDataGridNode._searchMatchedFunctionColumn) { profileDataGridNode.refresh(); return true; } return false; } var current = this.profileDataGridTree.children[0]; while (current) { if (matchesQuery(current)) { this._searchResults.push({ profileNode: current }); } current = current.traverseNextNode(false, null, false); } finishedCallback(this, this._searchResults.length); }, jumpToFirstSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; this._currentSearchResultIndex = 0; this._jumpToSearchResult(this._currentSearchResultIndex); }, jumpToLastSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; this._currentSearchResultIndex = (this._searchResults.length - 1); this._jumpToSearchResult(this._currentSearchResultIndex); }, jumpToNextSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; if (++this._currentSearchResultIndex >= this._searchResults.length) this._currentSearchResultIndex = 0; this._jumpToSearchResult(this._currentSearchResultIndex); }, jumpToPreviousSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; if (--this._currentSearchResultIndex < 0) this._currentSearchResultIndex = (this._searchResults.length - 1); this._jumpToSearchResult(this._currentSearchResultIndex); }, showingFirstSearchResult: function() { return (this._currentSearchResultIndex === 0); }, showingLastSearchResult: function() { return (this._searchResults && this._currentSearchResultIndex === (this._searchResults.length - 1)); }, _jumpToSearchResult: function(index) { var searchResult = this._searchResults[index]; if (!searchResult) return; var profileNode = searchResult.profileNode; profileNode.revealAndSelect(); }, _changeView: function() { if (!this.profile) return; switch (this.viewSelectComboBox.selectedOption().value) { case WebInspector.CPUProfileView._TypeTree: this.profileDataGridTree = this.topDownProfileDataGridTree; this._sortProfile(); this._viewType.set(WebInspector.CPUProfileView._TypeTree); break; case WebInspector.CPUProfileView._TypeHeavy: this.profileDataGridTree = this.bottomUpProfileDataGridTree; this._sortProfile(); this._viewType.set(WebInspector.CPUProfileView._TypeHeavy); } if (!this.currentQuery || !this._searchFinishedCallback || !this._searchResults) return; this._searchFinishedCallback(this, -this._searchResults.length); this.performSearch(this.currentQuery, this._searchFinishedCallback); }, _percentClicked: function(event) { var currentState = this.showSelfTimeAsPercent.get() && this.showTotalTimeAsPercent.get() && this.showAverageTimeAsPercent.get(); this.showSelfTimeAsPercent.set(!currentState); this.showTotalTimeAsPercent.set(!currentState); this.showAverageTimeAsPercent.set(!currentState); this.refreshShowAsPercents(); }, _updatePercentButton: function() { if (this.showSelfTimeAsPercent.get() && this.showTotalTimeAsPercent.get() && this.showAverageTimeAsPercent.get()) { this.percentButton.title = WebInspector.UIString("Show absolute total and self times."); this.percentButton.toggled = true; } else { this.percentButton.title = WebInspector.UIString("Show total and self times as percentages."); this.percentButton.toggled = false; } }, _focusClicked: function(event) { if (!this.dataGrid.selectedNode) return; this.resetButton.visible = true; this.profileDataGridTree.focus(this.dataGrid.selectedNode); this.refresh(); this.refreshVisibleData(); }, _excludeClicked: function(event) { var selectedNode = this.dataGrid.selectedNode if (!selectedNode) return; selectedNode.deselect(); this.resetButton.visible = true; this.profileDataGridTree.exclude(selectedNode); this.refresh(); this.refreshVisibleData(); }, _resetClicked: function(event) { this.resetButton.visible = false; this.profileDataGridTree.restore(); this._linkifier.reset(); this.refresh(); this.refreshVisibleData(); }, _dataGridNodeSelected: function(node) { this.focusButton.setEnabled(true); this.excludeButton.setEnabled(true); }, _dataGridNodeDeselected: function(node) { this.focusButton.setEnabled(false); this.excludeButton.setEnabled(false); }, _sortProfile: function() { var sortAscending = this.dataGrid.sortOrder === "ascending"; var sortColumnIdentifier = this.dataGrid.sortColumnIdentifier; var sortProperty = { "average": "averageTime", "self": "selfTime", "total": "totalTime", "calls": "numberOfCalls", "function": "functionName" }[sortColumnIdentifier]; this.profileDataGridTree.sort(WebInspector.ProfileDataGridTree.propertyComparator(sortProperty, sortAscending)); this.refresh(); }, _mouseDownInDataGrid: function(event) { if (event.detail < 2) return; var cell = event.target.enclosingNodeOrSelfWithNodeName("td"); if (!cell || (!cell.hasStyleClass("total-column") && !cell.hasStyleClass("self-column") && !cell.hasStyleClass("average-column"))) return; if (cell.hasStyleClass("total-column")) this.showTotalTimeAsPercent.set(!this.showTotalTimeAsPercent.get()); else if (cell.hasStyleClass("self-column")) this.showSelfTimeAsPercent.set(!this.showSelfTimeAsPercent.get()); else if (cell.hasStyleClass("average-column")) this.showAverageTimeAsPercent.set(!this.showAverageTimeAsPercent.get()); this.refreshShowAsPercents(); event.consume(true); }, _assignParentsInProfile: function() { var head = this.profile.head; head.parent = null; head.head = null; var nodesToTraverse = [ { parent: head, children: head.children } ]; while (nodesToTraverse.length > 0) { var pair = nodesToTraverse.shift(); var parent = pair.parent; var children = pair.children; var length = children.length; for (var i = 0; i < length; ++i) { children[i].head = head; children[i].parent = parent; if (children[i].children.length > 0) nodesToTraverse.push({ parent: children[i], children: children[i].children }); } } }, _injectIdleTimeNode: function(profile) { var idleTime = profile.idleTime; var nodes = profile.head.children; var programNode = {selfTime: 0}; for (var i = nodes.length - 1; i >= 0; --i) { if (nodes[i].functionName === "(program)") { programNode = nodes[i]; break; } } var programTime = programNode.selfTime; if (idleTime > programTime) idleTime = programTime; programTime = programTime - idleTime; programNode.selfTime = programTime; programNode.totalTime = programTime; var idleNode = { functionName: "(idle)", url: null, lineNumber: 0, totalTime: idleTime, selfTime: idleTime, numberOfCalls: 0, visible: true, callUID: 0, children: [] }; nodes.push(idleNode); }, __proto__: WebInspector.View.prototype } WebInspector.CPUProfileType = function() { WebInspector.ProfileType.call(this, WebInspector.CPUProfileType.TypeId, WebInspector.UIString("Collect JavaScript CPU Profile")); this._recording = false; WebInspector.CPUProfileType.instance = this; } WebInspector.CPUProfileType.TypeId = "CPU"; WebInspector.CPUProfileType.prototype = { get buttonTooltip() { return this._recording ? WebInspector.UIString("Stop CPU profiling.") : WebInspector.UIString("Start CPU profiling."); }, buttonClicked: function() { if (this._recording) { this.stopRecordingProfile(); return false; } else { this.startRecordingProfile(); return true; } }, get treeItemTitle() { return WebInspector.UIString("CPU PROFILES"); }, get description() { return WebInspector.UIString("CPU profiles show where the execution time is spent in your page's JavaScript functions."); }, isRecordingProfile: function() { return this._recording; }, startRecordingProfile: function() { this._recording = true; WebInspector.userMetrics.ProfilesCPUProfileTaken.record(); ProfilerAgent.start(); }, stopRecordingProfile: function() { this._recording = false; ProfilerAgent.stop(); }, setRecordingProfile: function(isProfiling) { this._recording = isProfiling; }, createTemporaryProfile: function(title) { title = title || WebInspector.UIString("Recording\u2026"); return new WebInspector.CPUProfileHeader(this, title); }, createProfile: function(profile) { return new WebInspector.CPUProfileHeader(this, profile.title, profile.uid); }, __proto__: WebInspector.ProfileType.prototype } WebInspector.CPUProfileHeader = function(type, title, uid) { WebInspector.ProfileHeader.call(this, type, title, uid); } WebInspector.CPUProfileHeader.prototype = { createSidebarTreeElement: function() { return new WebInspector.ProfileSidebarTreeElement(this, WebInspector.UIString("Profile %d"), "profile-sidebar-tree-item"); }, createView: function(profilesPanel) { return new WebInspector.CPUProfileView(this); }, __proto__: WebInspector.ProfileHeader.prototype } ; WebInspector.CSSSelectorDataGridNode = function(profileView, data) { WebInspector.DataGridNode.call(this, data, false); this._profileView = profileView; } WebInspector.CSSSelectorDataGridNode.prototype = { get data() { var data = {}; data.selector = this._data.selector; data.matches = this._data.matchCount; if (this._profileView.showTimeAsPercent.get()) data.time = Number(this._data.timePercent).toFixed(1) + "%"; else data.time = Number.secondsToString(this._data.time / 1000, true); return data; }, get rawData() { return this._data; }, createCell: function(columnIdentifier) { var cell = WebInspector.DataGridNode.prototype.createCell.call(this, columnIdentifier); if (columnIdentifier === "selector" && cell.firstChild) { cell.firstChild.title = this.rawData.selector; return cell; } if (columnIdentifier !== "source") return cell; cell.removeChildren(); if (this.rawData.url) { var wrapperDiv = cell.createChild("div"); wrapperDiv.appendChild(WebInspector.linkifyResourceAsNode(this.rawData.url, this.rawData.lineNumber)); } return cell; }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.CSSSelectorProfileView = function(profile) { WebInspector.View.call(this); this.element.addStyleClass("profile-view"); this.showTimeAsPercent = WebInspector.settings.createSetting("selectorProfilerShowTimeAsPercent", true); var columns = { "selector": { title: WebInspector.UIString("Selector"), width: "550px", sortable: true }, "source": { title: WebInspector.UIString("Source"), width: "100px", sortable: true }, "time": { title: WebInspector.UIString("Total"), width: "72px", sort: "descending", sortable: true }, "matches": { title: WebInspector.UIString("Matches"), width: "72px", sortable: true } }; this.dataGrid = new WebInspector.DataGrid(columns); this.dataGrid.element.addStyleClass("selector-profile-view"); this.dataGrid.addEventListener("sorting changed", this._sortProfile, this); this.dataGrid.element.addEventListener("mousedown", this._mouseDownInDataGrid.bind(this), true); this.dataGrid.show(this.element); this.percentButton = new WebInspector.StatusBarButton("", "percent-time-status-bar-item"); this.percentButton.addEventListener("click", this._percentClicked, this); this.profile = profile; this._createProfileNodes(); this._sortProfile(); this._updatePercentButton(); } WebInspector.CSSSelectorProfileView.prototype = { get statusBarItems() { return [this.percentButton.element]; }, get profile() { return this._profile; }, set profile(profile) { this._profile = profile; }, _createProfileNodes: function() { var data = this.profile.data; if (!data) { return; } this.profile.children = []; for (var i = 0; i < data.length; ++i) { data[i].timePercent = data[i].time * 100 / this.profile.totalTime; var node = new WebInspector.CSSSelectorDataGridNode(this, data[i]); this.profile.children.push(node); } }, rebuildGridItems: function() { this.dataGrid.rootNode().removeChildren(); var children = this.profile.children; var count = children.length; for (var index = 0; index < count; ++index) this.dataGrid.rootNode().appendChild(children[index]); }, refreshData: function() { var child = this.dataGrid.rootNode().children[0]; while (child) { child.refresh(); child = child.traverseNextNode(false, null, true); } }, refreshShowAsPercents: function() { this._updatePercentButton(); this.refreshData(); }, _percentClicked: function(event) { this.showTimeAsPercent.set(!this.showTimeAsPercent.get()); this.refreshShowAsPercents(); }, _updatePercentButton: function() { if (this.showTimeAsPercent.get()) { this.percentButton.title = WebInspector.UIString("Show absolute times."); this.percentButton.toggled = true; } else { this.percentButton.title = WebInspector.UIString("Show times as percentages."); this.percentButton.toggled = false; } }, _sortProfile: function() { var sortAscending = this.dataGrid.sortOrder === "ascending"; var sortColumnIdentifier = this.dataGrid.sortColumnIdentifier; function selectorComparator(a, b) { var result = b.rawData.selector.localeCompare(a.rawData.selector); return sortAscending ? -result : result; } function sourceComparator(a, b) { var aRawData = a.rawData; var bRawData = b.rawData; var result = bRawData.url.localeCompare(aRawData.url); if (!result) result = bRawData.lineNumber - aRawData.lineNumber; return sortAscending ? -result : result; } function timeComparator(a, b) { const result = b.rawData.time - a.rawData.time; return sortAscending ? -result : result; } function matchesComparator(a, b) { const result = b.rawData.matchCount - a.rawData.matchCount; return sortAscending ? -result : result; } var comparator; switch (sortColumnIdentifier) { case "time": comparator = timeComparator; break; case "matches": comparator = matchesComparator; break; case "selector": comparator = selectorComparator; break; case "source": comparator = sourceComparator; break; } this.profile.children.sort(comparator); this.rebuildGridItems(); }, _mouseDownInDataGrid: function(event) { if (event.detail < 2) return; var cell = event.target.enclosingNodeOrSelfWithNodeName("td"); if (!cell) return; if (cell.hasStyleClass("time-column")) this.showTimeAsPercent.set(!this.showTimeAsPercent.get()); else return; this.refreshShowAsPercents(); event.consume(true); }, __proto__: WebInspector.View.prototype } WebInspector.CSSSelectorProfileType = function() { WebInspector.ProfileType.call(this, WebInspector.CSSSelectorProfileType.TypeId, WebInspector.UIString("Collect CSS Selector Profile")); this._recording = false; this._profileUid = 1; WebInspector.CSSSelectorProfileType.instance = this; } WebInspector.CSSSelectorProfileType.TypeId = "SELECTOR"; WebInspector.CSSSelectorProfileType.prototype = { get buttonTooltip() { return this._recording ? WebInspector.UIString("Stop CSS selector profiling.") : WebInspector.UIString("Start CSS selector profiling."); }, buttonClicked: function(profilesPanel) { if (this._recording) { this._stopRecordingProfile(profilesPanel); return false; } else { this._startRecordingProfile(profilesPanel); return true; } }, get treeItemTitle() { return WebInspector.UIString("CSS SELECTOR PROFILES"); }, get description() { return WebInspector.UIString("CSS selector profiles show how long the selector matching has taken in total and how many times a certain selector has matched DOM elements (the results are approximate due to matching algorithm optimizations.)"); }, reset: function() { this._profileUid = 1; }, setRecordingProfile: function(isProfiling) { this._recording = isProfiling; }, _startRecordingProfile: function(profilesPanel) { this._recording = true; CSSAgent.startSelectorProfiler(); profilesPanel.setRecordingProfile(WebInspector.CSSSelectorProfileType.TypeId, true); }, _stopRecordingProfile: function(profilesPanel) { function callback(error, profile) { if (error) return; var uid = this._profileUid++; var title = WebInspector.UIString("Profile %d", uid) + String.sprintf(" (%s)", Number.secondsToString(profile.totalTime / 1000)); var profileHeader = new WebInspector.CSSProfileHeader(this, title, uid, profile); profilesPanel.addProfileHeader(profileHeader); profilesPanel.setRecordingProfile(WebInspector.CSSSelectorProfileType.TypeId, false); } this._recording = false; CSSAgent.stopSelectorProfiler(callback.bind(this)); }, createTemporaryProfile: function(title) { title = title || WebInspector.UIString("Recording\u2026"); return new WebInspector.CSSProfileHeader(this, title); }, __proto__: WebInspector.ProfileType.prototype } WebInspector.CSSProfileHeader = function(type, title, uid, protocolData) { WebInspector.ProfileHeader.call(this, type, title, uid); this._protocolData = protocolData; } WebInspector.CSSProfileHeader.prototype = { createSidebarTreeElement: function() { return new WebInspector.ProfileSidebarTreeElement(this, this.title, "profile-sidebar-tree-item"); }, createView: function(profilesPanel) { var profile = (this._protocolData); return new WebInspector.CSSSelectorProfileView(profile); }, __proto__: WebInspector.ProfileHeader.prototype } ; WebInspector.HeapSnapshotArraySlice = function(array, start, end) { this._array = array; this._start = start; this.length = end - start; } WebInspector.HeapSnapshotArraySlice.prototype = { item: function(index) { return this._array[this._start + index]; }, slice: function(start, end) { if (typeof end === "undefined") end = this.length; return this._array.subarray(this._start + start, this._start + end); } } WebInspector.HeapSnapshotEdge = function(snapshot, edges, edgeIndex) { this._snapshot = snapshot; this._edges = edges; this.edgeIndex = edgeIndex || 0; } WebInspector.HeapSnapshotEdge.prototype = { clone: function() { return new WebInspector.HeapSnapshotEdge(this._snapshot, this._edges, this.edgeIndex); }, hasStringName: function() { if (!this.isShortcut()) return this._hasStringName(); return isNaN(parseInt(this._name(), 10)); }, isElement: function() { return this._type() === this._snapshot._edgeElementType; }, isHidden: function() { return this._type() === this._snapshot._edgeHiddenType; }, isWeak: function() { return this._type() === this._snapshot._edgeWeakType; }, isInternal: function() { return this._type() === this._snapshot._edgeInternalType; }, isInvisible: function() { return this._type() === this._snapshot._edgeInvisibleType; }, isShortcut: function() { return this._type() === this._snapshot._edgeShortcutType; }, name: function() { if (!this.isShortcut()) return this._name(); var numName = parseInt(this._name(), 10); return isNaN(numName) ? this._name() : numName; }, node: function() { return new WebInspector.HeapSnapshotNode(this._snapshot, this.nodeIndex()); }, nodeIndex: function() { return this._edges.item(this.edgeIndex + this._snapshot._edgeToNodeOffset); }, rawEdges: function() { return this._edges; }, toString: function() { var name = this.name(); switch (this.type()) { case "context": return "->" + name; case "element": return "[" + name + "]"; case "weak": return "[[" + name + "]]"; case "property": return name.indexOf(" ") === -1 ? "." + name : "[\"" + name + "\"]"; case "shortcut": if (typeof name === "string") return name.indexOf(" ") === -1 ? "." + name : "[\"" + name + "\"]"; else return "[" + name + "]"; case "internal": case "hidden": case "invisible": return "{" + name + "}"; }; return "?" + name + "?"; }, type: function() { return this._snapshot._edgeTypes[this._type()]; }, _hasStringName: function() { return !this.isElement() && !this.isHidden() && !this.isWeak(); }, _name: function() { return this._hasStringName() ? this._snapshot._strings[this._nameOrIndex()] : this._nameOrIndex(); }, _nameOrIndex: function() { return this._edges.item(this.edgeIndex + this._snapshot._edgeNameOffset); }, _type: function() { return this._edges.item(this.edgeIndex + this._snapshot._edgeTypeOffset); } }; WebInspector.HeapSnapshotEdgeIterator = function(edge) { this.edge = edge; } WebInspector.HeapSnapshotEdgeIterator.prototype = { first: function() { this.edge.edgeIndex = 0; }, hasNext: function() { return this.edge.edgeIndex < this.edge._edges.length; }, index: function() { return this.edge.edgeIndex; }, setIndex: function(newIndex) { this.edge.edgeIndex = newIndex; }, item: function() { return this.edge; }, next: function() { this.edge.edgeIndex += this.edge._snapshot._edgeFieldsCount; } }; WebInspector.HeapSnapshotRetainerEdge = function(snapshot, retainedNodeIndex, retainerIndex) { this._snapshot = snapshot; this._retainedNodeIndex = retainedNodeIndex; var retainedNodeOrdinal = retainedNodeIndex / snapshot._nodeFieldCount; this._firstRetainer = snapshot._firstRetainerIndex[retainedNodeOrdinal]; this._retainersCount = snapshot._firstRetainerIndex[retainedNodeOrdinal + 1] - this._firstRetainer; this.setRetainerIndex(retainerIndex); } WebInspector.HeapSnapshotRetainerEdge.prototype = { clone: function() { return new WebInspector.HeapSnapshotRetainerEdge(this._snapshot, this._retainedNodeIndex, this.retainerIndex()); }, hasStringName: function() { return this._edge().hasStringName(); }, isElement: function() { return this._edge().isElement(); }, isHidden: function() { return this._edge().isHidden(); }, isInternal: function() { return this._edge().isInternal(); }, isInvisible: function() { return this._edge().isInvisible(); }, isShortcut: function() { return this._edge().isShortcut(); }, isWeak: function() { return this._edge().isWeak(); }, name: function() { return this._edge().name(); }, node: function() { return this._node(); }, nodeIndex: function() { return this._nodeIndex; }, retainerIndex: function() { return this._retainerIndex; }, setRetainerIndex: function(newIndex) { if (newIndex !== this._retainerIndex) { this._retainerIndex = newIndex; this.edgeIndex = newIndex; } }, set edgeIndex(edgeIndex) { var retainerIndex = this._firstRetainer + edgeIndex; this._globalEdgeIndex = this._snapshot._retainingEdges[retainerIndex]; this._nodeIndex = this._snapshot._retainingNodes[retainerIndex]; delete this._edgeInstance; delete this._nodeInstance; }, _node: function() { if (!this._nodeInstance) this._nodeInstance = new WebInspector.HeapSnapshotNode(this._snapshot, this._nodeIndex); return this._nodeInstance; }, _edge: function() { if (!this._edgeInstance) { var edgeIndex = this._globalEdgeIndex - this._node()._edgeIndexesStart(); this._edgeInstance = new WebInspector.HeapSnapshotEdge(this._snapshot, this._node().rawEdges(), edgeIndex); } return this._edgeInstance; }, toString: function() { return this._edge().toString(); }, type: function() { return this._edge().type(); } } WebInspector.HeapSnapshotRetainerEdgeIterator = function(retainer) { this.retainer = retainer; } WebInspector.HeapSnapshotRetainerEdgeIterator.prototype = { first: function() { this.retainer.setRetainerIndex(0); }, hasNext: function() { return this.retainer.retainerIndex() < this.retainer._retainersCount; }, index: function() { return this.retainer.retainerIndex(); }, setIndex: function(newIndex) { this.retainer.setRetainerIndex(newIndex); }, item: function() { return this.retainer; }, next: function() { this.retainer.setRetainerIndex(this.retainer.retainerIndex() + 1); } }; WebInspector.HeapSnapshotNode = function(snapshot, nodeIndex) { this._snapshot = snapshot; this._firstNodeIndex = nodeIndex; this.nodeIndex = nodeIndex; } WebInspector.HeapSnapshotNode.prototype = { canBeQueried: function() { var flags = this._snapshot._flagsOfNode(this); return !!(flags & this._snapshot._nodeFlags.canBeQueried); }, isPageObject: function() { var flags = this._snapshot._flagsOfNode(this); return !!(flags & this._snapshot._nodeFlags.pageObject); }, distanceToWindow: function() { return this._snapshot._distancesToWindow[this.nodeIndex / this._snapshot._nodeFieldCount]; }, className: function() { var type = this.type(); switch (type) { case "hidden": return WebInspector.UIString("(system)"); case "object": case "native": return this.name(); case "code": return WebInspector.UIString("(compiled code)"); default: return "(" + type + ")"; } }, classIndex: function() { var snapshot = this._snapshot; var nodes = snapshot._nodes; var type = nodes[this.nodeIndex + snapshot._nodeTypeOffset];; if (type === snapshot._nodeObjectType || type === snapshot._nodeNativeType) return nodes[this.nodeIndex + snapshot._nodeNameOffset]; return -1 - type; }, dominatorIndex: function() { var nodeFieldCount = this._snapshot._nodeFieldCount; return this._snapshot._dominatorsTree[this.nodeIndex / this._snapshot._nodeFieldCount] * nodeFieldCount; }, edges: function() { return new WebInspector.HeapSnapshotEdgeIterator(new WebInspector.HeapSnapshotEdge(this._snapshot, this.rawEdges())); }, edgesCount: function() { return (this._edgeIndexesEnd() - this._edgeIndexesStart()) / this._snapshot._edgeFieldsCount; }, flags: function() { return this._snapshot._flagsOfNode(this); }, id: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeIdOffset]; }, isHidden: function() { return this._type() === this._snapshot._nodeHiddenType; }, isNative: function() { return this._type() === this._snapshot._nodeNativeType; }, isSynthetic: function() { return this._type() === this._snapshot._nodeSyntheticType; }, isWindow: function() { const windowRE = /^Window/; return windowRE.test(this.name()); }, isDetachedDOMTreesRoot: function() { return this.name() === "(Detached DOM trees)"; }, isDetachedDOMTree: function() { const detachedDOMTreeRE = /^Detached DOM tree/; return detachedDOMTreeRE.test(this.className()); }, isRoot: function() { return this.nodeIndex === this._snapshot._rootNodeIndex; }, name: function() { return this._snapshot._strings[this._name()]; }, rawEdges: function() { return new WebInspector.HeapSnapshotArraySlice(this._snapshot._containmentEdges, this._edgeIndexesStart(), this._edgeIndexesEnd()); }, retainedSize: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeRetainedSizeOffset]; }, retainers: function() { return new WebInspector.HeapSnapshotRetainerEdgeIterator(new WebInspector.HeapSnapshotRetainerEdge(this._snapshot, this.nodeIndex, 0)); }, selfSize: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeSelfSizeOffset]; }, type: function() { return this._snapshot._nodeTypes[this._type()]; }, _name: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeNameOffset]; }, _edgeIndexesStart: function() { return this._snapshot._firstEdgeIndexes[this._ordinal()]; }, _edgeIndexesEnd: function() { return this._snapshot._firstEdgeIndexes[this._ordinal() + 1]; }, _ordinal: function() { return this.nodeIndex / this._snapshot._nodeFieldCount; }, _nextNodeIndex: function() { return this.nodeIndex + this._snapshot._nodeFieldCount; }, _type: function() { var snapshot = this._snapshot; return snapshot._nodes[this.nodeIndex + snapshot._nodeTypeOffset]; } }; WebInspector.HeapSnapshotNodeIterator = function(node) { this.node = node; this._nodesLength = node._snapshot._nodes.length; } WebInspector.HeapSnapshotNodeIterator.prototype = { first: function() { this.node.nodeIndex = this.node._firstNodeIndex; }, hasNext: function() { return this.node.nodeIndex < this._nodesLength; }, index: function() { return this.node.nodeIndex; }, setIndex: function(newIndex) { this.node.nodeIndex = newIndex; }, item: function() { return this.node; }, next: function() { this.node.nodeIndex = this.node._nextNodeIndex(); } } WebInspector.HeapSnapshot = function(profile) { this.uid = profile.snapshot.uid; this._nodes = profile.nodes; this._containmentEdges = profile.edges; this._metaNode = profile.snapshot.meta; this._strings = profile.strings; this._snapshotDiffs = {}; this._aggregatesForDiff = null; this._init(); } function HeapSnapshotMetainfo() { this.node_fields = []; this.node_types = []; this.edge_fields = []; this.edge_types = []; this.fields = []; this.types = []; } function HeapSnapshotHeader() { this.title = ""; this.uid = 0; this.meta = new HeapSnapshotMetainfo(); this.node_count = 0; this.edge_count = 0; } WebInspector.HeapSnapshot.prototype = { _init: function() { var meta = this._metaNode; this._rootNodeIndex = 0; this._nodeTypeOffset = meta.node_fields.indexOf("type"); this._nodeNameOffset = meta.node_fields.indexOf("name"); this._nodeIdOffset = meta.node_fields.indexOf("id"); this._nodeSelfSizeOffset = meta.node_fields.indexOf("self_size"); this._nodeEdgeCountOffset = meta.node_fields.indexOf("edge_count"); this._nodeFieldCount = meta.node_fields.length; this._nodeTypes = meta.node_types[this._nodeTypeOffset]; this._nodeHiddenType = this._nodeTypes.indexOf("hidden"); this._nodeObjectType = this._nodeTypes.indexOf("object"); this._nodeNativeType = this._nodeTypes.indexOf("native"); this._nodeCodeType = this._nodeTypes.indexOf("code"); this._nodeSyntheticType = this._nodeTypes.indexOf("synthetic"); this._edgeFieldsCount = meta.edge_fields.length; this._edgeTypeOffset = meta.edge_fields.indexOf("type"); this._edgeNameOffset = meta.edge_fields.indexOf("name_or_index"); this._edgeToNodeOffset = meta.edge_fields.indexOf("to_node"); this._edgeTypes = meta.edge_types[this._edgeTypeOffset]; this._edgeTypes.push("invisible"); this._edgeElementType = this._edgeTypes.indexOf("element"); this._edgeHiddenType = this._edgeTypes.indexOf("hidden"); this._edgeInternalType = this._edgeTypes.indexOf("internal"); this._edgeShortcutType = this._edgeTypes.indexOf("shortcut"); this._edgeWeakType = this._edgeTypes.indexOf("weak"); this._edgeInvisibleType = this._edgeTypes.indexOf("invisible"); this._nodeFlags = { canBeQueried: 1, detachedDOMTreeNode: 2, pageObject: 4, visitedMarkerMask: 0x0ffff, visitedMarker: 0x10000 }; this.nodeCount = this._nodes.length / this._nodeFieldCount; this._edgeCount = this._containmentEdges.length / this._edgeFieldsCount; this._buildEdgeIndexes(); this._markInvisibleEdges(); this._buildRetainers(); this._calculateFlags(); this._calculateObjectToWindowDistance(); var result = this._buildPostOrderIndex(); this._dominatorsTree = this._buildDominatorTree(result.postOrderIndex2NodeOrdinal, result.nodeOrdinal2PostOrderIndex); this._calculateRetainedSizes(result.postOrderIndex2NodeOrdinal); this._buildDominatedNodes(); }, _buildEdgeIndexes: function() { if (this._nodeEdgeCountOffset === -1) { var nodes = this._nodes; var nodeCount = this.nodeCount; var firstEdgeIndexes = this._firstEdgeIndexes = new Uint32Array(nodeCount + 1); var nodeFieldCount = this._nodeFieldCount; var nodeEdgesIndexOffset = this._metaNode.node_fields.indexOf("edges_index"); firstEdgeIndexes[nodeCount] = this._containmentEdges.length; for (var nodeOrdinal = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) { firstEdgeIndexes[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeEdgesIndexOffset]; } return; } var nodes = this._nodes; var nodeCount = this.nodeCount; var firstEdgeIndexes = this._firstEdgeIndexes = new Uint32Array(nodeCount + 1); var nodeFieldCount = this._nodeFieldCount; var edgeFieldsCount = this._edgeFieldsCount; var nodeEdgeCountOffset = this._nodeEdgeCountOffset; firstEdgeIndexes[nodeCount] = this._containmentEdges.length; for (var nodeOrdinal = 0, edgeIndex = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) { firstEdgeIndexes[nodeOrdinal] = edgeIndex; edgeIndex += nodes[nodeOrdinal * nodeFieldCount + nodeEdgeCountOffset] * edgeFieldsCount; } }, _buildRetainers: function() { var retainingNodes = this._retainingNodes = new Uint32Array(this._edgeCount); var retainingEdges = this._retainingEdges = new Uint32Array(this._edgeCount); var firstRetainerIndex = this._firstRetainerIndex = new Uint32Array(this.nodeCount + 1); var containmentEdges = this._containmentEdges; var edgeFieldsCount = this._edgeFieldsCount; var nodeFieldCount = this._nodeFieldCount; var edgeToNodeOffset = this._edgeToNodeOffset; var nodes = this._nodes; var firstEdgeIndexes = this._firstEdgeIndexes; var nodeCount = this.nodeCount; for (var toNodeFieldIndex = edgeToNodeOffset, l = containmentEdges.length; toNodeFieldIndex < l; toNodeFieldIndex += edgeFieldsCount) { var toNodeIndex = containmentEdges[toNodeFieldIndex]; if (toNodeIndex % nodeFieldCount) throw new Error("Invalid toNodeIndex " + toNodeIndex); ++firstRetainerIndex[toNodeIndex / nodeFieldCount]; } for (var i = 0, firstUnusedRetainerSlot = 0; i < nodeCount; i++) { var retainersCount = firstRetainerIndex[i]; firstRetainerIndex[i] = firstUnusedRetainerSlot; retainingNodes[firstUnusedRetainerSlot] = retainersCount; firstUnusedRetainerSlot += retainersCount; } firstRetainerIndex[nodeCount] = retainingNodes.length; var nextNodeFirstEdgeIndex = firstEdgeIndexes[0]; for (var srcNodeOrdinal = 0; srcNodeOrdinal < nodeCount; ++srcNodeOrdinal) { var firstEdgeIndex = nextNodeFirstEdgeIndex; nextNodeFirstEdgeIndex = firstEdgeIndexes[srcNodeOrdinal + 1]; var srcNodeIndex = srcNodeOrdinal * nodeFieldCount; for (var edgeIndex = firstEdgeIndex; edgeIndex < nextNodeFirstEdgeIndex; edgeIndex += edgeFieldsCount) { var toNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; if (toNodeIndex % nodeFieldCount) throw new Error("Invalid toNodeIndex " + toNodeIndex); var firstRetainerSlotIndex = firstRetainerIndex[toNodeIndex / nodeFieldCount]; var nextUnusedRetainerSlotIndex = firstRetainerSlotIndex + (--retainingNodes[firstRetainerSlotIndex]); retainingNodes[nextUnusedRetainerSlotIndex] = srcNodeIndex; retainingEdges[nextUnusedRetainerSlotIndex] = edgeIndex; } } }, dispose: function() { delete this._nodes; delete this._strings; delete this._retainingEdges; delete this._retainingNodes; delete this._firstRetainerIndex; if (this._aggregates) { delete this._aggregates; delete this._aggregatesSortedFlags; } delete this._dominatedNodes; delete this._firstDominatedNodeIndex; delete this._flags; delete this._distancesToWindow; delete this._dominatorsTree; }, _allNodes: function() { return new WebInspector.HeapSnapshotNodeIterator(this.rootNode()); }, rootNode: function() { return new WebInspector.HeapSnapshotNode(this, this._rootNodeIndex); }, get rootNodeIndex() { return this._rootNodeIndex; }, get totalSize() { return this.rootNode().retainedSize(); }, _getDominatedIndex: function(nodeIndex) { if (nodeIndex % this._nodeFieldCount) throw new Error("Invalid nodeIndex: " + nodeIndex); return this._firstDominatedNodeIndex[nodeIndex / this._nodeFieldCount]; }, _dominatedNodesOfNode: function(node) { var dominatedIndexFrom = this._getDominatedIndex(node.nodeIndex); var dominatedIndexTo = this._getDominatedIndex(node._nextNodeIndex()); return new WebInspector.HeapSnapshotArraySlice(this._dominatedNodes, dominatedIndexFrom, dominatedIndexTo); }, _flagsOfNode: function(node) { return this._flags[node.nodeIndex / this._nodeFieldCount]; }, aggregates: function(sortedIndexes, key, filterString) { if (!this._aggregates) { this._aggregates = {}; this._aggregatesSortedFlags = {}; } var aggregatesByClassName = this._aggregates[key]; if (aggregatesByClassName) { if (sortedIndexes && !this._aggregatesSortedFlags[key]) { this._sortAggregateIndexes(aggregatesByClassName); this._aggregatesSortedFlags[key] = sortedIndexes; } return aggregatesByClassName; } var filter; if (filterString) filter = this._parseFilter(filterString); var aggregates = this._buildAggregates(filter); this._calculateClassesRetainedSize(aggregates.aggregatesByClassIndex, filter); aggregatesByClassName = aggregates.aggregatesByClassName; if (sortedIndexes) this._sortAggregateIndexes(aggregatesByClassName); this._aggregatesSortedFlags[key] = sortedIndexes; this._aggregates[key] = aggregatesByClassName; return aggregatesByClassName; }, aggregatesForDiff: function() { if (this._aggregatesForDiff) return this._aggregatesForDiff; var aggregatesByClassName = this.aggregates(true, "allObjects"); this._aggregatesForDiff = {}; var node = new WebInspector.HeapSnapshotNode(this); for (var className in aggregatesByClassName) { var aggregate = aggregatesByClassName[className]; var indexes = aggregate.idxs; var ids = new Array(indexes.length); var selfSizes = new Array(indexes.length); for (var i = 0; i < indexes.length; i++) { node.nodeIndex = indexes[i]; ids[i] = node.id(); selfSizes[i] = node.selfSize(); } this._aggregatesForDiff[className] = { indexes: indexes, ids: ids, selfSizes: selfSizes }; } return this._aggregatesForDiff; }, _calculateObjectToWindowDistance: function() { var nodeFieldCount = this._nodeFieldCount; var distances = new Uint32Array(this.nodeCount); var nodesToVisit = new Uint32Array(this.nodeCount); var nodesToVisitLength = 0; for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { var node = iter.edge.node(); if (node.isWindow()) { nodesToVisit[nodesToVisitLength++] = node.nodeIndex; distances[node.nodeIndex / nodeFieldCount] = 1; } } this._bfs(nodesToVisit, nodesToVisitLength, distances); nodesToVisitLength = 0; nodesToVisit[nodesToVisitLength++] = this._rootNodeIndex; distances[this._rootNodeIndex / nodeFieldCount] = 1; this._bfs(nodesToVisit, nodesToVisitLength, distances); this._distancesToWindow = distances; }, _bfs: function(nodesToVisit, nodesToVisitLength, distances) { var edgeFieldsCount = this._edgeFieldsCount; var nodeFieldCount = this._nodeFieldCount; var containmentEdges = this._containmentEdges; var firstEdgeIndexes = this._firstEdgeIndexes; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeTypeOffset = this._edgeTypeOffset; var nodes = this._nodes; var nodeCount = this.nodeCount; var containmentEdgesLength = containmentEdges.length; var edgeWeakType = this._edgeWeakType; var edgeShortcutType = this._edgeShortcutType; var index = 0; while (index < nodesToVisitLength) { var nodeIndex = nodesToVisit[index++]; var nodeOrdinal = nodeIndex / nodeFieldCount; var distance = distances[nodeOrdinal] + 1; var firstEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var edgesEnd = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = firstEdgeIndex; edgeIndex < edgesEnd; edgeIndex += edgeFieldsCount) { var edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; if (edgeType == edgeWeakType) continue; var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; if (distances[childNodeOrdinal]) continue; distances[childNodeOrdinal] = distance; nodesToVisit[nodesToVisitLength++] = childNodeIndex; } } if (nodesToVisitLength > nodeCount) throw new Error("BFS failed. Nodes to visit (" + nodesToVisitLength + ") is more than nodes count (" + nodeCount + ")"); }, _buildAggregates: function(filter) { var aggregates = {}; var aggregatesByClassName = {}; var classIndexes = []; var nodes = this._nodes; var flags = this._flags; var nodesLength = nodes.length; var nodeNativeType = this._nodeNativeType; var nodeFieldCount = this._nodeFieldCount; var selfSizeOffset = this._nodeSelfSizeOffset; var nodeTypeOffset = this._nodeTypeOffset; var pageObjectFlag = this._nodeFlags.pageObject; var node = new WebInspector.HeapSnapshotNode(this, this._rootNodeIndex); var distancesToWindow = this._distancesToWindow; for (var nodeIndex = this._rootNodeIndex; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { var nodeOrdinal = nodeIndex / nodeFieldCount; if (!(flags[nodeOrdinal] & pageObjectFlag)) continue; node.nodeIndex = nodeIndex; if (filter && !filter(node)) continue; var selfSize = nodes[nodeIndex + selfSizeOffset]; if (!selfSize && nodes[nodeIndex + nodeTypeOffset] !== nodeNativeType) continue; var classIndex = node.classIndex(); if (!(classIndex in aggregates)) { var nodeType = node.type(); var nameMatters = nodeType === "object" || nodeType === "native"; var value = { count: 1, distanceToWindow: distancesToWindow[nodeOrdinal], self: selfSize, maxRet: 0, type: nodeType, name: nameMatters ? node.name() : null, idxs: [nodeIndex] }; aggregates[classIndex] = value; classIndexes.push(classIndex); aggregatesByClassName[node.className()] = value; } else { var clss = aggregates[classIndex]; clss.distanceToWindow = Math.min(clss.distanceToWindow, distancesToWindow[nodeOrdinal]); ++clss.count; clss.self += selfSize; clss.idxs.push(nodeIndex); } } for (var i = 0, l = classIndexes.length; i < l; ++i) { var classIndex = classIndexes[i]; aggregates[classIndex].idxs = aggregates[classIndex].idxs.slice(); } return {aggregatesByClassName: aggregatesByClassName, aggregatesByClassIndex: aggregates}; }, _calculateClassesRetainedSize: function(aggregates, filter) { var rootNodeIndex = this._rootNodeIndex; var node = new WebInspector.HeapSnapshotNode(this, rootNodeIndex); var list = [rootNodeIndex]; var sizes = [-1]; var classes = []; var seenClassNameIndexes = {}; var nodeFieldCount = this._nodeFieldCount; var nodeTypeOffset = this._nodeTypeOffset; var nodeNativeType = this._nodeNativeType; var dominatedNodes = this._dominatedNodes; var nodes = this._nodes; var flags = this._flags; var pageObjectFlag = this._nodeFlags.pageObject; var firstDominatedNodeIndex = this._firstDominatedNodeIndex; while (list.length) { var nodeIndex = list.pop(); node.nodeIndex = nodeIndex; var classIndex = node.classIndex(); var seen = !!seenClassNameIndexes[classIndex]; var nodeOrdinal = nodeIndex / nodeFieldCount; var dominatedIndexFrom = firstDominatedNodeIndex[nodeOrdinal]; var dominatedIndexTo = firstDominatedNodeIndex[nodeOrdinal + 1]; if (!seen && (flags[nodeOrdinal] & pageObjectFlag) && (!filter || filter(node)) && (node.selfSize() || nodes[nodeIndex + nodeTypeOffset] === nodeNativeType) ) { aggregates[classIndex].maxRet += node.retainedSize(); if (dominatedIndexFrom !== dominatedIndexTo) { seenClassNameIndexes[classIndex] = true; sizes.push(list.length); classes.push(classIndex); } } for (var i = dominatedIndexFrom; i < dominatedIndexTo; i++) list.push(dominatedNodes[i]); var l = list.length; while (sizes[sizes.length - 1] === l) { sizes.pop(); classIndex = classes.pop(); seenClassNameIndexes[classIndex] = false; } } }, _sortAggregateIndexes: function(aggregates) { var nodeA = new WebInspector.HeapSnapshotNode(this); var nodeB = new WebInspector.HeapSnapshotNode(this); for (var clss in aggregates) aggregates[clss].idxs.sort( function(idxA, idxB) { nodeA.nodeIndex = idxA; nodeB.nodeIndex = idxB; return nodeA.id() < nodeB.id() ? -1 : 1; }); }, _buildPostOrderIndex: function() { var nodeFieldCount = this._nodeFieldCount; var nodes = this._nodes; var nodeCount = this.nodeCount; var rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; var edgeFieldsCount = this._edgeFieldsCount; var edgeTypeOffset = this._edgeTypeOffset; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeShortcutType = this._edgeShortcutType; var firstEdgeIndexes = this._firstEdgeIndexes; var containmentEdges = this._containmentEdges; var containmentEdgesLength = this._containmentEdges.length; var flags = this._flags; var flag = this._nodeFlags.pageObject; var nodesToVisit = new Uint32Array(nodeCount); var postOrderIndex2NodeOrdinal = new Uint32Array(nodeCount); var nodeOrdinal2PostOrderIndex = new Uint32Array(nodeCount); var painted = new Uint8Array(nodeCount); var nodesToVisitLength = 0; var postOrderIndex = 0; var grey = 1; var black = 2; nodesToVisit[nodesToVisitLength++] = rootNodeOrdinal; painted[rootNodeOrdinal] = grey; while (nodesToVisitLength) { var nodeOrdinal = nodesToVisit[nodesToVisitLength - 1]; if (painted[nodeOrdinal] === grey) { painted[nodeOrdinal] = black; var nodeFlag = flags[nodeOrdinal] & flag; var beginEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { if (nodeOrdinal !== rootNodeOrdinal && containmentEdges[edgeIndex + edgeTypeOffset] === edgeShortcutType) continue; var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; var childNodeFlag = flags[childNodeOrdinal] & flag; if (nodeOrdinal !== rootNodeOrdinal && childNodeFlag && !nodeFlag) continue; if (!painted[childNodeOrdinal]) { painted[childNodeOrdinal] = grey; nodesToVisit[nodesToVisitLength++] = childNodeOrdinal; } } } else { nodeOrdinal2PostOrderIndex[nodeOrdinal] = postOrderIndex; postOrderIndex2NodeOrdinal[postOrderIndex++] = nodeOrdinal; --nodesToVisitLength; } } if (postOrderIndex !== nodeCount) throw new Error("Postordering failed. " + (nodeCount - postOrderIndex) + " hanging nodes"); return {postOrderIndex2NodeOrdinal: postOrderIndex2NodeOrdinal, nodeOrdinal2PostOrderIndex: nodeOrdinal2PostOrderIndex}; }, _buildDominatorTree: function(postOrderIndex2NodeOrdinal, nodeOrdinal2PostOrderIndex) { var nodeFieldCount = this._nodeFieldCount; var nodes = this._nodes; var firstRetainerIndex = this._firstRetainerIndex; var retainingNodes = this._retainingNodes; var retainingEdges = this._retainingEdges; var edgeFieldsCount = this._edgeFieldsCount; var edgeTypeOffset = this._edgeTypeOffset; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeShortcutType = this._edgeShortcutType; var firstEdgeIndexes = this._firstEdgeIndexes; var containmentEdges = this._containmentEdges; var containmentEdgesLength = this._containmentEdges.length; var rootNodeIndex = this._rootNodeIndex; var flags = this._flags; var flag = this._nodeFlags.pageObject; var nodesCount = postOrderIndex2NodeOrdinal.length; var rootPostOrderedIndex = nodesCount - 1; var noEntry = nodesCount; var dominators = new Uint32Array(nodesCount); for (var i = 0; i < rootPostOrderedIndex; ++i) dominators[i] = noEntry; dominators[rootPostOrderedIndex] = rootPostOrderedIndex; var affected = new Uint8Array(nodesCount); var nodeOrdinal; { nodeOrdinal = this._rootNodeIndex / nodeFieldCount; var beginEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal] + edgeToNodeOffset; var endEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var toNodeFieldIndex = beginEdgeToNodeFieldIndex; toNodeFieldIndex < endEdgeToNodeFieldIndex; toNodeFieldIndex += edgeFieldsCount) { var childNodeOrdinal = containmentEdges[toNodeFieldIndex] / nodeFieldCount; affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]] = 1; } } var changed = true; while (changed) { changed = false; for (var postOrderIndex = rootPostOrderedIndex - 1; postOrderIndex >= 0; --postOrderIndex) { if (affected[postOrderIndex] === 0) continue; affected[postOrderIndex] = 0; if (dominators[postOrderIndex] === rootPostOrderedIndex) continue; nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; var nodeFlag = !!(flags[nodeOrdinal] & flag); var newDominatorIndex = noEntry; var beginRetainerIndex = firstRetainerIndex[nodeOrdinal]; var endRetainerIndex = firstRetainerIndex[nodeOrdinal + 1]; for (var retainerIndex = beginRetainerIndex; retainerIndex < endRetainerIndex; ++retainerIndex) { var retainerEdgeIndex = retainingEdges[retainerIndex]; var retainerEdgeType = containmentEdges[retainerEdgeIndex + edgeTypeOffset]; var retainerNodeIndex = retainingNodes[retainerIndex]; if (retainerNodeIndex !== rootNodeIndex && retainerEdgeType === edgeShortcutType) continue; var retainerNodeOrdinal = retainerNodeIndex / nodeFieldCount; var retainerNodeFlag = !!(flags[retainerNodeOrdinal] & flag); if (retainerNodeIndex !== rootNodeIndex && nodeFlag && !retainerNodeFlag) continue; var retanerPostOrderIndex = nodeOrdinal2PostOrderIndex[retainerNodeOrdinal]; if (dominators[retanerPostOrderIndex] !== noEntry) { if (newDominatorIndex === noEntry) newDominatorIndex = retanerPostOrderIndex; else { while (retanerPostOrderIndex !== newDominatorIndex) { while (retanerPostOrderIndex < newDominatorIndex) retanerPostOrderIndex = dominators[retanerPostOrderIndex]; while (newDominatorIndex < retanerPostOrderIndex) newDominatorIndex = dominators[newDominatorIndex]; } } if (newDominatorIndex === rootPostOrderedIndex) break; } } if (newDominatorIndex !== noEntry && dominators[postOrderIndex] !== newDominatorIndex) { dominators[postOrderIndex] = newDominatorIndex; changed = true; nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; beginEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal] + edgeToNodeOffset; endEdgeToNodeFieldIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var toNodeFieldIndex = beginEdgeToNodeFieldIndex; toNodeFieldIndex < endEdgeToNodeFieldIndex; toNodeFieldIndex += edgeFieldsCount) { var childNodeOrdinal = containmentEdges[toNodeFieldIndex] / nodeFieldCount; affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]] = 1; } } } } var dominatorsTree = new Uint32Array(nodesCount); for (var postOrderIndex = 0, l = dominators.length; postOrderIndex < l; ++postOrderIndex) { nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; dominatorsTree[nodeOrdinal] = postOrderIndex2NodeOrdinal[dominators[postOrderIndex]]; } return dominatorsTree; }, _calculateRetainedSizes: function(postOrderIndex2NodeOrdinal) { var nodeCount = this.nodeCount; var nodes = this._nodes; var nodeSelfSizeOffset = this._nodeSelfSizeOffset; var nodeFieldCount = this._nodeFieldCount; var dominatorsTree = this._dominatorsTree; var nodeRetainedSizeOffset = this._nodeRetainedSizeOffset = this._nodeEdgeCountOffset; delete this._nodeEdgeCountOffset; for (var nodeIndex = 0, l = nodes.length; nodeIndex < l; nodeIndex += nodeFieldCount) nodes[nodeIndex + nodeRetainedSizeOffset] = nodes[nodeIndex + nodeSelfSizeOffset]; for (var postOrderIndex = 0; postOrderIndex < nodeCount - 1; ++postOrderIndex) { var nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; var nodeIndex = nodeOrdinal * nodeFieldCount; var dominatorIndex = dominatorsTree[nodeOrdinal] * nodeFieldCount; nodes[dominatorIndex + nodeRetainedSizeOffset] += nodes[nodeIndex + nodeRetainedSizeOffset]; } }, _buildDominatedNodes: function() { var indexArray = this._firstDominatedNodeIndex = new Uint32Array(this.nodeCount + 1); var dominatedNodes = this._dominatedNodes = new Uint32Array(this.nodeCount - 1); var nodeFieldCount = this._nodeFieldCount; var dominatorsTree = this._dominatorsTree; for (var nodeOrdinal = 1, l = this.nodeCount; nodeOrdinal < l; ++nodeOrdinal) ++indexArray[dominatorsTree[nodeOrdinal]]; var firstDominatedNodeIndex = 0; for (var i = 0, l = this.nodeCount; i < l; ++i) { var dominatedCount = dominatedNodes[firstDominatedNodeIndex] = indexArray[i]; indexArray[i] = firstDominatedNodeIndex; firstDominatedNodeIndex += dominatedCount; } indexArray[this.nodeCount] = dominatedNodes.length; for (var nodeOrdinal = 1, l = this.nodeCount; nodeOrdinal < l; ++nodeOrdinal) { var dominatorOrdinal = dominatorsTree[nodeOrdinal]; var dominatedRefIndex = indexArray[dominatorOrdinal]; dominatedRefIndex += (--dominatedNodes[dominatedRefIndex]); dominatedNodes[dominatedRefIndex] = nodeOrdinal * nodeFieldCount; } }, _markInvisibleEdges: function() { for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { var edge = iter.edge; if (!edge.isShortcut()) continue; var node = edge.node(); var propNames = {}; for (var innerIter = node.edges(); innerIter.hasNext(); innerIter.next()) { var globalObjEdge = innerIter.edge; if (globalObjEdge.isShortcut()) propNames[globalObjEdge._nameOrIndex()] = true; } for (innerIter.first(); innerIter.hasNext(); innerIter.next()) { var globalObjEdge = innerIter.edge; if (!globalObjEdge.isShortcut() && globalObjEdge.node().isHidden() && globalObjEdge._hasStringName() && (globalObjEdge._nameOrIndex() in propNames)) this._containmentEdges[globalObjEdge._edges._start + globalObjEdge.edgeIndex + this._edgeTypeOffset] = this._edgeInvisibleType; } } }, _numbersComparator: function(a, b) { return a < b ? -1 : (a > b ? 1 : 0); }, _markDetachedDOMTreeNodes: function() { var flag = this._nodeFlags.detachedDOMTreeNode; var detachedDOMTreesRoot; for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { var node = iter.edge.node(); if (node.isDetachedDOMTreesRoot()) { detachedDOMTreesRoot = node; break; } } if (!detachedDOMTreesRoot) return; for (var iter = detachedDOMTreesRoot.edges(); iter.hasNext(); iter.next()) { var node = iter.edge.node(); if (node.isDetachedDOMTree()) { for (var edgesIter = node.edges(); edgesIter.hasNext(); edgesIter.next()) this._flags[edgesIter.edge.node().nodeIndex / this._nodeFieldCount] |= flag; } } }, _markPageOwnedNodes: function() { var edgeShortcutType = this._edgeShortcutType; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeTypeOffset = this._edgeTypeOffset; var edgeFieldsCount = this._edgeFieldsCount; var edgeWeakType = this._edgeWeakType; var firstEdgeIndexes = this._firstEdgeIndexes; var containmentEdges = this._containmentEdges; var containmentEdgesLength = containmentEdges.length; var nodes = this._nodes; var nodeFieldCount = this._nodeFieldCount; var nodesCount = this.nodeCount; var flags = this._flags; var flag = this._nodeFlags.pageObject; var visitedMarker = this._nodeFlags.visitedMarker; var visitedMarkerMask = this._nodeFlags.visitedMarkerMask; var markerAndFlag = visitedMarker | flag; var nodesToVisit = new Uint32Array(nodesCount); var nodesToVisitLength = 0; var rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; for (var edgeIndex = firstEdgeIndexes[rootNodeOrdinal], endEdgeIndex = firstEdgeIndexes[rootNodeOrdinal + 1]; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { if (containmentEdges[edgeIndex + edgeTypeOffset] === edgeShortcutType) { var nodeOrdinal = containmentEdges[edgeIndex + edgeToNodeOffset] / nodeFieldCount; nodesToVisit[nodesToVisitLength++] = nodeOrdinal; flags[nodeOrdinal] |= visitedMarker; } } while (nodesToVisitLength) { var nodeOrdinal = nodesToVisit[--nodesToVisitLength]; flags[nodeOrdinal] |= flag; flags[nodeOrdinal] &= visitedMarkerMask; var beginEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; if (flags[childNodeOrdinal] & markerAndFlag) continue; var type = containmentEdges[edgeIndex + edgeTypeOffset]; if (type === edgeWeakType) continue; nodesToVisit[nodesToVisitLength++] = childNodeOrdinal; flags[childNodeOrdinal] |= visitedMarker; } } }, _markQueriableHeapObjects: function() { var flag = this._nodeFlags.canBeQueried; var hiddenEdgeType = this._edgeHiddenType; var internalEdgeType = this._edgeInternalType; var invisibleEdgeType = this._edgeInvisibleType; var weakEdgeType = this._edgeWeakType; var edgeToNodeOffset = this._edgeToNodeOffset; var edgeTypeOffset = this._edgeTypeOffset; var edgeFieldsCount = this._edgeFieldsCount; var containmentEdges = this._containmentEdges; var nodes = this._nodes; var nodeCount = this.nodeCount; var nodeFieldCount = this._nodeFieldCount; var firstEdgeIndexes = this._firstEdgeIndexes; var flags = this._flags; var list = []; for (var iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { if (iter.edge.node().isWindow()) list.push(iter.edge.node().nodeIndex / nodeFieldCount); } while (list.length) { var nodeOrdinal = list.pop(); if (flags[nodeOrdinal] & flag) continue; flags[nodeOrdinal] |= flag; var beginEdgeIndex = firstEdgeIndexes[nodeOrdinal]; var endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (var edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { var childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; var childNodeOrdinal = childNodeIndex / nodeFieldCount; if (flags[childNodeOrdinal] & flag) continue; var type = containmentEdges[edgeIndex + edgeTypeOffset]; if (type === hiddenEdgeType || type === invisibleEdgeType || type === internalEdgeType || type === weakEdgeType) continue; list.push(childNodeOrdinal); } } }, _calculateFlags: function() { this._flags = new Uint32Array(this.nodeCount); this._markDetachedDOMTreeNodes(); this._markQueriableHeapObjects(); this._markPageOwnedNodes(); }, calculateSnapshotDiff: function(baseSnapshotId, baseSnapshotAggregates) { var snapshotDiff = this._snapshotDiffs[baseSnapshotId]; if (snapshotDiff) return snapshotDiff; snapshotDiff = {}; var aggregates = this.aggregates(true, "allObjects"); for (var className in baseSnapshotAggregates) { var baseAggregate = baseSnapshotAggregates[className]; var diff = this._calculateDiffForClass(baseAggregate, aggregates[className]); if (diff) snapshotDiff[className] = diff; } var emptyBaseAggregate = { ids: [], indexes: [], selfSizes: [] }; for (var className in aggregates) { if (className in baseSnapshotAggregates) continue; snapshotDiff[className] = this._calculateDiffForClass(emptyBaseAggregate, aggregates[className]); } this._snapshotDiffs[baseSnapshotId] = snapshotDiff; return snapshotDiff; }, _calculateDiffForClass: function(baseAggregate, aggregate) { var baseIds = baseAggregate.ids; var baseIndexes = baseAggregate.indexes; var baseSelfSizes = baseAggregate.selfSizes; var indexes = aggregate ? aggregate.idxs : []; var i = 0, l = baseIds.length; var j = 0, m = indexes.length; var diff = { addedCount: 0, removedCount: 0, addedSize: 0, removedSize: 0, deletedIndexes: [], addedIndexes: [] }; var nodeB = new WebInspector.HeapSnapshotNode(this, indexes[j]); while (i < l && j < m) { var nodeAId = baseIds[i]; if (nodeAId < nodeB.id()) { diff.deletedIndexes.push(baseIndexes[i]); diff.removedCount++; diff.removedSize += baseSelfSizes[i]; ++i; } else if (nodeAId > nodeB.id()) { diff.addedIndexes.push(indexes[j]); diff.addedCount++; diff.addedSize += nodeB.selfSize(); nodeB.nodeIndex = indexes[++j]; } else { ++i; nodeB.nodeIndex = indexes[++j]; } } while (i < l) { diff.deletedIndexes.push(baseIndexes[i]); diff.removedCount++; diff.removedSize += baseSelfSizes[i]; ++i; } while (j < m) { diff.addedIndexes.push(indexes[j]); diff.addedCount++; diff.addedSize += nodeB.selfSize(); nodeB.nodeIndex = indexes[++j]; } diff.countDelta = diff.addedCount - diff.removedCount; diff.sizeDelta = diff.addedSize - diff.removedSize; if (!diff.addedCount && !diff.removedCount) return null; return diff; }, _nodeForSnapshotObjectId: function(snapshotObjectId) { for (var it = this._allNodes(); it.hasNext(); it.next()) { if (it.node.id() === snapshotObjectId) return it.node; } return null; }, nodeClassName: function(snapshotObjectId) { var node = this._nodeForSnapshotObjectId(snapshotObjectId); if (node) return node.className(); return null; }, dominatorIdsForNode: function(snapshotObjectId) { var node = this._nodeForSnapshotObjectId(snapshotObjectId); if (!node) return null; var result = []; while (!node.isRoot()) { result.push(node.id()); node.nodeIndex = node.dominatorIndex(); } return result; }, _parseFilter: function(filter) { if (!filter) return null; var parsedFilter = eval("(function(){return " + filter + "})()"); return parsedFilter.bind(this); }, createEdgesProvider: function(nodeIndex, filter) { var node = new WebInspector.HeapSnapshotNode(this, nodeIndex); return new WebInspector.HeapSnapshotEdgesProvider(this, this._parseFilter(filter), node.edges()); }, createRetainingEdgesProvider: function(nodeIndex, filter) { var node = new WebInspector.HeapSnapshotNode(this, nodeIndex); return new WebInspector.HeapSnapshotEdgesProvider(this, this._parseFilter(filter), node.retainers()); }, createAddedNodesProvider: function(baseSnapshotId, className) { var snapshotDiff = this._snapshotDiffs[baseSnapshotId]; var diffForClass = snapshotDiff[className]; return new WebInspector.HeapSnapshotNodesProvider(this, null, diffForClass.addedIndexes); }, createDeletedNodesProvider: function(nodeIndexes) { return new WebInspector.HeapSnapshotNodesProvider(this, null, nodeIndexes); }, createNodesProviderForClass: function(className, aggregatesKey) { function filter(node) { return node.isPageObject(); } return new WebInspector.HeapSnapshotNodesProvider(this, filter, this.aggregates(false, aggregatesKey)[className].idxs); }, createNodesProviderForDominator: function(nodeIndex) { var node = new WebInspector.HeapSnapshotNode(this, nodeIndex); return new WebInspector.HeapSnapshotNodesProvider(this, null, this._dominatedNodesOfNode(node)); }, updateStaticData: function() { return {nodeCount: this.nodeCount, rootNodeIndex: this._rootNodeIndex, totalSize: this.totalSize, uid: this.uid, nodeFlags: this._nodeFlags}; } }; WebInspector.HeapSnapshotFilteredOrderedIterator = function(iterator, filter, unfilteredIterationOrder) { this._filter = filter; this._iterator = iterator; this._unfilteredIterationOrder = unfilteredIterationOrder; this._iterationOrder = null; this._position = 0; this._currentComparator = null; this._sortedPrefixLength = 0; } WebInspector.HeapSnapshotFilteredOrderedIterator.prototype = { _createIterationOrder: function() { if (this._iterationOrder) return; if (this._unfilteredIterationOrder && !this._filter) { this._iterationOrder = this._unfilteredIterationOrder.slice(0); this._unfilteredIterationOrder = null; return; } this._iterationOrder = []; var iterator = this._iterator; if (!this._unfilteredIterationOrder && !this._filter) { for (iterator.first(); iterator.hasNext(); iterator.next()) this._iterationOrder.push(iterator.index()); } else if (!this._unfilteredIterationOrder) { for (iterator.first(); iterator.hasNext(); iterator.next()) { if (this._filter(iterator.item())) this._iterationOrder.push(iterator.index()); } } else { var order = this._unfilteredIterationOrder.constructor === Array ? this._unfilteredIterationOrder : this._unfilteredIterationOrder.slice(0); for (var i = 0, l = order.length; i < l; ++i) { iterator.setIndex(order[i]); if (this._filter(iterator.item())) this._iterationOrder.push(iterator.index()); } this._unfilteredIterationOrder = null; } }, first: function() { this._position = 0; }, hasNext: function() { return this._position < this._iterationOrder.length; }, isEmpty: function() { if (this._iterationOrder) return !this._iterationOrder.length; if (this._unfilteredIterationOrder && !this._filter) return !this._unfilteredIterationOrder.length; var iterator = this._iterator; if (!this._unfilteredIterationOrder && !this._filter) { iterator.first(); return !iterator.hasNext(); } else if (!this._unfilteredIterationOrder) { for (iterator.first(); iterator.hasNext(); iterator.next()) if (this._filter(iterator.item())) return false; } else { var order = this._unfilteredIterationOrder.constructor === Array ? this._unfilteredIterationOrder : this._unfilteredIterationOrder.slice(0); for (var i = 0, l = order.length; i < l; ++i) { iterator.setIndex(order[i]); if (this._filter(iterator.item())) return false; } } return true; }, item: function() { this._iterator.setIndex(this._iterationOrder[this._position]); return this._iterator.item(); }, get length() { this._createIterationOrder(); return this._iterationOrder.length; }, next: function() { ++this._position; }, serializeItemsRange: function(begin, end) { this._createIterationOrder(); if (begin > end) throw new Error("Start position > end position: " + begin + " > " + end); if (end >= this._iterationOrder.length) end = this._iterationOrder.length; if (this._sortedPrefixLength < end) { this.sort(this._currentComparator, this._sortedPrefixLength, this._iterationOrder.length - 1, end - this._sortedPrefixLength); this._sortedPrefixLength = end; } this._position = begin; var startPosition = this._position; var count = end - begin; var result = new Array(count); for (var i = 0 ; i < count && this.hasNext(); ++i, this.next()) result[i] = this.serializeItem(this.item()); result.length = i; result.totalLength = this._iterationOrder.length; result.startPosition = startPosition; result.endPosition = this._position; return result; }, sortAll: function() { this._createIterationOrder(); if (this._sortedPrefixLength === this._iterationOrder.length) return; this.sort(this._currentComparator, this._sortedPrefixLength, this._iterationOrder.length - 1, this._iterationOrder.length); this._sortedPrefixLength = this._iterationOrder.length; }, sortAndRewind: function(comparator) { this._currentComparator = comparator; this._sortedPrefixLength = 0; this.first(); } } WebInspector.HeapSnapshotFilteredOrderedIterator.prototype.createComparator = function(fieldNames) { return {fieldName1:fieldNames[0], ascending1:fieldNames[1], fieldName2:fieldNames[2], ascending2:fieldNames[3]}; } WebInspector.HeapSnapshotEdgesProvider = function(snapshot, filter, edgesIter) { this.snapshot = snapshot; WebInspector.HeapSnapshotFilteredOrderedIterator.call(this, edgesIter, filter); } WebInspector.HeapSnapshotEdgesProvider.prototype = { serializeItem: function(edge) { return { name: edge.name(), propertyAccessor: edge.toString(), node: WebInspector.HeapSnapshotNodesProvider.prototype.serializeItem(edge.node()), nodeIndex: edge.nodeIndex(), type: edge.type(), distanceToWindow: edge.node().distanceToWindow() }; }, sort: function(comparator, leftBound, rightBound, count) { var fieldName1 = comparator.fieldName1; var fieldName2 = comparator.fieldName2; var ascending1 = comparator.ascending1; var ascending2 = comparator.ascending2; var edgeA = this._iterator.item().clone(); var edgeB = edgeA.clone(); var nodeA = new WebInspector.HeapSnapshotNode(this.snapshot); var nodeB = new WebInspector.HeapSnapshotNode(this.snapshot); function compareEdgeFieldName(ascending, indexA, indexB) { edgeA.edgeIndex = indexA; edgeB.edgeIndex = indexB; if (edgeB.name() === "__proto__") return -1; if (edgeA.name() === "__proto__") return 1; var result = edgeA.hasStringName() === edgeB.hasStringName() ? (edgeA.name() < edgeB.name() ? -1 : (edgeA.name() > edgeB.name() ? 1 : 0)) : (edgeA.hasStringName() ? -1 : 1); return ascending ? result : -result; } function compareNodeField(fieldName, ascending, indexA, indexB) { edgeA.edgeIndex = indexA; nodeA.nodeIndex = edgeA.nodeIndex(); var valueA = nodeA[fieldName](); edgeB.edgeIndex = indexB; nodeB.nodeIndex = edgeB.nodeIndex(); var valueB = nodeB[fieldName](); var result = valueA < valueB ? -1 : (valueA > valueB ? 1 : 0); return ascending ? result : -result; } function compareEdgeAndNode(indexA, indexB) { var result = compareEdgeFieldName(ascending1, indexA, indexB); if (result === 0) result = compareNodeField(fieldName2, ascending2, indexA, indexB); return result; } function compareNodeAndEdge(indexA, indexB) { var result = compareNodeField(fieldName1, ascending1, indexA, indexB); if (result === 0) result = compareEdgeFieldName(ascending2, indexA, indexB); return result; } function compareNodeAndNode(indexA, indexB) { var result = compareNodeField(fieldName1, ascending1, indexA, indexB); if (result === 0) result = compareNodeField(fieldName2, ascending2, indexA, indexB); return result; } if (fieldName1 === "!edgeName") this._iterationOrder.sortRange(compareEdgeAndNode, leftBound, rightBound, count); else if (fieldName2 === "!edgeName") this._iterationOrder.sortRange(compareNodeAndEdge, leftBound, rightBound, count); else this._iterationOrder.sortRange(compareNodeAndNode, leftBound, rightBound, count); }, __proto__: WebInspector.HeapSnapshotFilteredOrderedIterator.prototype } WebInspector.HeapSnapshotNodesProvider = function(snapshot, filter, nodeIndexes) { this.snapshot = snapshot; WebInspector.HeapSnapshotFilteredOrderedIterator.call(this, snapshot._allNodes(), filter, nodeIndexes); } WebInspector.HeapSnapshotNodesProvider.prototype = { nodePosition: function(snapshotObjectId) { this._createIterationOrder(); if (this.isEmpty()) return -1; this.sortAll(); var node = new WebInspector.HeapSnapshotNode(this.snapshot); for (var i = 0; i < this._iterationOrder.length; i++) { node.nodeIndex = this._iterationOrder[i]; if (node.id() === snapshotObjectId) return i; } return -1; }, serializeItem: function(node) { return { id: node.id(), name: node.name(), distanceToWindow: node.distanceToWindow(), nodeIndex: node.nodeIndex, retainedSize: node.retainedSize(), selfSize: node.selfSize(), type: node.type(), flags: node.flags() }; }, sort: function(comparator, leftBound, rightBound, count) { var fieldName1 = comparator.fieldName1; var fieldName2 = comparator.fieldName2; var ascending1 = comparator.ascending1; var ascending2 = comparator.ascending2; var nodeA = new WebInspector.HeapSnapshotNode(this.snapshot); var nodeB = new WebInspector.HeapSnapshotNode(this.snapshot); function sortByNodeField(fieldName, ascending) { var valueOrFunctionA = nodeA[fieldName]; var valueA = typeof valueOrFunctionA !== "function" ? valueOrFunctionA : valueOrFunctionA.call(nodeA); var valueOrFunctionB = nodeB[fieldName]; var valueB = typeof valueOrFunctionB !== "function" ? valueOrFunctionB : valueOrFunctionB.call(nodeB); var result = valueA < valueB ? -1 : (valueA > valueB ? 1 : 0); return ascending ? result : -result; } function sortByComparator(indexA, indexB) { nodeA.nodeIndex = indexA; nodeB.nodeIndex = indexB; var result = sortByNodeField(fieldName1, ascending1); if (result === 0) result = sortByNodeField(fieldName2, ascending2); return result; } this._iterationOrder.sortRange(sortByComparator, leftBound, rightBound, count); }, __proto__: WebInspector.HeapSnapshotFilteredOrderedIterator.prototype } ; WebInspector.HeapSnapshotSortableDataGrid = function(columns) { WebInspector.DataGrid.call(this, columns); this._recursiveSortingDepth = 0; this._highlightedNode = null; this._populatedAndSorted = false; this.addEventListener("sorting complete", this._sortingComplete, this); this.addEventListener("sorting changed", this.sortingChanged, this); } WebInspector.HeapSnapshotSortableDataGrid.Events = { ContentShown: "ContentShown" } WebInspector.HeapSnapshotSortableDataGrid.prototype = { defaultPopulateCount: function() { return 100; }, dispose: function() { var children = this.topLevelNodes(); for (var i = 0, l = children.length; i < l; ++i) children[i].dispose(); }, wasShown: function() { if (this._populatedAndSorted) this.dispatchEventToListeners(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown, this); }, _sortingComplete: function() { this.removeEventListener("sorting complete", this._sortingComplete, this); this._populatedAndSorted = true; this.dispatchEventToListeners(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown, this); }, willHide: function() { this._clearCurrentHighlight(); }, populateContextMenu: function(profilesPanel, contextMenu, event) { var td = event.target.enclosingNodeOrSelfWithNodeName("td"); if (!td) return; var node = td.heapSnapshotNode; if (node instanceof WebInspector.HeapSnapshotInstanceNode || node instanceof WebInspector.HeapSnapshotObjectNode) { function revealInDominatorsView() { profilesPanel.showObject(node.snapshotNodeId, "Dominators"); } contextMenu.appendItem(WebInspector.UIString("Reveal in Dominators View"), revealInDominatorsView.bind(this)); } else if (node instanceof WebInspector.HeapSnapshotDominatorObjectNode) { function revealInSummaryView() { profilesPanel.showObject(node.snapshotNodeId, "Summary"); } contextMenu.appendItem(WebInspector.UIString("Reveal in Summary View"), revealInSummaryView.bind(this)); } }, resetSortingCache: function() { delete this._lastSortColumnIdentifier; delete this._lastSortAscending; }, topLevelNodes: function() { return this.rootNode().children; }, highlightObjectByHeapSnapshotId: function(heapSnapshotObjectId) { }, highlightNode: function(node) { var prevNode = this._highlightedNode; this._clearCurrentHighlight(); this._highlightedNode = node; this._highlightedNode.element.addStyleClass("highlighted-row"); if (node === prevNode) { var element = node.element; var parent = element.parentElement; var nextSibling = element.nextSibling; parent.removeChild(element); parent.insertBefore(element, nextSibling); } }, nodeWasDetached: function(node) { if (this._highlightedNode === node) this._clearCurrentHighlight(); }, _clearCurrentHighlight: function() { if (!this._highlightedNode) return this._highlightedNode.element.removeStyleClass("highlighted-row"); this._highlightedNode = null; }, changeNameFilter: function(filter) { filter = filter.toLowerCase(); var children = this.topLevelNodes(); for (var i = 0, l = children.length; i < l; ++i) { var node = children[i]; if (node.depth === 0) node.revealed = node._name.toLowerCase().indexOf(filter) !== -1; } this.updateVisibleNodes(); }, sortingChanged: function() { var sortAscending = this.sortOrder === "ascending"; var sortColumnIdentifier = this.sortColumnIdentifier; if (this._lastSortColumnIdentifier === sortColumnIdentifier && this._lastSortAscending === sortAscending) return; this._lastSortColumnIdentifier = sortColumnIdentifier; this._lastSortAscending = sortAscending; var sortFields = this._sortFields(sortColumnIdentifier, sortAscending); function SortByTwoFields(nodeA, nodeB) { var field1 = nodeA[sortFields[0]]; var field2 = nodeB[sortFields[0]]; var result = field1 < field2 ? -1 : (field1 > field2 ? 1 : 0); if (!sortFields[1]) result = -result; if (result !== 0) return result; field1 = nodeA[sortFields[2]]; field2 = nodeB[sortFields[2]]; result = field1 < field2 ? -1 : (field1 > field2 ? 1 : 0); if (!sortFields[3]) result = -result; return result; } this._performSorting(SortByTwoFields); }, _performSorting: function(sortFunction) { this.recursiveSortingEnter(); var children = this._topLevelNodes; this.rootNode().removeChildren(); children.sort(sortFunction); for (var i = 0, l = children.length; i < l; ++i) { var child = children[i]; this.appendChildAfterSorting(child); if (child.expanded) child.sort(); } this.updateVisibleNodes(); this.recursiveSortingLeave(); }, appendChildAfterSorting: function(child) { var revealed = child.revealed; this.rootNode().appendChild(child); child.revealed = revealed; }, updateVisibleNodes: function() { }, recursiveSortingEnter: function() { ++this._recursiveSortingDepth; }, recursiveSortingLeave: function() { if (!this._recursiveSortingDepth) return; if (!--this._recursiveSortingDepth) this.dispatchEventToListeners("sorting complete"); }, __proto__: WebInspector.DataGrid.prototype } WebInspector.HeapSnapshotViewportDataGrid = function(columns) { WebInspector.HeapSnapshotSortableDataGrid.call(this, columns); this.scrollContainer.addEventListener("scroll", this._onScroll.bind(this), true); this._topLevelNodes = []; this._topPadding = new WebInspector.HeapSnapshotPaddingNode(); this._bottomPadding = new WebInspector.HeapSnapshotPaddingNode(); this._nodeToHighlightAfterScroll = null; } WebInspector.HeapSnapshotViewportDataGrid.prototype = { topLevelNodes: function() { return this._topLevelNodes; }, appendChildAfterSorting: function(child) { }, updateVisibleNodes: function() { var scrollTop = this.scrollContainer.scrollTop; var viewPortHeight = this.scrollContainer.offsetHeight; this._removePaddingRows(); var children = this._topLevelNodes; var i = 0; var topPadding = 0; while (i < children.length) { if (children[i].revealed) { var newTop = topPadding + children[i].nodeHeight(); if (newTop > scrollTop) break; topPadding = newTop; } ++i; } this.rootNode().removeChildren(); var heightToFill = viewPortHeight + (scrollTop - topPadding); var filledHeight = 0; while (i < children.length && filledHeight < heightToFill) { if (children[i].revealed) { this.rootNode().appendChild(children[i]); filledHeight += children[i].nodeHeight(); } ++i; } var bottomPadding = 0; while (i < children.length) { bottomPadding += children[i].nodeHeight(); ++i; } this._addPaddingRows(topPadding, bottomPadding); }, appendTopLevelNode: function(node) { this._topLevelNodes.push(node); }, removeTopLevelNodes: function() { this.rootNode().removeChildren(); this._topLevelNodes = []; }, highlightNode: function(node) { if (this._isScrolledIntoView(node.element)) WebInspector.HeapSnapshotSortableDataGrid.prototype.highlightNode.call(this, node); else { node.element.scrollIntoViewIfNeeded(true); this._nodeToHighlightAfterScroll = node; } }, _isScrolledIntoView: function(element) { var viewportTop = this.scrollContainer.scrollTop; var viewportBottom = viewportTop + this.scrollContainer.clientHeight; var elemTop = element.offsetTop var elemBottom = elemTop + element.offsetHeight; return elemBottom <= viewportBottom && elemTop >= viewportTop; }, _addPaddingRows: function(top, bottom) { if (this._topPadding.element.parentNode !== this.dataTableBody) this.dataTableBody.insertBefore(this._topPadding.element, this.dataTableBody.firstChild); if (this._bottomPadding.element.parentNode !== this.dataTableBody) this.dataTableBody.insertBefore(this._bottomPadding.element, this.dataTableBody.lastChild); this._topPadding.setHeight(top); this._bottomPadding.setHeight(bottom); }, _removePaddingRows: function() { this._bottomPadding.removeFromTable(); this._topPadding.removeFromTable(); }, onResize: function() { WebInspector.HeapSnapshotSortableDataGrid.prototype.onResize.call(this); this.updateVisibleNodes(); }, _onScroll: function(event) { this.updateVisibleNodes(); if (this._nodeToHighlightAfterScroll) { WebInspector.HeapSnapshotSortableDataGrid.prototype.highlightNode.call(this, this._nodeToHighlightAfterScroll); this._nodeToHighlightAfterScroll = null; } }, __proto__: WebInspector.HeapSnapshotSortableDataGrid.prototype } WebInspector.HeapSnapshotPaddingNode = function() { this.element = document.createElement("tr"); this.element.addStyleClass("revealed"); } WebInspector.HeapSnapshotPaddingNode.prototype = { setHeight: function(height) { this.element.style.height = height + "px"; }, removeFromTable: function() { var parent = this.element.parentNode; if (parent) parent.removeChild(this.element); } } WebInspector.HeapSnapshotContainmentDataGrid = function(columns) { columns = columns || { object: { title: WebInspector.UIString("Object"), disclosure: true, sortable: true }, shallowSize: { title: WebInspector.UIString("Shallow Size"), width: "120px", sortable: true }, retainedSize: { title: WebInspector.UIString("Retained Size"), width: "120px", sortable: true, sort: "descending" } }; WebInspector.HeapSnapshotSortableDataGrid.call(this, columns); } WebInspector.HeapSnapshotContainmentDataGrid.prototype = { setDataSource: function(snapshot, nodeIndex) { this.snapshot = snapshot; var node = new WebInspector.HeapSnapshotNode(snapshot, nodeIndex || snapshot.rootNodeIndex); var fakeEdge = { node: node }; this.setRootNode(new WebInspector.HeapSnapshotObjectNode(this, false, fakeEdge, null)); this.rootNode().sort(); }, sortingChanged: function() { this.rootNode().sort(); }, __proto__: WebInspector.HeapSnapshotSortableDataGrid.prototype } WebInspector.HeapSnapshotRetainmentDataGrid = function() { this.showRetainingEdges = true; var columns = { object: { title: WebInspector.UIString("Object"), disclosure: true, sortable: true }, shallowSize: { title: WebInspector.UIString("Shallow Size"), width: "120px", sortable: true }, retainedSize: { title: WebInspector.UIString("Retained Size"), width: "120px", sortable: true }, distanceToWindow: { title: WebInspector.UIString("Distance"), width: "80px", sortable: true, sort: "ascending" } }; WebInspector.HeapSnapshotContainmentDataGrid.call(this, columns); } WebInspector.HeapSnapshotRetainmentDataGrid.prototype = { _sortFields: function(sortColumn, sortAscending) { return { object: ["_name", sortAscending, "_count", false], count: ["_count", sortAscending, "_name", true], shallowSize: ["_shallowSize", sortAscending, "_name", true], retainedSize: ["_retainedSize", sortAscending, "_name", true], distanceToWindow: ["_distanceToWindow", sortAscending, "_name", true] }[sortColumn]; }, reset: function() { this.rootNode().removeChildren(); this.resetSortingCache(); }, __proto__: WebInspector.HeapSnapshotContainmentDataGrid.prototype } WebInspector.HeapSnapshotConstructorsDataGrid = function() { var columns = { object: { title: WebInspector.UIString("Constructor"), disclosure: true, sortable: true }, distanceToWindow: { title: WebInspector.UIString("Distance"), width: "90px", sortable: true }, count: { title: WebInspector.UIString("Objects Count"), width: "90px", sortable: true }, shallowSize: { title: WebInspector.UIString("Shallow Size"), width: "120px", sortable: true }, retainedSize: { title: WebInspector.UIString("Retained Size"), width: "120px", sort: "descending", sortable: true } }; WebInspector.HeapSnapshotViewportDataGrid.call(this, columns); this._profileIndex = -1; this._topLevelNodes = []; this._objectIdToSelect = null; } WebInspector.HeapSnapshotConstructorsDataGrid.prototype = { _sortFields: function(sortColumn, sortAscending) { return { object: ["_name", sortAscending, "_count", false], distanceToWindow: ["_distanceToWindow", sortAscending, "_retainedSize", true], count: ["_count", sortAscending, "_name", true], shallowSize: ["_shallowSize", sortAscending, "_name", true], retainedSize: ["_retainedSize", sortAscending, "_name", true] }[sortColumn]; }, highlightObjectByHeapSnapshotId: function(id) { if (!this.snapshot) { this._objectIdToSelect = id; return; } function didGetClassName(className) { var constructorNodes = this.topLevelNodes(); for (var i = 0; i < constructorNodes.length; i++) { var parent = constructorNodes[i]; if (parent._name === className) { parent.revealNodeBySnapshotObjectId(parseInt(id, 10)); return; } } } this.snapshot.nodeClassName(parseInt(id, 10), didGetClassName.bind(this)); }, setDataSource: function(snapshot) { this.snapshot = snapshot; if (this._profileIndex === -1) this._populateChildren(); if (this._objectIdToSelect) { this.highlightObjectByHeapSnapshotId(this._objectIdToSelect); this._objectIdToSelect = null; } }, _aggregatesReceived: function(key, aggregates) { for (var constructor in aggregates) this.appendTopLevelNode(new WebInspector.HeapSnapshotConstructorNode(this, constructor, aggregates[constructor], key)); this.sortingChanged(); }, _populateChildren: function() { this.dispose(); this.removeTopLevelNodes(); this.resetSortingCache(); var key = this._profileIndex === -1 ? "allObjects" : this._minNodeId + ".." + this._maxNodeId; var filter = this._profileIndex === -1 ? null : "function(node) { var id = node.id(); return id > " + this._minNodeId + " && id <= " + this._maxNodeId + "; }"; this.snapshot.aggregates(false, key, filter, this._aggregatesReceived.bind(this, key)); }, filterSelectIndexChanged: function(profiles, profileIndex) { this._profileIndex = profileIndex; delete this._maxNodeId; delete this._minNodeId; if (this._profileIndex !== -1) { this._minNodeId = profileIndex > 0 ? profiles[profileIndex - 1].maxJSObjectId : 0; this._maxNodeId = profiles[profileIndex].maxJSObjectId; } this._populateChildren(); }, __proto__: WebInspector.HeapSnapshotViewportDataGrid.prototype } WebInspector.HeapSnapshotDiffDataGrid = function() { var columns = { object: { title: WebInspector.UIString("Constructor"), disclosure: true, sortable: true }, addedCount: { title: WebInspector.UIString("# New"), width: "72px", sortable: true }, removedCount: { title: WebInspector.UIString("# Deleted"), width: "72px", sortable: true }, countDelta: { title: "# Delta", width: "64px", sortable: true }, addedSize: { title: WebInspector.UIString("Alloc. Size"), width: "72px", sortable: true, sort: "descending" }, removedSize: { title: WebInspector.UIString("Freed Size"), width: "72px", sortable: true }, sizeDelta: { title: "Size Delta", width: "72px", sortable: true } }; WebInspector.HeapSnapshotViewportDataGrid.call(this, columns); } WebInspector.HeapSnapshotDiffDataGrid.prototype = { defaultPopulateCount: function() { return 50; }, _sortFields: function(sortColumn, sortAscending) { return { object: ["_name", sortAscending, "_count", false], addedCount: ["_addedCount", sortAscending, "_name", true], removedCount: ["_removedCount", sortAscending, "_name", true], countDelta: ["_countDelta", sortAscending, "_name", true], addedSize: ["_addedSize", sortAscending, "_name", true], removedSize: ["_removedSize", sortAscending, "_name", true], sizeDelta: ["_sizeDelta", sortAscending, "_name", true] }[sortColumn]; }, setDataSource: function(snapshot) { this.snapshot = snapshot; }, setBaseDataSource: function(baseSnapshot) { this.baseSnapshot = baseSnapshot; this.dispose(); this.removeTopLevelNodes(); this.resetSortingCache(); if (this.baseSnapshot === this.snapshot) { this.dispatchEventToListeners("sorting complete"); return; } this._populateChildren(); }, _populateChildren: function() { function aggregatesForDiffReceived(aggregatesForDiff) { this.snapshot.calculateSnapshotDiff(this.baseSnapshot.uid, aggregatesForDiff, didCalculateSnapshotDiff.bind(this)); function didCalculateSnapshotDiff(diffByClassName) { for (var className in diffByClassName) { var diff = diffByClassName[className]; this.appendTopLevelNode(new WebInspector.HeapSnapshotDiffNode(this, className, diff)); } this.sortingChanged(); } } this.baseSnapshot.aggregatesForDiff(aggregatesForDiffReceived.bind(this)); }, __proto__: WebInspector.HeapSnapshotViewportDataGrid.prototype } WebInspector.HeapSnapshotDominatorsDataGrid = function() { var columns = { object: { title: WebInspector.UIString("Object"), disclosure: true, sortable: true }, shallowSize: { title: WebInspector.UIString("Shallow Size"), width: "120px", sortable: true }, retainedSize: { title: WebInspector.UIString("Retained Size"), width: "120px", sort: "descending", sortable: true } }; WebInspector.HeapSnapshotSortableDataGrid.call(this, columns); this._objectIdToSelect = null; } WebInspector.HeapSnapshotDominatorsDataGrid.prototype = { defaultPopulateCount: function() { return 25; }, setDataSource: function(snapshot) { this.snapshot = snapshot; var fakeNode = { nodeIndex: this.snapshot.rootNodeIndex }; this.setRootNode(new WebInspector.HeapSnapshotDominatorObjectNode(this, fakeNode)); this.rootNode().sort(); if (this._objectIdToSelect) { this.highlightObjectByHeapSnapshotId(this._objectIdToSelect); this._objectIdToSelect = null; } }, sortingChanged: function() { this.rootNode().sort(); }, highlightObjectByHeapSnapshotId: function(id) { if (!this.snapshot) { this._objectIdToSelect = id; return; } function didGetDominators(dominatorIds) { if (!dominatorIds) { WebInspector.log(WebInspector.UIString("Cannot find corresponding heap snapshot node")); return; } var dominatorNode = this.rootNode(); expandNextDominator.call(this, dominatorIds, dominatorNode); } function expandNextDominator(dominatorIds, dominatorNode) { if (!dominatorNode) { console.error("Cannot find dominator node"); return; } if (!dominatorIds.length) { this.highlightNode(dominatorNode); dominatorNode.element.scrollIntoViewIfNeeded(true); return; } var snapshotObjectId = dominatorIds.pop(); dominatorNode.retrieveChildBySnapshotObjectId(snapshotObjectId, expandNextDominator.bind(this, dominatorIds)); } this.snapshot.dominatorIdsForNode(parseInt(id, 10), didGetDominators.bind(this)); }, __proto__: WebInspector.HeapSnapshotSortableDataGrid.prototype } ; WebInspector.HeapSnapshotGridNode = function(tree, hasChildren) { WebInspector.DataGridNode.call(this, null, hasChildren); this._dataGrid = tree; this._instanceCount = 0; this._savedChildren = null; this._retrievedChildrenRanges = []; this.addEventListener("populate", this._populate, this); } WebInspector.HeapSnapshotGridNode.prototype = { createProvider: function() { throw new Error("Needs implemented."); }, _provider: function() { if (!this._providerObject) this._providerObject = this.createProvider(); return this._providerObject; }, createCell: function(columnIdentifier) { var cell = WebInspector.DataGridNode.prototype.createCell.call(this, columnIdentifier); if (this._searchMatched) cell.addStyleClass("highlight"); return cell; }, collapse: function() { WebInspector.DataGridNode.prototype.collapse.call(this); this._dataGrid.updateVisibleNodes(); }, dispose: function() { if (this._provider()) this._provider().dispose(); for (var node = this.children[0]; node; node = node.traverseNextNode(true, this, true)) if (node.dispose) node.dispose(); }, _reachableFromWindow: false, queryObjectContent: function(callback) { }, wasDetached: function() { this._dataGrid.nodeWasDetached(this); }, _toPercentString: function(num) { return num.toFixed(0) + "\u2009%"; }, childForPosition: function(nodePosition) { var indexOfFirsChildInRange = 0; for (var i = 0; i < this._retrievedChildrenRanges.length; i++) { var range = this._retrievedChildrenRanges[i]; if (range.from <= nodePosition && nodePosition < range.to) { var childIndex = indexOfFirsChildInRange + nodePosition - range.from; return this.children[childIndex]; } indexOfFirsChildInRange += range.to - range.from + 1; } return null; }, _createValueCell: function(columnIdentifier) { var cell = document.createElement("td"); cell.className = columnIdentifier + "-column"; if (this.dataGrid.snapshot.totalSize !== 0) { var div = document.createElement("div"); var valueSpan = document.createElement("span"); valueSpan.textContent = this.data[columnIdentifier]; div.appendChild(valueSpan); var percentColumn = columnIdentifier + "-percent"; if (percentColumn in this.data) { var percentSpan = document.createElement("span"); percentSpan.className = "percent-column"; percentSpan.textContent = this.data[percentColumn]; div.appendChild(percentSpan); } cell.appendChild(div); } return cell; }, _populate: function(event) { this.removeEventListener("populate", this._populate, this); function sorted() { this._populateChildren(); } this._provider().sortAndRewind(this.comparator(), sorted.bind(this)); }, expandWithoutPopulate: function(callback) { this.removeEventListener("populate", this._populate, this); this.expand(); this._provider().sortAndRewind(this.comparator(), callback); }, _populateChildren: function(fromPosition, toPosition, afterPopulate) { fromPosition = fromPosition || 0; toPosition = toPosition || fromPosition + this._dataGrid.defaultPopulateCount(); var firstNotSerializedPosition = fromPosition; function serializeNextChunk() { if (firstNotSerializedPosition >= toPosition) return; var end = Math.min(firstNotSerializedPosition + this._dataGrid.defaultPopulateCount(), toPosition); this._provider().serializeItemsRange(firstNotSerializedPosition, end, childrenRetrieved.bind(this)); firstNotSerializedPosition = end; } function insertRetrievedChild(item, insertionIndex) { if (this._savedChildren) { var hash = this._childHashForEntity(item); if (hash in this._savedChildren) { this.insertChild(this._savedChildren[hash], insertionIndex); return; } } this.insertChild(this._createChildNode(item), insertionIndex); } function insertShowMoreButton(from, to, insertionIndex) { var button = new WebInspector.ShowMoreDataGridNode(this._populateChildren.bind(this), from, to, this._dataGrid.defaultPopulateCount()); this.insertChild(button, insertionIndex); } function childrenRetrieved(items) { var itemIndex = 0; var itemPosition = items.startPosition; var insertionIndex = 0; if (!this._retrievedChildrenRanges.length) { if (items.startPosition > 0) { this._retrievedChildrenRanges.push({from: 0, to: 0}); insertShowMoreButton.call(this, 0, items.startPosition, insertionIndex++); } this._retrievedChildrenRanges.push({from: items.startPosition, to: items.endPosition}); for (var i = 0, l = items.length; i < l; ++i) insertRetrievedChild.call(this, items[i], insertionIndex++); if (items.endPosition < items.totalLength) insertShowMoreButton.call(this, items.endPosition, items.totalLength, insertionIndex++); } else { var rangeIndex = 0; var found = false; var range; while (rangeIndex < this._retrievedChildrenRanges.length) { range = this._retrievedChildrenRanges[rangeIndex]; if (range.to >= itemPosition) { found = true; break; } insertionIndex += range.to - range.from; if (range.to < items.totalLength) insertionIndex += 1; ++rangeIndex; } if (!found || items.startPosition < range.from) { this.children[insertionIndex - 1].setEndPosition(items.startPosition); insertShowMoreButton.call(this, items.startPosition, found ? range.from : items.totalLength, insertionIndex); range = {from: items.startPosition, to: items.startPosition}; if (!found) rangeIndex = this._retrievedChildrenRanges.length; this._retrievedChildrenRanges.splice(rangeIndex, 0, range); } else { insertionIndex += itemPosition - range.from; } while (range.to < items.endPosition) { var skipCount = range.to - itemPosition; insertionIndex += skipCount; itemIndex += skipCount; itemPosition = range.to; var nextRange = this._retrievedChildrenRanges[rangeIndex + 1]; var newEndOfRange = nextRange ? nextRange.from : items.totalLength; if (newEndOfRange > items.endPosition) newEndOfRange = items.endPosition; while (itemPosition < newEndOfRange) { insertRetrievedChild.call(this, items[itemIndex++], insertionIndex++); ++itemPosition; } if (nextRange && newEndOfRange === nextRange.from) { range.to = nextRange.to; this.removeChild(this.children[insertionIndex]); this._retrievedChildrenRanges.splice(rangeIndex + 1, 1); } else { range.to = newEndOfRange; if (newEndOfRange === items.totalLength) this.removeChild(this.children[insertionIndex]); else this.children[insertionIndex].setStartPosition(items.endPosition); } } } this._instanceCount += items.length; if (firstNotSerializedPosition < toPosition) { serializeNextChunk.call(this); return; } if (afterPopulate) afterPopulate(); this.dispatchEventToListeners("populate complete"); } serializeNextChunk.call(this); }, _saveChildren: function() { this._savedChildren = null; for (var i = 0, childrenCount = this.children.length; i < childrenCount; ++i) { var child = this.children[i]; if (!child.expanded) continue; if (!this._savedChildren) this._savedChildren = {}; this._savedChildren[this._childHashForNode(child)] = child; } }, sort: function() { this._dataGrid.recursiveSortingEnter(); function afterSort() { this._saveChildren(); this.removeChildren(); this._retrievedChildrenRanges = []; function afterPopulate() { for (var i = 0, l = this.children.length; i < l; ++i) { var child = this.children[i]; if (child.expanded) child.sort(); } this._dataGrid.recursiveSortingLeave(); } var instanceCount = this._instanceCount; this._instanceCount = 0; this._populateChildren(0, instanceCount, afterPopulate.bind(this)); } this._provider().sortAndRewind(this.comparator(), afterSort.bind(this)); }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.HeapSnapshotGenericObjectNode = function(tree, node) { this.snapshotNodeIndex = 0; WebInspector.HeapSnapshotGridNode.call(this, tree, false); if (!node) return; this._name = node.name; this._type = node.type; this._distanceToWindow = node.distanceToWindow; this._shallowSize = node.selfSize; this._retainedSize = node.retainedSize; this.snapshotNodeId = node.id; this.snapshotNodeIndex = node.nodeIndex; if (this._type === "string") this._reachableFromWindow = true; else if (this._type === "object" && this.isWindow(this._name)) { this._name = this.shortenWindowURL(this._name, false); this._reachableFromWindow = true; } else if (node.flags & tree.snapshot.nodeFlags.canBeQueried) this._reachableFromWindow = true; if (node.flags & tree.snapshot.nodeFlags.detachedDOMTreeNode) this.detachedDOMTreeNode = true; }; WebInspector.HeapSnapshotGenericObjectNode.prototype = { createCell: function(columnIdentifier) { var cell = columnIdentifier !== "object" ? this._createValueCell(columnIdentifier) : this._createObjectCell(); if (this._searchMatched) cell.addStyleClass("highlight"); return cell; }, _createObjectCell: function() { var cell = document.createElement("td"); cell.className = "object-column"; var div = document.createElement("div"); div.className = "source-code event-properties"; div.style.overflow = "visible"; var data = this.data["object"]; if (this._prefixObjectCell) this._prefixObjectCell(div, data); var valueSpan = document.createElement("span"); valueSpan.className = "value console-formatted-" + data.valueStyle; valueSpan.textContent = data.value; div.appendChild(valueSpan); var idSpan = document.createElement("span"); idSpan.className = "console-formatted-id"; idSpan.textContent = " @" + data["nodeId"]; div.appendChild(idSpan); if (this._postfixObjectCell) this._postfixObjectCell(div, data); cell.appendChild(div); cell.addStyleClass("disclosure"); if (this.depth) cell.style.setProperty("padding-left", (this.depth * this.dataGrid.indentWidth) + "px"); cell.heapSnapshotNode = this; return cell; }, get data() { var data = this._emptyData(); var value = this._name; var valueStyle = "object"; switch (this._type) { case "string": value = "\"" + value + "\""; valueStyle = "string"; break; case "regexp": value = "/" + value + "/"; valueStyle = "string"; break; case "closure": value = "function" + (value ? " " : "") + value + "()"; valueStyle = "function"; break; case "number": valueStyle = "number"; break; case "hidden": valueStyle = "null"; break; case "array": if (!value) value = "[]"; else value += "[]"; break; }; if (this._reachableFromWindow) valueStyle += " highlight"; if (value === "Object") value = ""; if (this.detachedDOMTreeNode) valueStyle += " detached-dom-tree-node"; data["object"] = { valueStyle: valueStyle, value: value, nodeId: this.snapshotNodeId }; data["distanceToWindow"] = this._distanceToWindow; data["shallowSize"] = Number.withThousandsSeparator(this._shallowSize); data["retainedSize"] = Number.withThousandsSeparator(this._retainedSize); data["shallowSize-percent"] = this._toPercentString(this._shallowSizePercent); data["retainedSize-percent"] = this._toPercentString(this._retainedSizePercent); return this._enhanceData ? this._enhanceData(data) : data; }, queryObjectContent: function(callback, objectGroupName) { if (this._type === "string") callback(WebInspector.RemoteObject.fromPrimitiveValue(this._name)); else { function formatResult(error, object) { if (!error && object.type) callback(WebInspector.RemoteObject.fromPayload(object), !!error); else callback(WebInspector.RemoteObject.fromPrimitiveValue(WebInspector.UIString("Not available"))); } ProfilerAgent.getObjectByHeapObjectId(String(this.snapshotNodeId), objectGroupName, formatResult); } }, get _retainedSizePercent() { return this._retainedSize / this.dataGrid.snapshot.totalSize * 100.0; }, get _shallowSizePercent() { return this._shallowSize / this.dataGrid.snapshot.totalSize * 100.0; }, updateHasChildren: function() { function isEmptyCallback(isEmpty) { this.hasChildren = !isEmpty; } this._provider().isEmpty(isEmptyCallback.bind(this)); }, isWindow: function(fullName) { return fullName.substr(0, 9) === "Window"; }, shortenWindowURL: function(fullName, hasObjectId) { var startPos = fullName.indexOf("/"); var endPos = hasObjectId ? fullName.indexOf("@") : fullName.length; if (startPos !== -1 && endPos !== -1) { var fullURL = fullName.substring(startPos + 1, endPos).trimLeft(); var url = fullURL.trimURL(); if (url.length > 40) url = url.trimMiddle(40); return fullName.substr(0, startPos + 2) + url + fullName.substr(endPos); } else return fullName; }, __proto__: WebInspector.HeapSnapshotGridNode.prototype } WebInspector.HeapSnapshotObjectNode = function(tree, isFromBaseSnapshot, edge, parentGridNode) { WebInspector.HeapSnapshotGenericObjectNode.call(this, tree, edge.node); this._referenceName = edge.name; this._referenceType = edge.type; this._propertyAccessor = edge.propertyAccessor; this._distanceToWindow = edge.distanceToWindow; this.showRetainingEdges = tree.showRetainingEdges; this._isFromBaseSnapshot = isFromBaseSnapshot; this._parentGridNode = parentGridNode; this._cycledWithAncestorGridNode = this._findAncestorWithSameSnapshotNodeId(); if (!this._cycledWithAncestorGridNode) this.updateHasChildren(); } WebInspector.HeapSnapshotObjectNode.prototype = { createProvider: function() { var tree = this._dataGrid; var showHiddenData = WebInspector.settings.showHeapSnapshotObjectsHiddenProperties.get(); var filter = "function(edge) {\n" + " return !edge.isInvisible()\n" + " && (" + !tree.showRetainingEdges + " || (edge.node().id() !== 1 && !edge.node().isSynthetic() && !edge.isWeak()))\n" + " && (" + showHiddenData + " || (!edge.isHidden() && !edge.node().isHidden()));\n" + "}\n"; var snapshot = this._isFromBaseSnapshot ? tree.baseSnapshot : tree.snapshot; if (this.showRetainingEdges) return snapshot.createRetainingEdgesProvider(this.snapshotNodeIndex, filter); else return snapshot.createEdgesProvider(this.snapshotNodeIndex, filter); }, _findAncestorWithSameSnapshotNodeId: function() { var ancestor = this._parentGridNode; while (ancestor) { if (ancestor.snapshotNodeId === this.snapshotNodeId) return ancestor; ancestor = ancestor._parentGridNode; } return null; }, _createChildNode: function(item) { return new WebInspector.HeapSnapshotObjectNode(this._dataGrid, this._isFromBaseSnapshot, item, this); }, _childHashForEntity: function(edge) { var prefix = this.showRetainingEdges ? edge.node.id + "#" : ""; return prefix + edge.type + "#" + edge.name; }, _childHashForNode: function(childNode) { var prefix = this.showRetainingEdges ? childNode.snapshotNodeId + "#" : ""; return prefix + childNode._referenceType + "#" + childNode._referenceName; }, comparator: function() { var sortAscending = this._dataGrid.sortOrder === "ascending"; var sortColumnIdentifier = this._dataGrid.sortColumnIdentifier; var sortFields = { object: ["!edgeName", sortAscending, "retainedSize", false], count: ["!edgeName", true, "retainedSize", false], shallowSize: ["selfSize", sortAscending, "!edgeName", true], retainedSize: ["retainedSize", sortAscending, "!edgeName", true], distanceToWindow: ["distanceToWindow", sortAscending, "_name", true] }[sortColumnIdentifier] || ["!edgeName", true, "retainedSize", false]; return WebInspector.HeapSnapshotFilteredOrderedIterator.prototype.createComparator(sortFields); }, _emptyData: function() { return { count: "", addedCount: "", removedCount: "", countDelta: "", addedSize: "", removedSize: "", sizeDelta: "" }; }, _enhanceData: function(data) { var name = this._referenceName; if (name === "") name = "(empty)"; var nameClass = "name"; switch (this._referenceType) { case "context": nameClass = "console-formatted-number"; break; case "internal": case "hidden": nameClass = "console-formatted-null"; break; case "element": name = "[" + name + "]"; break; } data["object"].nameClass = nameClass; data["object"].name = name; data["distanceToWindow"] = this._distanceToWindow; return data; }, _prefixObjectCell: function(div, data) { if (this._cycledWithAncestorGridNode) div.className += " cycled-ancessor-node"; var nameSpan = document.createElement("span"); nameSpan.className = data.nameClass; nameSpan.textContent = data.name; div.appendChild(nameSpan); var separatorSpan = document.createElement("span"); separatorSpan.className = "grayed"; separatorSpan.textContent = this.showRetainingEdges ? " in " : " :: "; div.appendChild(separatorSpan); }, __proto__: WebInspector.HeapSnapshotGenericObjectNode.prototype } WebInspector.HeapSnapshotInstanceNode = function(tree, baseSnapshot, snapshot, node) { WebInspector.HeapSnapshotGenericObjectNode.call(this, tree, node); this._baseSnapshotOrSnapshot = baseSnapshot || snapshot; this._isDeletedNode = !!baseSnapshot; this.updateHasChildren(); }; WebInspector.HeapSnapshotInstanceNode.prototype = { createProvider: function() { var showHiddenData = WebInspector.settings.showHeapSnapshotObjectsHiddenProperties.get(); return this._baseSnapshotOrSnapshot.createEdgesProvider( this.snapshotNodeIndex, "function(edge) {" + " return !edge.isInvisible()" + " && (" + showHiddenData + " || (!edge.isHidden() && !edge.node().isHidden()));" + "}"); }, _createChildNode: function(item) { return new WebInspector.HeapSnapshotObjectNode(this._dataGrid, this._isDeletedNode, item, null); }, _childHashForEntity: function(edge) { return edge.type + "#" + edge.name; }, _childHashForNode: function(childNode) { return childNode._referenceType + "#" + childNode._referenceName; }, comparator: function() { var sortAscending = this._dataGrid.sortOrder === "ascending"; var sortColumnIdentifier = this._dataGrid.sortColumnIdentifier; var sortFields = { object: ["!edgeName", sortAscending, "retainedSize", false], distanceToWindow: ["distanceToWindow", sortAscending, "retainedSize", false], count: ["!edgeName", true, "retainedSize", false], addedSize: ["selfSize", sortAscending, "!edgeName", true], removedSize: ["selfSize", sortAscending, "!edgeName", true], shallowSize: ["selfSize", sortAscending, "!edgeName", true], retainedSize: ["retainedSize", sortAscending, "!edgeName", true] }[sortColumnIdentifier] || ["!edgeName", true, "retainedSize", false]; return WebInspector.HeapSnapshotFilteredOrderedIterator.prototype.createComparator(sortFields); }, _emptyData: function() { return {count:"", countDelta:"", sizeDelta: ""}; }, _enhanceData: function(data) { if (this._isDeletedNode) { data["addedCount"] = ""; data["addedSize"] = ""; data["removedCount"] = "\u2022"; data["removedSize"] = Number.withThousandsSeparator(this._shallowSize); } else { data["addedCount"] = "\u2022"; data["addedSize"] = Number.withThousandsSeparator(this._shallowSize); data["removedCount"] = ""; data["removedSize"] = ""; } return data; }, get isDeletedNode() { return this._isDeletedNode; }, __proto__: WebInspector.HeapSnapshotGenericObjectNode.prototype } WebInspector.HeapSnapshotConstructorNode = function(tree, className, aggregate, aggregatesKey) { WebInspector.HeapSnapshotGridNode.call(this, tree, aggregate.count > 0); this._name = className; this._aggregatesKey = aggregatesKey; this._distanceToWindow = aggregate.distanceToWindow; this._count = aggregate.count; this._shallowSize = aggregate.self; this._retainedSize = aggregate.maxRet; } WebInspector.HeapSnapshotConstructorNode.prototype = { createProvider: function() { return this._dataGrid.snapshot.createNodesProviderForClass(this._name, this._aggregatesKey) }, revealNodeBySnapshotObjectId: function(snapshotObjectId) { function didExpand() { this._provider().nodePosition(snapshotObjectId, didGetNodePosition.bind(this)); } function didGetNodePosition(nodePosition) { if (nodePosition === -1) this.collapse(); else this._populateChildren(nodePosition, null, didPopulateChildren.bind(this, nodePosition)); } function didPopulateChildren(nodePosition) { var indexOfFirsChildInRange = 0; for (var i = 0; i < this._retrievedChildrenRanges.length; i++) { var range = this._retrievedChildrenRanges[i]; if (range.from <= nodePosition && nodePosition < range.to) { var childIndex = indexOfFirsChildInRange + nodePosition - range.from; var instanceNode = this.children[childIndex]; this._dataGrid.highlightNode(instanceNode); return; } indexOfFirsChildInRange += range.to - range.from + 1; } } this.expandWithoutPopulate(didExpand.bind(this)); }, createCell: function(columnIdentifier) { var cell = columnIdentifier !== "object" ? this._createValueCell(columnIdentifier) : WebInspector.HeapSnapshotGridNode.prototype.createCell.call(this, columnIdentifier); if (this._searchMatched) cell.addStyleClass("highlight"); return cell; }, _createChildNode: function(item) { return new WebInspector.HeapSnapshotInstanceNode(this._dataGrid, null, this._dataGrid.snapshot, item); }, comparator: function() { var sortAscending = this._dataGrid.sortOrder === "ascending"; var sortColumnIdentifier = this._dataGrid.sortColumnIdentifier; var sortFields = { object: ["id", sortAscending, "retainedSize", false], distanceToWindow: ["distanceToWindow", true, "retainedSize", false], count: ["id", true, "retainedSize", false], shallowSize: ["selfSize", sortAscending, "id", true], retainedSize: ["retainedSize", sortAscending, "id", true] }[sortColumnIdentifier]; return WebInspector.HeapSnapshotFilteredOrderedIterator.prototype.createComparator(sortFields); }, _childHashForEntity: function(node) { return node.id; }, _childHashForNode: function(childNode) { return childNode.snapshotNodeId; }, get data() { var data = { object: this._name }; data["count"] = Number.withThousandsSeparator(this._count); data["distanceToWindow"] = this._distanceToWindow; data["shallowSize"] = Number.withThousandsSeparator(this._shallowSize); data["retainedSize"] = Number.withThousandsSeparator(this._retainedSize); data["count-percent"] = this._toPercentString(this._countPercent); data["shallowSize-percent"] = this._toPercentString(this._shallowSizePercent); data["retainedSize-percent"] = this._toPercentString(this._retainedSizePercent); return data; }, get _countPercent() { return this._count / this.dataGrid.snapshot.nodeCount * 100.0; }, get _retainedSizePercent() { return this._retainedSize / this.dataGrid.snapshot.totalSize * 100.0; }, get _shallowSizePercent() { return this._shallowSize / this.dataGrid.snapshot.totalSize * 100.0; }, __proto__: WebInspector.HeapSnapshotGridNode.prototype } WebInspector.HeapSnapshotDiffNodesProvider = function(addedNodesProvider, deletedNodesProvider, addedCount, removedCount) { this._addedNodesProvider = addedNodesProvider; this._deletedNodesProvider = deletedNodesProvider; this._addedCount = addedCount; this._removedCount = removedCount; } WebInspector.HeapSnapshotDiffNodesProvider.prototype = { dispose: function() { this._addedNodesProvider.dispose(); this._deletedNodesProvider.dispose(); }, isEmpty: function(callback) { callback(false); }, serializeItemsRange: function(beginPosition, endPosition, callback) { function didReceiveAllItems(items) { items.totalLength = this._addedCount + this._removedCount; callback(items); } function didReceiveDeletedItems(addedItems, items) { if (!addedItems.length) addedItems.startPosition = this._addedCount + items.startPosition; for (var i = 0; i < items.length; i++) { items[i].isAddedNotRemoved = false; addedItems.push(items[i]); } addedItems.endPosition = this._addedCount + items.endPosition; didReceiveAllItems.call(this, addedItems); } function didReceiveAddedItems(items) { for (var i = 0; i < items.length; i++) items[i].isAddedNotRemoved = true; if (items.endPosition < endPosition) return this._deletedNodesProvider.serializeItemsRange(0, endPosition - items.endPosition, didReceiveDeletedItems.bind(this, items)); items.totalLength = this._addedCount + this._removedCount; didReceiveAllItems.call(this, items); } if (beginPosition < this._addedCount) this._addedNodesProvider.serializeItemsRange(beginPosition, endPosition, didReceiveAddedItems.bind(this)); else this._deletedNodesProvider.serializeItemsRange(beginPosition - this._addedCount, endPosition - this._addedCount, didReceiveDeletedItems.bind(this, [])); }, sortAndRewind: function(comparator, callback) { function afterSort() { this._deletedNodesProvider.sortAndRewind(comparator, callback); } this._addedNodesProvider.sortAndRewind(comparator, afterSort.bind(this)); } }; WebInspector.HeapSnapshotDiffNode = function(tree, className, diffForClass) { WebInspector.HeapSnapshotGridNode.call(this, tree, true); this._name = className; this._addedCount = diffForClass.addedCount; this._removedCount = diffForClass.removedCount; this._countDelta = diffForClass.countDelta; this._addedSize = diffForClass.addedSize; this._removedSize = diffForClass.removedSize; this._sizeDelta = diffForClass.sizeDelta; this._deletedIndexes = diffForClass.deletedIndexes; } WebInspector.HeapSnapshotDiffNode.prototype = { createProvider: function() { var tree = this._dataGrid; return new WebInspector.HeapSnapshotDiffNodesProvider( tree.snapshot.createAddedNodesProvider(tree.baseSnapshot.uid, this._name), tree.baseSnapshot.createDeletedNodesProvider(this._deletedIndexes), this._addedCount, this._removedCount); }, _createChildNode: function(item) { if (item.isAddedNotRemoved) return new WebInspector.HeapSnapshotInstanceNode(this._dataGrid, null, this._dataGrid.snapshot, item); else return new WebInspector.HeapSnapshotInstanceNode(this._dataGrid, this._dataGrid.baseSnapshot, null, item); }, _childHashForEntity: function(node) { return node.id; }, _childHashForNode: function(childNode) { return childNode.snapshotNodeId; }, comparator: function() { var sortAscending = this._dataGrid.sortOrder === "ascending"; var sortColumnIdentifier = this._dataGrid.sortColumnIdentifier; var sortFields = { object: ["id", sortAscending, "selfSize", false], addedCount: ["selfSize", sortAscending, "id", true], removedCount: ["selfSize", sortAscending, "id", true], countDelta: ["selfSize", sortAscending, "id", true], addedSize: ["selfSize", sortAscending, "id", true], removedSize: ["selfSize", sortAscending, "id", true], sizeDelta: ["selfSize", sortAscending, "id", true] }[sortColumnIdentifier]; return WebInspector.HeapSnapshotFilteredOrderedIterator.prototype.createComparator(sortFields); }, _signForDelta: function(delta) { if (delta === 0) return ""; if (delta > 0) return "+"; else return "\u2212"; }, get data() { var data = {object: this._name}; data["addedCount"] = Number.withThousandsSeparator(this._addedCount); data["removedCount"] = Number.withThousandsSeparator(this._removedCount); data["countDelta"] = this._signForDelta(this._countDelta) + Number.withThousandsSeparator(Math.abs(this._countDelta)); data["addedSize"] = Number.withThousandsSeparator(this._addedSize); data["removedSize"] = Number.withThousandsSeparator(this._removedSize); data["sizeDelta"] = this._signForDelta(this._sizeDelta) + Number.withThousandsSeparator(Math.abs(this._sizeDelta)); return data; }, __proto__: WebInspector.HeapSnapshotGridNode.prototype } WebInspector.HeapSnapshotDominatorObjectNode = function(tree, node) { WebInspector.HeapSnapshotGenericObjectNode.call(this, tree, node); this.updateHasChildren(); }; WebInspector.HeapSnapshotDominatorObjectNode.prototype = { createProvider: function() { return this._dataGrid.snapshot.createNodesProviderForDominator(this.snapshotNodeIndex); }, retrieveChildBySnapshotObjectId: function(snapshotObjectId, callback) { function didExpand() { this._provider().nodePosition(snapshotObjectId, didGetNodePosition.bind(this)); } function didGetNodePosition(nodePosition) { if (nodePosition === -1) { this.collapse(); callback(null); } else this._populateChildren(nodePosition, null, didPopulateChildren.bind(this, nodePosition)); } function didPopulateChildren(nodePosition) { var child = this.childForPosition(nodePosition); callback(child); } this.hasChildren = true; this.expandWithoutPopulate(didExpand.bind(this)); }, _createChildNode: function(item) { return new WebInspector.HeapSnapshotDominatorObjectNode(this._dataGrid, item); }, _childHashForEntity: function(node) { return node.id; }, _childHashForNode: function(childNode) { return childNode.snapshotNodeId; }, comparator: function() { var sortAscending = this._dataGrid.sortOrder === "ascending"; var sortColumnIdentifier = this._dataGrid.sortColumnIdentifier; var sortFields = { object: ["id", sortAscending, "retainedSize", false], shallowSize: ["selfSize", sortAscending, "id", true], retainedSize: ["retainedSize", sortAscending, "id", true] }[sortColumnIdentifier]; return WebInspector.HeapSnapshotFilteredOrderedIterator.prototype.createComparator(sortFields); }, _emptyData: function() { return {}; }, __proto__: WebInspector.HeapSnapshotGenericObjectNode.prototype } ; WebInspector.HeapSnapshotLoader = function() { this._reset(); } WebInspector.HeapSnapshotLoader.prototype = { dispose: function() { this._reset(); }, _reset: function() { this._json = ""; this._state = "find-snapshot-info"; this._snapshot = {}; }, close: function() { if (this._json) this._parseStringsArray(); }, buildSnapshot: function() { var result = new WebInspector.HeapSnapshot(this._snapshot); this._reset(); return result; }, _parseUintArray: function() { var index = 0; var char0 = "0".charCodeAt(0), char9 = "9".charCodeAt(0), closingBracket = "]".charCodeAt(0); var length = this._json.length; while (true) { while (index < length) { var code = this._json.charCodeAt(index); if (char0 <= code && code <= char9) break; else if (code === closingBracket) { this._json = this._json.slice(index + 1); return false; } ++index; } if (index === length) { this._json = ""; return true; } var nextNumber = 0; var startIndex = index; while (index < length) { var code = this._json.charCodeAt(index); if (char0 > code || code > char9) break; nextNumber *= 10; nextNumber += (code - char0); ++index; } if (index === length) { this._json = this._json.slice(startIndex); return true; } this._array[this._arrayIndex++] = nextNumber; } }, _parseStringsArray: function() { var closingBracketIndex = this._json.lastIndexOf("]"); if (closingBracketIndex === -1) throw new Error("Incomplete JSON"); this._json = this._json.slice(0, closingBracketIndex + 1); this._snapshot.strings = JSON.parse(this._json); }, write: function(chunk) { this._json += chunk; switch (this._state) { case "find-snapshot-info": { var snapshotToken = "\"snapshot\""; var snapshotTokenIndex = this._json.indexOf(snapshotToken); if (snapshotTokenIndex === -1) throw new Error("Snapshot token not found"); this._json = this._json.slice(snapshotTokenIndex + snapshotToken.length + 1); this._state = "parse-snapshot-info"; } case "parse-snapshot-info": { var closingBracketIndex = WebInspector.findBalancedCurlyBrackets(this._json); if (closingBracketIndex === -1) return; this._snapshot.snapshot = (JSON.parse(this._json.slice(0, closingBracketIndex))); this._json = this._json.slice(closingBracketIndex); this._state = "find-nodes"; } case "find-nodes": { var nodesToken = "\"nodes\""; var nodesTokenIndex = this._json.indexOf(nodesToken); if (nodesTokenIndex === -1) return; var bracketIndex = this._json.indexOf("[", nodesTokenIndex); if (bracketIndex === -1) return; this._json = this._json.slice(bracketIndex + 1); var node_fields_count = this._snapshot.snapshot.meta.node_fields.length; var nodes_length = this._snapshot.snapshot.node_count * node_fields_count; this._array = new Uint32Array(nodes_length); this._arrayIndex = 0; this._state = "parse-nodes"; } case "parse-nodes": { if (this._parseUintArray()) return; this._snapshot.nodes = this._array; this._state = "find-edges"; this._array = null; } case "find-edges": { var edgesToken = "\"edges\""; var edgesTokenIndex = this._json.indexOf(edgesToken); if (edgesTokenIndex === -1) return; var bracketIndex = this._json.indexOf("[", edgesTokenIndex); if (bracketIndex === -1) return; this._json = this._json.slice(bracketIndex + 1); var edge_fields_count = this._snapshot.snapshot.meta.edge_fields.length; var edges_length = this._snapshot.snapshot.edge_count * edge_fields_count; this._array = new Uint32Array(edges_length); this._arrayIndex = 0; this._state = "parse-edges"; } case "parse-edges": { if (this._parseUintArray()) return; this._snapshot.edges = this._array; this._array = null; this._state = "find-strings"; } case "find-strings": { var stringsToken = "\"strings\""; var stringsTokenIndex = this._json.indexOf(stringsToken); if (stringsTokenIndex === -1) return; var bracketIndex = this._json.indexOf("[", stringsTokenIndex); if (bracketIndex === -1) return; this._json = this._json.slice(bracketIndex); this._state = "accumulate-strings"; break; } case "accumulate-strings": break; } } }; ; WebInspector.HeapSnapshotWorkerWrapper = function() { } WebInspector.HeapSnapshotWorkerWrapper.prototype = { postMessage: function(message) { }, terminate: function() { }, __proto__: WebInspector.Object.prototype } WebInspector.HeapSnapshotRealWorker = function() { this._worker = new Worker("HeapSnapshotWorker.js"); this._worker.addEventListener("message", this._messageReceived.bind(this), false); } WebInspector.HeapSnapshotRealWorker.prototype = { _messageReceived: function(event) { var message = event.data; if ("callId" in message) this.dispatchEventToListeners("message", message); else { if (message.object !== "console") { console.log(WebInspector.UIString("Worker asks to call a method '%s' on an unsupported object '%s'.", message.method, message.object)); return; } if (message.method !== "log" && message.method !== "info" && message.method !== "error") { console.log(WebInspector.UIString("Worker asks to call an unsupported method '%s' on the console object.", message.method)); return; } console[message.method].apply(window[message.object], message.arguments); } }, postMessage: function(message) { this._worker.postMessage(message); }, terminate: function() { this._worker.terminate(); }, __proto__: WebInspector.HeapSnapshotWorkerWrapper.prototype } WebInspector.AsyncTaskQueue = function() { this._queue = []; this._isTimerSheduled = false; } WebInspector.AsyncTaskQueue.prototype = { addTask: function(task) { this._queue.push(task); this._scheduleTimer(); }, _onTimeout: function() { this._isTimerSheduled = false; var queue = this._queue; this._queue = []; for (var i = 0; i < queue.length; i++) { try { queue[i](); } catch (e) { console.error("Exception while running task: " + e.stack); } } this._scheduleTimer(); }, _scheduleTimer: function() { if (this._queue.length && !this._isTimerSheduled) { setTimeout(this._onTimeout.bind(this), 0); this._isTimerSheduled = true; } } } WebInspector.HeapSnapshotFakeWorker = function() { this._dispatcher = new WebInspector.HeapSnapshotWorkerDispatcher(window, this._postMessageFromWorker.bind(this)); this._asyncTaskQueue = new WebInspector.AsyncTaskQueue(); } WebInspector.HeapSnapshotFakeWorker.prototype = { postMessage: function(message) { function dispatch() { if (this._dispatcher) this._dispatcher.dispatchMessage({data: message}); } this._asyncTaskQueue.addTask(dispatch.bind(this)); }, terminate: function() { this._dispatcher = null; }, _postMessageFromWorker: function(message) { function send() { this.dispatchEventToListeners("message", message); } this._asyncTaskQueue.addTask(send.bind(this)); }, __proto__: WebInspector.HeapSnapshotWorkerWrapper.prototype } WebInspector.HeapSnapshotWorker = function() { this._nextObjectId = 1; this._nextCallId = 1; this._callbacks = []; this._previousCallbacks = []; this._worker = typeof InspectorTest === "undefined" ? new WebInspector.HeapSnapshotRealWorker() : new WebInspector.HeapSnapshotFakeWorker(); this._worker.addEventListener("message", this._messageReceived, this); } WebInspector.HeapSnapshotWorker.prototype = { createObject: function(constructorName) { var proxyConstructorFunction = this._findFunction(constructorName + "Proxy"); var objectId = this._nextObjectId++; var proxy = new proxyConstructorFunction(this, objectId); this._postMessage({callId: this._nextCallId++, disposition: "create", objectId: objectId, methodName: constructorName}); return proxy; }, dispose: function() { this._worker.terminate(); if (this._interval) clearInterval(this._interval); }, disposeObject: function(objectId) { this._postMessage({callId: this._nextCallId++, disposition: "dispose", objectId: objectId}); }, callGetter: function(callback, objectId, getterName) { var callId = this._nextCallId++; this._callbacks[callId] = callback; this._postMessage({callId: callId, disposition: "getter", objectId: objectId, methodName: getterName}); }, callFactoryMethod: function(callback, objectId, methodName, proxyConstructorName) { var callId = this._nextCallId++; var methodArguments = Array.prototype.slice.call(arguments, 4); var newObjectId = this._nextObjectId++; var proxyConstructorFunction = this._findFunction(proxyConstructorName); if (callback) { function wrapCallback(remoteResult) { callback(remoteResult ? new proxyConstructorFunction(this, newObjectId) : null); } this._callbacks[callId] = wrapCallback.bind(this); this._postMessage({callId: callId, disposition: "factory", objectId: objectId, methodName: methodName, methodArguments: methodArguments, newObjectId: newObjectId}); return null; } else { this._postMessage({callId: callId, disposition: "factory", objectId: objectId, methodName: methodName, methodArguments: methodArguments, newObjectId: newObjectId}); return new proxyConstructorFunction(this, newObjectId); } }, callMethod: function(callback, objectId, methodName) { var callId = this._nextCallId++; var methodArguments = Array.prototype.slice.call(arguments, 3); if (callback) this._callbacks[callId] = callback; this._postMessage({callId: callId, disposition: "method", objectId: objectId, methodName: methodName, methodArguments: methodArguments}); }, startCheckingForLongRunningCalls: function() { if (this._interval) return; this._checkLongRunningCalls(); this._interval = setInterval(this._checkLongRunningCalls.bind(this), 300); }, _checkLongRunningCalls: function() { for (var callId in this._previousCallbacks) if (!(callId in this._callbacks)) delete this._previousCallbacks[callId]; var hasLongRunningCalls = false; for (callId in this._previousCallbacks) { hasLongRunningCalls = true; break; } this.dispatchEventToListeners("wait", hasLongRunningCalls); for (callId in this._callbacks) this._previousCallbacks[callId] = true; }, _findFunction: function(name) { var path = name.split("."); var result = window; for (var i = 0; i < path.length; ++i) result = result[path[i]]; return result; }, _messageReceived: function(event) { var data = event.data; if (event.data.error) { if (event.data.errorMethodName) WebInspector.log(WebInspector.UIString("An error happened when a call for method '%s' was requested", event.data.errorMethodName)); WebInspector.log(event.data.errorCallStack); delete this._callbacks[data.callId]; return; } if (!this._callbacks[data.callId]) return; var callback = this._callbacks[data.callId]; delete this._callbacks[data.callId]; callback(data.result); }, _postMessage: function(message) { this._worker.postMessage(message); }, __proto__: WebInspector.Object.prototype } WebInspector.HeapSnapshotProxyObject = function(worker, objectId) { this._worker = worker; this._objectId = objectId; } WebInspector.HeapSnapshotProxyObject.prototype = { _callWorker: function(workerMethodName, args) { args.splice(1, 0, this._objectId); return this._worker[workerMethodName].apply(this._worker, args); }, dispose: function() { this._worker.disposeObject(this._objectId); }, disposeWorker: function() { this._worker.dispose(); }, callFactoryMethod: function(callback, methodName, proxyConstructorName, var_args) { return this._callWorker("callFactoryMethod", Array.prototype.slice.call(arguments, 0)); }, callGetter: function(callback, getterName) { return this._callWorker("callGetter", Array.prototype.slice.call(arguments, 0)); }, callMethod: function(callback, methodName, var_args) { return this._callWorker("callMethod", Array.prototype.slice.call(arguments, 0)); }, get worker() { return this._worker; } }; WebInspector.HeapSnapshotLoaderProxy = function(worker, objectId) { WebInspector.HeapSnapshotProxyObject.call(this, worker, objectId); this._pendingSnapshotConsumers = []; } WebInspector.HeapSnapshotLoaderProxy.prototype = { addConsumer: function(callback) { this._pendingSnapshotConsumers.push(callback); }, write: function(chunk, callback) { this.callMethod(callback, "write", chunk); }, close: function() { function buildSnapshot() { this.callFactoryMethod(updateStaticData.bind(this), "buildSnapshot", "WebInspector.HeapSnapshotProxy"); } function updateStaticData(snapshotProxy) { this.dispose(); snapshotProxy.updateStaticData(notifyPendingConsumers.bind(this)); } function notifyPendingConsumers(snapshotProxy) { for (var i = 0; i < this._pendingSnapshotConsumers.length; ++i) this._pendingSnapshotConsumers[i](snapshotProxy); this._pendingSnapshotConsumers = []; } this.callMethod(buildSnapshot.bind(this), "close"); }, __proto__: WebInspector.HeapSnapshotProxyObject.prototype } WebInspector.HeapSnapshotProxy = function(worker, objectId) { WebInspector.HeapSnapshotProxyObject.call(this, worker, objectId); } WebInspector.HeapSnapshotProxy.prototype = { aggregates: function(sortedIndexes, key, filter, callback) { this.callMethod(callback, "aggregates", sortedIndexes, key, filter); }, aggregatesForDiff: function(callback) { this.callMethod(callback, "aggregatesForDiff"); }, calculateSnapshotDiff: function(baseSnapshotId, baseSnapshotAggregates, callback) { this.callMethod(callback, "calculateSnapshotDiff", baseSnapshotId, baseSnapshotAggregates); }, nodeClassName: function(snapshotObjectId, callback) { this.callMethod(callback, "nodeClassName", snapshotObjectId); }, dominatorIdsForNode: function(nodeIndex, callback) { this.callMethod(callback, "dominatorIdsForNode", nodeIndex); }, createEdgesProvider: function(nodeIndex, filter) { return this.callFactoryMethod(null, "createEdgesProvider", "WebInspector.HeapSnapshotProviderProxy", nodeIndex, filter); }, createRetainingEdgesProvider: function(nodeIndex, filter) { return this.callFactoryMethod(null, "createRetainingEdgesProvider", "WebInspector.HeapSnapshotProviderProxy", nodeIndex, filter); }, createAddedNodesProvider: function(baseSnapshotId, className) { return this.callFactoryMethod(null, "createAddedNodesProvider", "WebInspector.HeapSnapshotProviderProxy", baseSnapshotId, className); }, createDeletedNodesProvider: function(nodeIndexes) { return this.callFactoryMethod(null, "createDeletedNodesProvider", "WebInspector.HeapSnapshotProviderProxy", nodeIndexes); }, createNodesProvider: function(filter) { return this.callFactoryMethod(null, "createNodesProvider", "WebInspector.HeapSnapshotProviderProxy", filter); }, createNodesProviderForClass: function(className, aggregatesKey) { return this.callFactoryMethod(null, "createNodesProviderForClass", "WebInspector.HeapSnapshotProviderProxy", className, aggregatesKey); }, createNodesProviderForDominator: function(nodeIndex) { return this.callFactoryMethod(null, "createNodesProviderForDominator", "WebInspector.HeapSnapshotProviderProxy", nodeIndex); }, dispose: function() { this.disposeWorker(); }, get nodeCount() { return this._staticData.nodeCount; }, get nodeFlags() { return this._staticData.nodeFlags; }, get rootNodeIndex() { return this._staticData.rootNodeIndex; }, updateStaticData: function(callback) { function dataReceived(staticData) { this._staticData = staticData; callback(this); } this.callMethod(dataReceived.bind(this), "updateStaticData"); }, get totalSize() { return this._staticData.totalSize; }, get uid() { return this._staticData.uid; }, __proto__: WebInspector.HeapSnapshotProxyObject.prototype } WebInspector.HeapSnapshotProviderProxy = function(worker, objectId) { WebInspector.HeapSnapshotProxyObject.call(this, worker, objectId); } WebInspector.HeapSnapshotProviderProxy.prototype = { nodePosition: function(snapshotObjectId, callback) { this.callMethod(callback, "nodePosition", snapshotObjectId); }, isEmpty: function(callback) { this.callMethod(callback, "isEmpty"); }, serializeItemsRange: function(startPosition, endPosition, callback) { this.callMethod(callback, "serializeItemsRange", startPosition, endPosition); }, sortAndRewind: function(comparator, callback) { this.callMethod(callback, "sortAndRewind", comparator); }, __proto__: WebInspector.HeapSnapshotProxyObject.prototype } ; WebInspector.HeapSnapshotView = function(parent, profile) { WebInspector.View.call(this); this.element.addStyleClass("heap-snapshot-view"); this.parent = parent; this.parent.addEventListener("profile added", this._updateBaseOptions, this); this.parent.addEventListener("profile added", this._updateFilterOptions, this); this.viewsContainer = document.createElement("div"); this.viewsContainer.addStyleClass("views-container"); this.element.appendChild(this.viewsContainer); this.containmentView = new WebInspector.View(); this.containmentView.element.addStyleClass("view"); this.containmentDataGrid = new WebInspector.HeapSnapshotContainmentDataGrid(); this.containmentDataGrid.element.addEventListener("mousedown", this._mouseDownInContentsGrid.bind(this), true); this.containmentDataGrid.show(this.containmentView.element); this.containmentDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._selectionChanged, this); this.constructorsView = new WebInspector.View(); this.constructorsView.element.addStyleClass("view"); this.constructorsView.element.appendChild(this._createToolbarWithClassNameFilter()); this.constructorsDataGrid = new WebInspector.HeapSnapshotConstructorsDataGrid(); this.constructorsDataGrid.element.addStyleClass("class-view-grid"); this.constructorsDataGrid.element.addEventListener("mousedown", this._mouseDownInContentsGrid.bind(this), true); this.constructorsDataGrid.show(this.constructorsView.element); this.constructorsDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._selectionChanged, this); this.diffView = new WebInspector.View(); this.diffView.element.addStyleClass("view"); this.diffView.element.appendChild(this._createToolbarWithClassNameFilter()); this.diffDataGrid = new WebInspector.HeapSnapshotDiffDataGrid(); this.diffDataGrid.element.addStyleClass("class-view-grid"); this.diffDataGrid.show(this.diffView.element); this.diffDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._selectionChanged, this); this.dominatorView = new WebInspector.View(); this.dominatorView.element.addStyleClass("view"); this.dominatorDataGrid = new WebInspector.HeapSnapshotDominatorsDataGrid(); this.dominatorDataGrid.element.addEventListener("mousedown", this._mouseDownInContentsGrid.bind(this), true); this.dominatorDataGrid.show(this.dominatorView.element); this.dominatorDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._selectionChanged, this); this.retainmentViewHeader = document.createElement("div"); this.retainmentViewHeader.addStyleClass("retainers-view-header"); WebInspector.installDragHandle(this.retainmentViewHeader, this._startRetainersHeaderDragging.bind(this), this._retainersHeaderDragging.bind(this), this._endRetainersHeaderDragging.bind(this), "row-resize"); var retainingPathsTitleDiv = document.createElement("div"); retainingPathsTitleDiv.className = "title"; var retainingPathsTitle = document.createElement("span"); retainingPathsTitle.textContent = WebInspector.UIString("Object's retaining tree"); retainingPathsTitleDiv.appendChild(retainingPathsTitle); this.retainmentViewHeader.appendChild(retainingPathsTitleDiv); this.element.appendChild(this.retainmentViewHeader); this.retainmentView = new WebInspector.View(); this.retainmentView.element.addStyleClass("view"); this.retainmentView.element.addStyleClass("retaining-paths-view"); this.retainmentDataGrid = new WebInspector.HeapSnapshotRetainmentDataGrid(); this.retainmentDataGrid.show(this.retainmentView.element); this.retainmentDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._inspectedObjectChanged, this); this.retainmentView.show(this.element); this.retainmentDataGrid.reset(); this.dataGrid = this.constructorsDataGrid; this.currentView = this.constructorsView; this.viewSelectElement = document.createElement("select"); this.viewSelectElement.className = "status-bar-item"; this.viewSelectElement.addEventListener("change", this._onSelectedViewChanged.bind(this), false); this.views = [{title: "Summary", view: this.constructorsView, grid: this.constructorsDataGrid}, {title: "Comparison", view: this.diffView, grid: this.diffDataGrid}, {title: "Containment", view: this.containmentView, grid: this.containmentDataGrid}, {title: "Dominators", view: this.dominatorView, grid: this.dominatorDataGrid}]; this.views.current = 0; for (var i = 0; i < this.views.length; ++i) { var view = this.views[i]; var option = document.createElement("option"); option.label = WebInspector.UIString(view.title); this.viewSelectElement.appendChild(option); } this._profileUid = profile.uid; this.baseSelectElement = document.createElement("select"); this.baseSelectElement.className = "status-bar-item"; this.baseSelectElement.addEventListener("change", this._changeBase.bind(this), false); this._updateBaseOptions(); this.filterSelectElement = document.createElement("select"); this.filterSelectElement.className = "status-bar-item"; this.filterSelectElement.addEventListener("change", this._changeFilter.bind(this), false); this._updateFilterOptions(); this.helpButton = new WebInspector.StatusBarButton("", "heap-snapshot-help-status-bar-item status-bar-item"); this.helpButton.addEventListener("click", this._helpClicked, this); this._popoverHelper = new WebInspector.ObjectPopoverHelper(this.element, this._getHoverAnchor.bind(this), this._resolveObjectForPopover.bind(this), undefined, true); this.profile.load(profileCallback.bind(this)); function profileCallback(heapSnapshotProxy) { var list = this._profiles(); var profileIndex; for (var i = 0; i < list.length; ++i) { if (list[i].uid === this._profileUid) { profileIndex = i; break; } } if (profileIndex > 0) this.baseSelectElement.selectedIndex = profileIndex - 1; else this.baseSelectElement.selectedIndex = profileIndex; this.dataGrid.setDataSource(heapSnapshotProxy); } } WebInspector.HeapSnapshotView.prototype = { dispose: function() { this.profile.dispose(); if (this.baseProfile) this.baseProfile.dispose(); this.containmentDataGrid.dispose(); this.constructorsDataGrid.dispose(); this.diffDataGrid.dispose(); this.dominatorDataGrid.dispose(); this.retainmentDataGrid.dispose(); }, get statusBarItems() { function appendArrowImage(element, hidden) { var span = document.createElement("span"); span.className = "status-bar-select-container" + (hidden ? " hidden" : ""); span.appendChild(element); return span; } return [appendArrowImage(this.viewSelectElement), appendArrowImage(this.baseSelectElement, true), appendArrowImage(this.filterSelectElement), this.helpButton.element]; }, get profile() { return this.parent.getProfile(WebInspector.HeapSnapshotProfileType.TypeId, this._profileUid); }, get baseProfile() { return this.parent.getProfile(WebInspector.HeapSnapshotProfileType.TypeId, this._baseProfileUid); }, wasShown: function() { this.profile.load(profileCallback1.bind(this)); function profileCallback1() { if (this.baseProfile) this.baseProfile.load(profileCallback2.bind(this)); else profileCallback2.call(this); } function profileCallback2() { this.currentView.show(this.viewsContainer); } }, willHide: function() { this._currentSearchResultIndex = -1; this._popoverHelper.hidePopover(); if (this.helpPopover && this.helpPopover.isShowing()) this.helpPopover.hide(); }, onResize: function() { var height = this.retainmentView.element.clientHeight; this._updateRetainmentViewHeight(height); }, searchCanceled: function() { if (this._searchResults) { for (var i = 0; i < this._searchResults.length; ++i) { var node = this._searchResults[i].node; delete node._searchMatched; node.refresh(); } } delete this._searchFinishedCallback; this._currentSearchResultIndex = -1; this._searchResults = []; }, performSearch: function(query, finishedCallback) { this.searchCanceled(); query = query.trim(); if (!query.length) return; if (this.currentView !== this.constructorsView && this.currentView !== this.diffView) return; this._searchFinishedCallback = finishedCallback; function matchesByName(gridNode) { return ("_name" in gridNode) && gridNode._name.hasSubstring(query, true); } function matchesById(gridNode) { return ("snapshotNodeId" in gridNode) && gridNode.snapshotNodeId === query; } var matchPredicate; if (query.charAt(0) !== "@") matchPredicate = matchesByName; else { query = parseInt(query.substring(1), 10); matchPredicate = matchesById; } function matchesQuery(gridNode) { delete gridNode._searchMatched; if (matchPredicate(gridNode)) { gridNode._searchMatched = true; gridNode.refresh(); return true; } return false; } var current = this.dataGrid.rootNode().children[0]; var depth = 0; var info = {}; const maxDepth = 1; while (current) { if (matchesQuery(current)) this._searchResults.push({ node: current }); current = current.traverseNextNode(false, null, (depth >= maxDepth), info); depth += info.depthChange; } finishedCallback(this, this._searchResults.length); }, jumpToFirstSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; this._currentSearchResultIndex = 0; this._jumpToSearchResult(this._currentSearchResultIndex); }, jumpToLastSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; this._currentSearchResultIndex = (this._searchResults.length - 1); this._jumpToSearchResult(this._currentSearchResultIndex); }, jumpToNextSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; if (++this._currentSearchResultIndex >= this._searchResults.length) this._currentSearchResultIndex = 0; this._jumpToSearchResult(this._currentSearchResultIndex); }, jumpToPreviousSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; if (--this._currentSearchResultIndex < 0) this._currentSearchResultIndex = (this._searchResults.length - 1); this._jumpToSearchResult(this._currentSearchResultIndex); }, showingFirstSearchResult: function() { return (this._currentSearchResultIndex === 0); }, showingLastSearchResult: function() { return (this._searchResults && this._currentSearchResultIndex === (this._searchResults.length - 1)); }, _jumpToSearchResult: function(index) { var searchResult = this._searchResults[index]; if (!searchResult) return; var node = searchResult.node; node.revealAndSelect(); }, refreshVisibleData: function() { var child = this.dataGrid.rootNode().children[0]; while (child) { child.refresh(); child = child.traverseNextNode(false, null, true); } }, _changeBase: function() { if (this._baseProfileUid === this._profiles()[this.baseSelectElement.selectedIndex].uid) return; this._baseProfileUid = this._profiles()[this.baseSelectElement.selectedIndex].uid; var dataGrid = (this.dataGrid); if (dataGrid.snapshot) this.baseProfile.load(dataGrid.setBaseDataSource.bind(dataGrid)); if (!this.currentQuery || !this._searchFinishedCallback || !this._searchResults) return; this._searchFinishedCallback(this, -this._searchResults.length); this.performSearch(this.currentQuery, this._searchFinishedCallback); }, _changeFilter: function() { var profileIndex = this.filterSelectElement.selectedIndex - 1; this.dataGrid.filterSelectIndexChanged(this._profiles(), profileIndex); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.HeapSnapshotFilterChanged, label: this.filterSelectElement[this.filterSelectElement.selectedIndex].label }); if (!this.currentQuery || !this._searchFinishedCallback || !this._searchResults) return; this._searchFinishedCallback(this, -this._searchResults.length); this.performSearch(this.currentQuery, this._searchFinishedCallback); }, _createToolbarWithClassNameFilter: function() { var toolbar = document.createElement("div"); toolbar.addStyleClass("class-view-toolbar"); var classNameFilter = document.createElement("input"); classNameFilter.addStyleClass("class-name-filter"); classNameFilter.setAttribute("placeholder", WebInspector.UIString("Class filter")); classNameFilter.addEventListener("keyup", this._changeNameFilter.bind(this, classNameFilter), false); toolbar.appendChild(classNameFilter); return toolbar; }, _changeNameFilter: function(classNameInputElement) { var filter = classNameInputElement.value; this.dataGrid.changeNameFilter(filter); }, _profiles: function() { return this.parent.getProfiles(WebInspector.HeapSnapshotProfileType.TypeId); }, processLoadedSnapshot: function(profile, snapshot) { profile.nodes = snapshot.nodes; profile.strings = snapshot.strings; var s = new WebInspector.HeapSnapshot(profile); profile.sidebarElement.subtitle = Number.bytesToString(s.totalSize); }, populateContextMenu: function(contextMenu, event) { this.dataGrid.populateContextMenu(this.parent, contextMenu, event); }, _selectionChanged: function(event) { var selectedNode = event.target.selectedNode; this._setRetainmentDataGridSource(selectedNode); this._inspectedObjectChanged(event); }, _inspectedObjectChanged: function(event) { var selectedNode = event.target.selectedNode; if (!this.profile.fromFile() && selectedNode instanceof WebInspector.HeapSnapshotGenericObjectNode) ConsoleAgent.addInspectedHeapObject(selectedNode.snapshotNodeId); }, _setRetainmentDataGridSource: function(nodeItem) { if (nodeItem && nodeItem.snapshotNodeIndex) this.retainmentDataGrid.setDataSource(nodeItem.isDeletedNode ? nodeItem.dataGrid.baseSnapshot : nodeItem.dataGrid.snapshot, nodeItem.snapshotNodeIndex); else this.retainmentDataGrid.reset(); }, _mouseDownInContentsGrid: function(event) { if (event.detail < 2) return; var cell = event.target.enclosingNodeOrSelfWithNodeName("td"); if (!cell || (!cell.hasStyleClass("count-column") && !cell.hasStyleClass("shallowSize-column") && !cell.hasStyleClass("retainedSize-column"))) return; event.consume(true); }, changeView: function(viewTitle, callback) { var viewIndex = null; for (var i = 0; i < this.views.length; ++i) if (this.views[i].title === viewTitle) { viewIndex = i; break; } if (this.views.current === viewIndex) { setTimeout(callback, 0); return; } function dataGridContentShown(event) { var dataGrid = event.data; dataGrid.removeEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown, dataGridContentShown, this); if (dataGrid === this.dataGrid) callback(); } this.views[viewIndex].grid.addEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown, dataGridContentShown, this); this.viewSelectElement.selectedIndex = viewIndex; this._changeView(viewIndex); }, _updateDataSourceAndView: function() { var dataGrid = this.dataGrid; if (dataGrid.snapshot) return; this.profile.load(didLoadSnapshot.bind(this)); function didLoadSnapshot(snapshotProxy) { if (this.dataGrid !== dataGrid) return; if (dataGrid.snapshot !== snapshotProxy) dataGrid.setDataSource(snapshotProxy); if (dataGrid === this.diffDataGrid) { if (!this._baseProfileUid) this._baseProfileUid = this._profiles()[this.baseSelectElement.selectedIndex].uid; this.baseProfile.load(didLoadBaseSnaphot.bind(this)); } } function didLoadBaseSnaphot(baseSnapshotProxy) { if (this.diffDataGrid.baseSnapshot !== baseSnapshotProxy) this.diffDataGrid.setBaseDataSource(baseSnapshotProxy); } }, _onSelectedViewChanged: function(event) { this._changeView(event.target.selectedIndex); }, _updateSelectorsVisibility: function() { if (this.currentView === this.diffView) this.baseSelectElement.parentElement.removeStyleClass("hidden"); else this.baseSelectElement.parentElement.addStyleClass("hidden"); if (this.currentView === this.constructorsView) this.filterSelectElement.parentElement.removeStyleClass("hidden"); else this.filterSelectElement.parentElement.addStyleClass("hidden"); }, _changeView: function(selectedIndex) { if (selectedIndex === this.views.current) return; this.views.current = selectedIndex; this.currentView.detach(); var view = this.views[this.views.current]; this.currentView = view.view; this.dataGrid = view.grid; this.currentView.show(this.viewsContainer); this.refreshVisibleData(); this.dataGrid.updateWidths(); this._updateSelectorsVisibility(); this._updateDataSourceAndView(); if (!this.currentQuery || !this._searchFinishedCallback || !this._searchResults) return; this._searchFinishedCallback(this, -this._searchResults.length); this.performSearch(this.currentQuery, this._searchFinishedCallback); }, _getHoverAnchor: function(target) { var span = target.enclosingNodeOrSelfWithNodeName("span"); if (!span) return; var row = target.enclosingNodeOrSelfWithNodeName("tr"); if (!row) return; span.node = row._dataGridNode; return span; }, _resolveObjectForPopover: function(element, showCallback, objectGroupName) { if (this.profile.fromFile()) return; element.node.queryObjectContent(showCallback, objectGroupName); }, _helpClicked: function(event) { if (!this._helpPopoverContentElement) { var refTypes = ["a:", "console-formatted-name", WebInspector.UIString("property"), "0:", "console-formatted-name", WebInspector.UIString("element"), "a:", "console-formatted-number", WebInspector.UIString("context var"), "a:", "console-formatted-null", WebInspector.UIString("system prop")]; var objTypes = [" a ", "console-formatted-object", "Object", "\"a\"", "console-formatted-string", "String", "/a/", "console-formatted-string", "RegExp", "a()", "console-formatted-function", "Function", "a[]", "console-formatted-object", "Array", "num", "console-formatted-number", "Number", " a ", "console-formatted-null", "System"]; var contentElement = document.createElement("table"); contentElement.className = "heap-snapshot-help"; var headerRow = document.createElement("tr"); var propsHeader = document.createElement("th"); propsHeader.textContent = WebInspector.UIString("Property types:"); headerRow.appendChild(propsHeader); var objsHeader = document.createElement("th"); objsHeader.textContent = WebInspector.UIString("Object types:"); headerRow.appendChild(objsHeader); contentElement.appendChild(headerRow); function appendHelp(help, index, cell) { var div = document.createElement("div"); div.className = "source-code event-properties"; var name = document.createElement("span"); name.textContent = help[index]; name.className = help[index + 1]; div.appendChild(name); var desc = document.createElement("span"); desc.textContent = " " + help[index + 2]; div.appendChild(desc); cell.appendChild(div); } var len = Math.max(refTypes.length, objTypes.length); for (var i = 0; i < len; i += 3) { var row = document.createElement("tr"); var refCell = document.createElement("td"); if (refTypes[i]) appendHelp(refTypes, i, refCell); row.appendChild(refCell); var objCell = document.createElement("td"); if (objTypes[i]) appendHelp(objTypes, i, objCell); row.appendChild(objCell); contentElement.appendChild(row); } this._helpPopoverContentElement = contentElement; this.helpPopover = new WebInspector.Popover(); } if (this.helpPopover.isShowing()) this.helpPopover.hide(); else this.helpPopover.show(this._helpPopoverContentElement, this.helpButton.element); }, _startRetainersHeaderDragging: function(event) { if (!this.isShowing()) return false; this._previousDragPosition = event.pageY; return true; }, _retainersHeaderDragging: function(event) { var height = this.retainmentView.element.clientHeight; height += this._previousDragPosition - event.pageY; this._previousDragPosition = event.pageY; this._updateRetainmentViewHeight(height); event.consume(true); }, _endRetainersHeaderDragging: function(event) { delete this._previousDragPosition; event.consume(); }, _updateRetainmentViewHeight: function(height) { height = Number.constrain(height, Preferences.minConsoleHeight, this.element.clientHeight - Preferences.minConsoleHeight); this.viewsContainer.style.bottom = (height + this.retainmentViewHeader.clientHeight) + "px"; this.retainmentView.element.style.height = height + "px"; this.retainmentViewHeader.style.bottom = height + "px"; }, _updateBaseOptions: function() { var list = this._profiles(); if (this.baseSelectElement.length === list.length) return; for (var i = this.baseSelectElement.length, n = list.length; i < n; ++i) { var baseOption = document.createElement("option"); var title = list[i].title; if (!title.indexOf(UserInitiatedProfileName)) title = WebInspector.UIString("Snapshot %d", title.substring(UserInitiatedProfileName.length + 1)); baseOption.label = title; this.baseSelectElement.appendChild(baseOption); } }, _updateFilterOptions: function() { var list = this._profiles(); if (this.filterSelectElement.length - 1 === list.length) return; if (!this.filterSelectElement.length) { var filterOption = document.createElement("option"); filterOption.label = WebInspector.UIString("All objects"); this.filterSelectElement.appendChild(filterOption); } if (this.profile.fromFile()) return; for (var i = this.filterSelectElement.length - 1, n = list.length; i < n; ++i) { var profile = list[i]; var filterOption = document.createElement("option"); var title = list[i].title; if (!title.indexOf(UserInitiatedProfileName)) { if (!i) title = WebInspector.UIString("Objects allocated before Snapshot %d", title.substring(UserInitiatedProfileName.length + 1)); else title = WebInspector.UIString("Objects allocated between Snapshots %d and %d", title.substring(UserInitiatedProfileName.length + 1) - 1, title.substring(UserInitiatedProfileName.length + 1)); } filterOption.label = title; this.filterSelectElement.appendChild(filterOption); } }, __proto__: WebInspector.View.prototype } WebInspector.HeapSnapshotProfileType = function() { WebInspector.ProfileType.call(this, WebInspector.HeapSnapshotProfileType.TypeId, WebInspector.UIString("Take Heap Snapshot")); } WebInspector.HeapSnapshotProfileType.TypeId = "HEAP"; WebInspector.HeapSnapshotProfileType.prototype = { get buttonTooltip() { return WebInspector.UIString("Take heap snapshot."); }, buttonClicked: function(profilesPanel) { profilesPanel.takeHeapSnapshot(); return false; }, get treeItemTitle() { return WebInspector.UIString("HEAP SNAPSHOTS"); }, get description() { return WebInspector.UIString("Heap snapshot profiles show memory distribution among your page's JavaScript objects and related DOM nodes."); }, createTemporaryProfile: function(title) { title = title || WebInspector.UIString("Snapshotting\u2026"); return new WebInspector.HeapProfileHeader(this, title); }, createProfile: function(profile) { return new WebInspector.HeapProfileHeader(this, profile.title, profile.uid, profile.maxJSObjectId || 0); }, __proto__: WebInspector.ProfileType.prototype } WebInspector.HeapProfileHeader = function(type, title, uid, maxJSObjectId) { WebInspector.ProfileHeader.call(this, type, title, uid); this.maxJSObjectId = maxJSObjectId; this._receiver = null; this._snapshotProxy = null; this._totalNumberOfChunks = 0; } WebInspector.HeapProfileHeader.prototype = { createSidebarTreeElement: function() { return new WebInspector.ProfileSidebarTreeElement(this, WebInspector.UIString("Snapshot %d"), "heap-snapshot-sidebar-tree-item"); }, createView: function(profilesPanel) { return new WebInspector.HeapSnapshotView(profilesPanel, this); }, snapshotProxy: function() { return this._snapshotProxy; }, load: function(callback) { if (this._snapshotProxy) { callback(this._snapshotProxy); return; } this._numberOfChunks = 0; this._savedChunks = 0; this._savingToFile = false; if (!this._receiver) { this._setupWorker(); this.sidebarElement.subtitle = WebInspector.UIString("Loading\u2026"); this.sidebarElement.wait = true; ProfilerAgent.getProfile(this.profileType().id, this.uid); } var loaderProxy = (this._receiver); loaderProxy.addConsumer(callback); }, _setupWorker: function() { function setProfileWait(event) { this.sidebarElement.wait = event.data; } var worker = new WebInspector.HeapSnapshotWorker(); worker.addEventListener("wait", setProfileWait, this); var loaderProxy = worker.createObject("WebInspector.HeapSnapshotLoader"); loaderProxy.addConsumer(this._snapshotReceived.bind(this)); this._receiver = loaderProxy; }, dispose: function() { if (this._receiver) this._receiver.close(); else if (this._snapshotProxy) this._snapshotProxy.dispose(); }, _updateTransferProgress: function(value, maxValue) { var percentValue = ((maxValue ? (value / maxValue) : 0) * 100).toFixed(2); if (this._savingToFile) this.sidebarElement.subtitle = WebInspector.UIString("Saving\u2026 %d\%", percentValue); else this.sidebarElement.subtitle = WebInspector.UIString("Loading\u2026 %d\%", percentValue); }, _updateSnapshotStatus: function() { this.sidebarElement.subtitle = Number.bytesToString(this._snapshotProxy.totalSize); this.sidebarElement.wait = false; }, transferChunk: function(chunk) { ++this._numberOfChunks; this._receiver.write(chunk, callback.bind(this)); function callback() { this._updateTransferProgress(++this._savedChunks, this._totalNumberOfChunks); if (this._totalNumberOfChunks === this._savedChunks) { if (this._savingToFile) this._updateSnapshotStatus(); else this.sidebarElement.subtitle = WebInspector.UIString("Parsing\u2026"); this._receiver.close(); } } }, _snapshotReceived: function(snapshotProxy) { this._receiver = null; if (snapshotProxy) this._snapshotProxy = snapshotProxy; this._updateSnapshotStatus(); var worker = (this._snapshotProxy.worker); this.isTemporary = false; worker.startCheckingForLongRunningCalls(); }, finishHeapSnapshot: function() { this._totalNumberOfChunks = this._numberOfChunks; }, canSaveToFile: function() { return !this.fromFile() && !!this._snapshotProxy && !this._receiver; }, saveToFile: function() { this._numberOfChunks = 0; var fileOutputStream = new WebInspector.FileOutputStream(); function onOpen() { this._receiver = fileOutputStream; this._savedChunks = 0; this._updateTransferProgress(0, this._totalNumberOfChunks); ProfilerAgent.getProfile(this.profileType().id, this.uid); } this._savingToFile = true; this._fileName = this._fileName || "Heap-" + new Date().toISO8601Compact() + ".heapsnapshot"; fileOutputStream.open(this._fileName, onOpen.bind(this)); }, canLoadFromFile: function() { return false; }, loadFromFile: function(file) { this.title = file.name; this.sidebarElement.subtitle = WebInspector.UIString("Loading\u2026"); this.sidebarElement.wait = true; this._setupWorker(); this._numberOfChunks = 0; this._savingToFile = false; var delegate = new WebInspector.HeapSnapshotLoadFromFileDelegate(this); var fileReader = this._createFileReader(file, delegate); fileReader.start(this._receiver); }, _createFileReader: function(file, delegate) { return new WebInspector.ChunkedFileReader(file, 10000000, delegate); }, __proto__: WebInspector.ProfileHeader.prototype } WebInspector.HeapSnapshotLoadFromFileDelegate = function(snapshotHeader) { this._snapshotHeader = snapshotHeader; } WebInspector.HeapSnapshotLoadFromFileDelegate.prototype = { onTransferStarted: function() { }, onChunkTransferred: function(reader) { this._snapshotHeader._updateTransferProgress(reader.loadedSize(), reader.fileSize()); }, onTransferFinished: function() { this._snapshotHeader.finishHeapSnapshot(); }, onError: function (reader, e) { switch(e.target.error.code) { case e.target.error.NOT_FOUND_ERR: this._snapshotHeader.sidebarElement.subtitle = WebInspector.UIString("'%s' not found.", reader.fileName()); break; case e.target.error.NOT_READABLE_ERR: this._snapshotHeader.sidebarElement.subtitle = WebInspector.UIString("'%s' is not readable", reader.fileName()); break; case e.target.error.ABORT_ERR: break; default: this._snapshotHeader.sidebarElement.subtitle = WebInspector.UIString("'%s' error %d", reader.fileName(), e.target.error.code); } } } ; WebInspector.HeapSnapshotWorkerDispatcher = function(globalObject, postMessage) { this._objects = []; this._global = globalObject; this._postMessage = postMessage; } WebInspector.HeapSnapshotWorkerDispatcher.prototype = { _findFunction: function(name) { var path = name.split("."); var result = this._global; for (var i = 0; i < path.length; ++i) result = result[path[i]]; return result; }, dispatchMessage: function(event) { var data = event.data; var response = {callId: data.callId}; try { switch (data.disposition) { case "create": { var constructorFunction = this._findFunction(data.methodName); this._objects[data.objectId] = new constructorFunction(); break; } case "dispose": { delete this._objects[data.objectId]; break; } case "getter": { var object = this._objects[data.objectId]; var result = object[data.methodName]; response.result = result; break; } case "factory": { var object = this._objects[data.objectId]; var result = object[data.methodName].apply(object, data.methodArguments); if (result) this._objects[data.newObjectId] = result; response.result = !!result; break; } case "method": { var object = this._objects[data.objectId]; response.result = object[data.methodName].apply(object, data.methodArguments); break; } } } catch (e) { response.error = e.toString(); response.errorCallStack = e.stack; if (data.methodName) response.errorMethodName = data.methodName; } this._postMessage(response); } }; ; WebInspector.NativeHeapGraph = function(rawGraph) { this._rawGraph = rawGraph; this._nodeFieldCount = 5; this._nodeTypeOffset = 0; this._nodeSizeOffset = 1; this._nodeClassNameOffset = 2; this._nodeNameOffset = 3; this._nodeEdgeCountOffset = 4; this._nodeFirstEdgeOffset = this._nodeEdgeCountOffset; this._edgeFieldCount = 3; this._edgeTypeOffset = 0; this._edgeTargetOffset = 1; this._edgeNameOffset = 2; this._nodeCount = rawGraph.nodes.length / this._nodeFieldCount; this._nodes = rawGraph.nodes; this._edges = rawGraph.edges; this._strings = rawGraph.strings; this._calculateNodeEdgeIndexes(); } WebInspector.NativeHeapGraph.prototype = { rootNodes: function() { var nodeHasIncomingEdges = new Uint8Array(this._nodeCount); var edges = this._edges; var edgesLength = edges.length; var edgeFieldCount = this._edgeFieldCount; var nodeFieldCount = this._nodeFieldCount; for (var i = this._edgeTargetOffset; i < edgesLength; i += edgeFieldCount) { var targetIndex = edges[i]; nodeHasIncomingEdges[targetIndex] = 1; } var roots = []; var nodeCount = nodeHasIncomingEdges.length; for (var i = 0; i < nodeCount; i++) { if (!nodeHasIncomingEdges[i]) roots.push(new WebInspector.NativeHeapGraph.Node(this, i * nodeFieldCount)); } return roots; }, _calculateNodeEdgeIndexes: function() { var nodes = this._nodes; var nodeFieldCount = this._nodeFieldCount; var nodeLength = nodes.length; var firstEdgeIndex = 0; for (var i = this._nodeEdgeCountOffset; i < nodeLength; i += nodeFieldCount) { var count = nodes[i]; nodes[i] = firstEdgeIndex; firstEdgeIndex += count; } this._addDummyNode(); }, _addDummyNode: function() { var firstEdgePosition = this._nodes.length + this._nodeFirstEdgeOffset; for (var i = 0; i < this._nodeFieldCount; i++) this._nodes.push(0); this._nodes[firstEdgePosition] = this._edges.length; } } WebInspector.NativeHeapGraph.Edge = function(graph, position) { this._graph = graph; this._position = position; } WebInspector.NativeHeapGraph.Edge.prototype = { type: function() { return this._getStringField(this._graph._edgeTypeOffset); }, name: function() { return this._getStringField(this._graph._edgeNameOffset); }, target: function() { var edges = this._graph._edges; var targetPosition = edges[this._position + this._graph._edgeTargetOffset] * this._graph._nodeFieldCount; return new WebInspector.NativeHeapGraph.Node(this._graph, targetPosition); }, _getStringField: function(offset) { var typeIndex = this._graph._edges[this._position + offset]; return this._graph._rawGraph.strings[typeIndex]; }, toString: function() { return "Edge#" + this._position + " -" + this.name() + "-> " + this.target(); } } WebInspector.NativeHeapGraph.Node = function(graph, position) { this._graph = graph; this._position = position; } WebInspector.NativeHeapGraph.Node.prototype = { id: function() { return this._position / this._graph._nodeFieldCount; }, type: function() { return this._getStringField(this._graph._nodeTypeOffset); }, size: function() { return this._graph._nodes[this._position + this._graph._nodeSizeOffset]; }, className: function() { return this._getStringField(this._graph._nodeClassNameOffset); }, name: function() { return this._getStringField(this._graph._nodeNameOffset); }, hasReferencedNodes: function() { return this._afterLastEdgePosition() > this._firstEdgePoistion(); }, referencedNodes: function() { var edges = this._graph._edges; var nodes = this._graph._nodes; var edgeFieldCount = this._graph._edgeFieldCount; var nodeFieldCount = this._graph._nodeFieldCount; var firstEdgePosition = this._firstEdgePoistion(); var afterLastEdgePosition = this._afterLastEdgePosition(); var result = []; for (var i = firstEdgePosition + this._graph._edgeTargetOffset; i < afterLastEdgePosition; i += edgeFieldCount) result.push(new WebInspector.NativeHeapGraph.Node(this._graph, edges[i] * nodeFieldCount)); return result; }, outgoingEdges: function() { var edges = this._graph._edges; var edgeFieldCount = this._graph._edgeFieldCount; var firstEdgePosition = this._firstEdgePoistion(); var afterLastEdgePosition = this._afterLastEdgePosition(); var result = []; for (var i = firstEdgePosition; i < afterLastEdgePosition; i += edgeFieldCount) result.push(new WebInspector.NativeHeapGraph.Edge(this._graph, i)); return result; }, targetOfEdge: function(edgeName) { return this.targetsOfAllEdges(edgeName)[0]; }, targetsOfAllEdges: function(edgeName) { var edges = this._graph._edges; var edgeFieldCount = this._graph._edgeFieldCount; var firstEdgePosition = this._firstEdgePoistion(); var afterLastEdgePosition = this._afterLastEdgePosition(); var edge = new WebInspector.NativeHeapGraph.Edge(this._graph, firstEdgePosition) var result = []; for (var i = firstEdgePosition; i < afterLastEdgePosition; i += edgeFieldCount) { edge._position = i; if (edge.name() === edgeName) result.push(edge.target()); } return result; }, _firstEdgePoistion: function() { return this._graph._nodes[this._position + this._graph._nodeFirstEdgeOffset] * this._graph._edgeFieldCount; }, _afterLastEdgePosition: function() { return this._graph._nodes[this._position + this._graph._nodeFieldCount + this._graph._nodeFirstEdgeOffset] * this._graph._edgeFieldCount; }, _getStringField: function(offset) { var typeIndex = this._graph._nodes[this._position + offset]; return this._graph._rawGraph.strings[typeIndex]; }, toString: function() { return "Node#" + this.id() + " " + this.name() + "(" + this.className() + ")"; } } ; WebInspector.NativeMemorySnapshotView = function(profile) { WebInspector.View.call(this); this.registerRequiredCSS("nativeMemoryProfiler.css"); this.element.addStyleClass("native-snapshot-view"); this._containmentDataGrid = new WebInspector.NativeSnapshotDataGrid(profile); this._containmentDataGrid.show(this.element); this._heapGraphDataGrid = new WebInspector.NativeHeapGraphDataGrid(profile._graph); this._viewSelectElement = document.createElement("select"); this._viewSelectElement.className = "status-bar-item"; this._viewSelectElement.addEventListener("change", this._onSelectedViewChanged.bind(this), false); this._views = [{title: "Aggregated", view: this._containmentDataGrid}, {title: "Graph", view: this._heapGraphDataGrid}]; this._currentViewIndex = 0; for (var i = 0; i < this._views.length; ++i) { var view = this._views[i]; var option = document.createElement("option"); option.label = WebInspector.UIString(view.title); this._viewSelectElement.appendChild(option); } } WebInspector.NativeMemorySnapshotView.prototype = { _onSelectedViewChanged: function(event) { var index = event.target.selectedIndex; if (index === this._currentViewIndex) return; var currentView = this._views[this._currentViewIndex].view; currentView.detach(); this._currentViewIndex = index; var selectedView = this._views[index].view; selectedView.show(this.element); }, get statusBarItems() { var span = document.createElement("span"); span.className = "status-bar-select-container"; span.appendChild(this._viewSelectElement); return [span]; }, __proto__: WebInspector.View.prototype } WebInspector.NativeSnapshotDataGrid = function(profile) { var columns = { name: { title: WebInspector.UIString("Object"), width: "200px", disclosure: true, sortable: true }, size: { title: WebInspector.UIString("Size"), sortable: true, sort: "descending" }, }; WebInspector.DataGrid.call(this, columns); this._profile = profile; this._totalNode = new WebInspector.NativeSnapshotNode(profile._memoryBlock, profile._memoryBlock); if (WebInspector.settings.showNativeSnapshotUninstrumentedSize.get()) { this.setRootNode(new WebInspector.DataGridNode(null, true)); this.rootNode().appendChild(this._totalNode) this._totalNode.expand(); } else { this.setRootNode(this._totalNode); this._totalNode._populate(); } this.addEventListener("sorting changed", this.sortingChanged.bind(this), this); } WebInspector.NativeSnapshotDataGrid.prototype = { sortingChanged: function() { var expandedNodes = {}; this._totalNode._storeState(expandedNodes); this._totalNode.removeChildren(); this._totalNode._populate(); this._totalNode._shouldRefreshChildren = true; this._totalNode._restoreState(expandedNodes); }, _sortingFunction: function(nodeA, nodeB) { var sortColumnIdentifier = this.sortColumnIdentifier; var sortAscending = this.sortOrder === "ascending"; var field1 = nodeA[sortColumnIdentifier]; var field2 = nodeB[sortColumnIdentifier]; var result = field1 < field2 ? -1 : (field1 > field2 ? 1 : 0); if (!sortAscending) result = -result; return result; }, __proto__: WebInspector.DataGrid.prototype } WebInspector.NativeSnapshotNode = function(nodeData, rootMemoryBlock) { this._nodeData = nodeData; this._rootMemoryBlock = rootMemoryBlock; var viewProperties = WebInspector.MemoryBlockViewProperties._forMemoryBlock(nodeData); var data = { name: viewProperties._description, size: this._nodeData.size }; var hasChildren = !!nodeData.children && nodeData.children.length !== 0; WebInspector.DataGridNode.call(this, data, hasChildren); this.addEventListener("populate", this._populate, this); } WebInspector.NativeSnapshotNode.prototype = { createCell: function(columnIdentifier) { var cell = columnIdentifier === "size" ? this._createSizeCell(columnIdentifier) : WebInspector.DataGridNode.prototype.createCell.call(this, columnIdentifier); return cell; }, _storeState: function(expandedNodes) { if (!this.expanded) return; expandedNodes[this.uid()] = true; for (var i in this.children) this.children[i]._storeState(expandedNodes); }, _restoreState: function(expandedNodes) { if (!expandedNodes[this.uid()]) return; this.expand(); for (var i in this.children) this.children[i]._restoreState(expandedNodes); }, uid: function() { if (!this._uid) this._uid = (!this.parent || !this.parent.uid ? "" : this.parent.uid() || "") + "/" + this._nodeData.name; return this._uid; }, _createSizeCell: function(columnIdentifier) { var node = this; var viewProperties = null; var dimmed = false; while (!viewProperties || viewProperties._fillStyle === "inherit") { viewProperties = WebInspector.MemoryBlockViewProperties._forMemoryBlock(node._nodeData); if (viewProperties._fillStyle === "inherit") dimmed = true; node = node.parent; } var sizeKB = this._nodeData.size / 1024; var totalSize = this._rootMemoryBlock.size; var percentage = this._nodeData.size / totalSize * 100; var cell = document.createElement("td"); cell.className = columnIdentifier + "-column"; var textDiv = document.createElement("div"); textDiv.textContent = Number.withThousandsSeparator(sizeKB.toFixed(0)) + "\u2009" + WebInspector.UIString("KB"); textDiv.className = "size-text"; cell.appendChild(textDiv); var barDiv = document.createElement("div"); barDiv.className = "size-bar"; barDiv.style.width = percentage + "%"; barDiv.style.backgroundColor = viewProperties._fillStyle; var fillerDiv = document.createElement("div"); fillerDiv.className = "percent-text" barDiv.appendChild(fillerDiv); var percentDiv = document.createElement("div"); percentDiv.textContent = percentage.toFixed(1) + "%"; percentDiv.className = "percent-text" barDiv.appendChild(percentDiv); var barHolderDiv = document.createElement("div"); if (dimmed) barHolderDiv.className = "dimmed"; barHolderDiv.appendChild(barDiv); cell.appendChild(barHolderDiv); return cell; }, _populate: function() { this.removeEventListener("populate", this._populate, this); this._nodeData.children.sort(this.dataGrid._sortingFunction.bind(this.dataGrid)); for (var node in this._nodeData.children) { var nodeData = this._nodeData.children[node]; this._addChildrenFromGraph(nodeData); if (WebInspector.settings.showNativeSnapshotUninstrumentedSize.get() || nodeData.name !== "Other") this.appendChild(new WebInspector.NativeSnapshotNode(nodeData, this._rootMemoryBlock)); } }, _addChildrenFromGraph: function(memoryBlock) { if (memoryBlock.children) return; if (memoryBlock.name !== "Image" || this._nodeData.name !== "MemoryCache") return; var graph = this.dataGrid._profile._graph; var roots = graph.rootNodes(); var memoryCache; for (var i = 0; i < roots.length; i++) { var root = roots[i]; if (root.className() === "MemoryCache") { memoryCache = root; break; } } var edges = memoryCache.outgoingEdges(); var cachedImages = []; for (var i = 0; i < edges.length; i++) { var target = edges[i].target(); if (target.className() === "CachedImage") { var cachedImage = { name: target.name(), size: target.size(), children: [] }; cachedImages.push(cachedImage); var image = target.targetOfEdge("m_image"); if (image.className() === "BitmapImage") { var frames = image.targetsOfAllEdges("m_frame"); for (var j = 0; j < frames.length; j++) { var pixels = frames[j].targetOfEdge("pixels"); if (pixels) { cachedImage.size += pixels.size(); cachedImage.children.push({ name: "Bitmap pixels", size: pixels.size() }); } } } } } memoryBlock.children = cachedImages; }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.NativeHeapGraphDataGrid = function(nativeHeapGraph) { var columns = { id: { title: WebInspector.UIString("id"), width: "80px", disclosure: true, sortable: true }, type: { title: WebInspector.UIString("Type"), width: "200px", sortable: true }, className: { title: WebInspector.UIString("Class name"), width: "200px", sortable: true }, name: { title: WebInspector.UIString("Name"), width: "200px", sortable: true }, size: { title: WebInspector.UIString("Size"), sortable: true, sort: "descending" }, }; WebInspector.DataGrid.call(this, columns); this._nativeHeapGraph = nativeHeapGraph; this._root = new WebInspector.NativeHeapGraphDataGridRoot(this._nativeHeapGraph); this.setRootNode(this._root); this._root._populate(); } WebInspector.NativeHeapGraphDataGrid.prototype = { __proto__: WebInspector.DataGrid.prototype } WebInspector.NativeHeapGraphDataGridRoot = function(graph) { WebInspector.DataGridNode.call(this, { id: "root" }, true); this._graph = graph; this.addEventListener("populate", this._populate, this); } WebInspector.NativeHeapGraphDataGridRoot.prototype = { _populate: function() { this.removeEventListener("populate", this._populate, this); var roots = this._graph.rootNodes(); for (var i = 0; i < roots.length; i++) this.appendChild(new WebInspector.NativeHeapGraphDataGridNode(roots[i])); }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.NativeHeapGraphDataGridNode = function(node) { var data = { id: node.id(), size: node.size(), type: node.type(), className: node.className(), name: node.name(), }; WebInspector.DataGridNode.call(this, data, node.hasReferencedNodes()); this._node = node; this.addEventListener("populate", this._populate, this); } WebInspector.NativeHeapGraphDataGridNode.prototype = { _populate: function() { this.removeEventListener("populate", this._populate, this); var children = this._node.referencedNodes(); for (var i = 0; i < children.length; i++) this.appendChild(new WebInspector.NativeHeapGraphDataGridNode(children[i])); }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.NativeMemoryProfileType = function() { WebInspector.ProfileType.call(this, WebInspector.NativeMemoryProfileType.TypeId, WebInspector.UIString("Take Native Memory Snapshot")); this._nextProfileUid = 1; } WebInspector.NativeMemoryProfileType.TypeId = "NATIVE_MEMORY"; WebInspector.NativeMemoryProfileType.prototype = { get buttonTooltip() { return WebInspector.UIString("Take native memory snapshot."); }, buttonClicked: function(profilesPanel) { var profileHeader = new WebInspector.NativeMemoryProfileHeader(this, WebInspector.UIString("Snapshot %d", this._nextProfileUid), this._nextProfileUid); ++this._nextProfileUid; profileHeader.isTemporary = true; profilesPanel.addProfileHeader(profileHeader); function didReceiveMemorySnapshot(error, memoryBlock, graph) { if (memoryBlock.size && memoryBlock.children) { var knownSize = 0; for (var i = 0; i < memoryBlock.children.length; i++) { var size = memoryBlock.children[i].size; if (size) knownSize += size; } var otherSize = memoryBlock.size - knownSize; if (otherSize) { memoryBlock.children.push({ name: "Other", size: otherSize }); } } profileHeader._memoryBlock = memoryBlock; profileHeader._graph = new WebInspector.NativeHeapGraph(graph); profileHeader.isTemporary = false; profileHeader.sidebarElement.subtitle = Number.bytesToString( (memoryBlock.size)); } MemoryAgent.getProcessMemoryDistribution(true, didReceiveMemorySnapshot.bind(this)); return false; }, get treeItemTitle() { return WebInspector.UIString("MEMORY DISTRIBUTION"); }, get description() { return WebInspector.UIString("Native memory snapshot profiles show memory distribution among browser subsystems"); }, createTemporaryProfile: function(title) { title = title || WebInspector.UIString("Snapshotting\u2026"); return new WebInspector.NativeMemoryProfileHeader(this, title); }, createProfile: function(profile) { return new WebInspector.NativeMemoryProfileHeader(this, profile.title, -1); }, __proto__: WebInspector.ProfileType.prototype } WebInspector.NativeMemoryProfileHeader = function(type, title, uid) { WebInspector.ProfileHeader.call(this, type, title, uid); this._memoryBlock = null; } WebInspector.NativeMemoryProfileHeader.prototype = { createSidebarTreeElement: function() { return new WebInspector.ProfileSidebarTreeElement(this, WebInspector.UIString("Snapshot %d"), "heap-snapshot-sidebar-tree-item"); }, createView: function(profilesPanel) { return new WebInspector.NativeMemorySnapshotView(this); }, __proto__: WebInspector.ProfileHeader.prototype } WebInspector.MemoryBlockViewProperties = function(fillStyle, name, description) { this._fillStyle = fillStyle; this._name = name; this._description = description; } WebInspector.MemoryBlockViewProperties._standardBlocks = null; WebInspector.MemoryBlockViewProperties._initialize = function() { if (WebInspector.MemoryBlockViewProperties._standardBlocks) return; WebInspector.MemoryBlockViewProperties._standardBlocks = {}; function addBlock(fillStyle, name, description) { WebInspector.MemoryBlockViewProperties._standardBlocks[name] = new WebInspector.MemoryBlockViewProperties(fillStyle, name, WebInspector.UIString(description)); } addBlock("hsl( 0, 0%, 60%)", "ProcessPrivateMemory", "Total"); addBlock("hsl( 0, 0%, 80%)", "OwnersTypePlaceholder", "OwnersTypePlaceholder"); addBlock("hsl( 0, 0%, 60%)", "Other", "Other"); addBlock("hsl(220, 80%, 70%)", "Page", "Page structures"); addBlock("hsl(100, 60%, 50%)", "JSHeap", "JavaScript heap"); addBlock("hsl( 90, 40%, 80%)", "JSExternalResources", "JavaScript external resources"); addBlock("hsl( 90, 60%, 80%)", "JSExternalArrays", "JavaScript external arrays"); addBlock("hsl( 90, 60%, 80%)", "JSExternalStrings", "JavaScript external strings"); addBlock("hsl( 0, 80%, 60%)", "WebInspector", "Inspector data"); addBlock("hsl( 36, 90%, 50%)", "MemoryCache", "Memory cache resources"); addBlock("hsl( 40, 80%, 80%)", "GlyphCache", "Glyph cache resources"); addBlock("hsl( 35, 80%, 80%)", "DOMStorageCache", "DOM storage cache"); addBlock("hsl( 60, 80%, 60%)", "RenderTree", "Render tree"); addBlock("hsl( 20, 80%, 50%)", "MallocWaste", "Memory allocator waste"); } WebInspector.MemoryBlockViewProperties._forMemoryBlock = function(memoryBlock) { WebInspector.MemoryBlockViewProperties._initialize(); var result = WebInspector.MemoryBlockViewProperties._standardBlocks[memoryBlock.name]; if (result) return result; return new WebInspector.MemoryBlockViewProperties("inherit", memoryBlock.name, memoryBlock.name); } WebInspector.NativeMemoryBarChart = function() { WebInspector.View.call(this); this.registerRequiredCSS("nativeMemoryProfiler.css"); this._memorySnapshot = null; this.element = document.createElement("div"); this._table = this.element.createChild("table"); this._divs = {}; var row = this._table.insertRow(); this._totalDiv = row.insertCell().createChild("div"); this._totalDiv.addStyleClass("memory-bar-chart-total"); row.insertCell(); } WebInspector.NativeMemoryBarChart.prototype = { _updateStats: function() { function didReceiveMemorySnapshot(error, memoryBlock, graph) { if (memoryBlock.size && memoryBlock.children) { var knownSize = 0; for (var i = 0; i < memoryBlock.children.length; i++) { var size = memoryBlock.children[i].size; if (size) knownSize += size; } var otherSize = memoryBlock.size - knownSize; if (otherSize) { memoryBlock.children.push({ name: "Other", size: otherSize }); } } this._memorySnapshot = memoryBlock; this._updateView(); } MemoryAgent.getProcessMemoryDistribution(false, didReceiveMemorySnapshot.bind(this)); }, willHide: function() { clearInterval(this._timerId); }, wasShown: function() { this._timerId = setInterval(this._updateStats.bind(this), 1000); }, _updateView: function() { var memoryBlock = this._memorySnapshot; if (!memoryBlock) return; var MB = 1024 * 1024; var maxSize = 100 * MB; for (var i = 0; i < memoryBlock.children.length; ++i) maxSize = Math.max(maxSize, memoryBlock.children[i].size); var maxBarLength = 500; var barLengthSizeRatio = maxBarLength / maxSize; for (var i = memoryBlock.children.length - 1; i >= 0 ; --i) { var child = memoryBlock.children[i]; var name = child.name; var divs = this._divs[name]; if (!divs) { var row = this._table.insertRow(); var nameDiv = row.insertCell(-1).createChild("div"); var viewProperties = WebInspector.MemoryBlockViewProperties._forMemoryBlock(child); var title = viewProperties._description; nameDiv.textContent = title; nameDiv.addStyleClass("memory-bar-chart-name"); var barCell = row.insertCell(-1); var barDiv = barCell.createChild("div"); barDiv.addStyleClass("memory-bar-chart-bar"); viewProperties = WebInspector.MemoryBlockViewProperties._forMemoryBlock(child); barDiv.style.backgroundColor = viewProperties._fillStyle; var unusedDiv = barDiv.createChild("div"); unusedDiv.addStyleClass("memory-bar-chart-unused"); var percentDiv = barDiv.createChild("div"); percentDiv.addStyleClass("memory-bar-chart-percent"); var sizeDiv = barCell.createChild("div"); sizeDiv.addStyleClass("memory-bar-chart-size"); divs = this._divs[name] = { barDiv: barDiv, unusedDiv: unusedDiv, percentDiv: percentDiv, sizeDiv: sizeDiv }; } var unusedSize = 0; if (!!child.children) { var unusedName = name + ".Unused"; for (var j = 0; j < child.children.length; ++j) { if (child.children[j].name === unusedName) { unusedSize = child.children[j].size; break; } } } var unusedLength = unusedSize * barLengthSizeRatio; var barLength = child.size * barLengthSizeRatio; divs.barDiv.style.width = barLength + "px"; divs.unusedDiv.style.width = unusedLength + "px"; divs.percentDiv.textContent = barLength > 20 ? (child.size / memoryBlock.size * 100).toFixed(0) + "%" : ""; divs.sizeDiv.textContent = (child.size / MB).toFixed(1) + "\u2009MB"; } var memoryBlockViewProperties = WebInspector.MemoryBlockViewProperties._forMemoryBlock(memoryBlock); this._totalDiv.textContent = memoryBlockViewProperties._description + ": " + (memoryBlock.size / MB).toFixed(1) + "\u2009MB"; }, __proto__: WebInspector.View.prototype } ; WebInspector.ProfileLauncherView = function(profilesPanel) { WebInspector.View.call(this); this._panel = profilesPanel; this._profileRunning = false; this.element.addStyleClass("profile-launcher-view"); this.element.addStyleClass("panel-enabler-view"); this._contentElement = document.createElement("div"); this._contentElement.className = "profile-launcher-view-content"; this.element.appendChild(this._contentElement); var header = this._contentElement.createChild("h1"); header.textContent = WebInspector.UIString("Select profiling type"); this._profileTypeSelectorForm = this._contentElement.createChild("form"); if (WebInspector.experimentsSettings.liveNativeMemoryChart.isEnabled()) { this._nativeMemoryElement = document.createElement("div"); this._contentElement.appendChild(this._nativeMemoryElement); this._nativeMemoryLiveChart = new WebInspector.NativeMemoryBarChart(); this._nativeMemoryLiveChart.show(this._nativeMemoryElement); } this._contentElement.createChild("div", "flexible-space"); this._controlButton = this._contentElement.createChild("button", "control-profiling"); this._controlButton.addEventListener("click", this._controlButtonClicked.bind(this), false); this._updateControls(); } WebInspector.ProfileLauncherView.EventTypes = { ProfileTypeSelected: "profile-type-selected" } WebInspector.ProfileLauncherView.prototype = { addProfileType: function(profileType) { var checked = !this._profileTypeSelectorForm.children.length; var labelElement = this._profileTypeSelectorForm.createChild("label"); labelElement.textContent = profileType.name; var optionElement = document.createElement("input"); labelElement.insertBefore(optionElement, labelElement.firstChild); optionElement.type = "radio"; optionElement.name = "profile-type"; if (checked) { optionElement.checked = checked; this.dispatchEventToListeners(WebInspector.ProfileLauncherView.EventTypes.ProfileTypeSelected, profileType); } optionElement.addEventListener("change", this._profileTypeChanged.bind(this, profileType), false); var descriptionElement = labelElement.createChild("p"); descriptionElement.textContent = profileType.description; }, _controlButtonClicked: function() { this._panel.toggleRecordButton(); }, _updateControls: function() { if (this._isProfiling) { this._profileTypeSelectorForm.disabled = true; this._controlButton.addStyleClass("running"); this._controlButton.textContent = WebInspector.UIString("Stop"); } else { this._profileTypeSelectorForm.disabled = false; this._controlButton.removeStyleClass("running"); this._controlButton.textContent = WebInspector.UIString("Start"); } }, _profileTypeChanged: function(profileType, event) { this.dispatchEventToListeners(WebInspector.ProfileLauncherView.EventTypes.ProfileTypeSelected, profileType); }, profileStarted: function() { this._isProfiling = true; this._updateControls(); }, profileFinished: function() { this._isProfiling = false; this._updateControls(); }, __proto__: WebInspector.View.prototype } ; WebInspector.TopDownProfileDataGridNode = function( profileView, profileNode, owningTree) { var hasChildren = (profileNode.children && profileNode.children.length); WebInspector.ProfileDataGridNode.call(this, profileView, profileNode, owningTree, hasChildren); this._remainingChildren = profileNode.children; } WebInspector.TopDownProfileDataGridNode.prototype = { _sharedPopulate: function() { var children = this._remainingChildren; var childrenLength = children.length; for (var i = 0; i < childrenLength; ++i) this.appendChild(new WebInspector.TopDownProfileDataGridNode(this.profileView, children[i], this.tree)); this._remainingChildren = null; }, _exclude: function(aCallUID) { if (this._remainingChildren) this._populate(); this._save(); var children = this.children; var index = this.children.length; while (index--) children[index]._exclude(aCallUID); var child = this.childrenByCallUID[aCallUID]; if (child) this._merge(child, true); }, __proto__: WebInspector.ProfileDataGridNode.prototype } WebInspector.TopDownProfileDataGridTree = function( profileView, profileNode) { WebInspector.ProfileDataGridTree.call(this, profileView, profileNode); this._remainingChildren = profileNode.children; var any = this; var node = any; WebInspector.TopDownProfileDataGridNode.prototype._populate.call(node); } WebInspector.TopDownProfileDataGridTree.prototype = { focus: function( profileDataGrideNode) { if (!profileDataGrideNode) return; this._save(); profileDataGrideNode.savePosition(); this.children = [profileDataGrideNode]; this.totalTime = profileDataGrideNode.totalTime; }, exclude: function( profileDataGrideNode) { if (!profileDataGrideNode) return; this._save(); var excludedCallUID = profileDataGrideNode.callUID; var any = this; var node = any; WebInspector.TopDownProfileDataGridNode.prototype._exclude.call(node, excludedCallUID); if (this.lastComparator) this.sort(this.lastComparator, true); }, restore: function() { if (!this._savedChildren) return; this.children[0].restorePosition(); WebInspector.ProfileDataGridTree.prototype.restore.call(this); }, _merge: WebInspector.TopDownProfileDataGridNode.prototype._merge, _sharedPopulate: WebInspector.TopDownProfileDataGridNode.prototype._sharedPopulate, __proto__: WebInspector.ProfileDataGridTree.prototype } ; WebInspector.CanvasProfileView = function(profile) { WebInspector.View.call(this); this.registerRequiredCSS("canvasProfiler.css"); this._profile = profile; this._traceLogId = profile.traceLogId(); this.element.addStyleClass("canvas-profile-view"); this._linkifier = new WebInspector.Linkifier(); this._splitView = new WebInspector.SplitView(false, "canvasProfileViewSplitLocation", 300); var columns = { 0: {}, 1: {}, 2: {} }; columns[0].title = "#"; columns[0].sortable = true; columns[0].width = "5%"; columns[1].title = WebInspector.UIString("Call"); columns[1].sortable = true; columns[1].width = "75%"; columns[2].title = WebInspector.UIString("Location"); columns[2].sortable = true; columns[2].width = "20%"; this._logGrid = new WebInspector.DataGrid(columns); this._logGrid.element.addStyleClass("fill"); this._logGrid.show(this._splitView.secondElement()); this._logGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._replayTraceLog.bind(this)); var replayImageContainer = this._splitView.firstElement(); replayImageContainer.id = "canvas-replay-image-container"; this._replayImageElement = document.createElement("image"); this._replayImageElement.id = "canvas-replay-image"; replayImageContainer.appendChild(this._replayImageElement); this._debugInfoElement = document.createElement("div"); replayImageContainer.appendChild(this._debugInfoElement); this._splitView.show(this.element); this._enableWaitIcon(true); CanvasAgent.getTraceLog(this._traceLogId, 0, this._didReceiveTraceLog.bind(this)); } WebInspector.CanvasProfileView.prototype = { dispose: function() { this._linkifier.reset(); CanvasAgent.dropTraceLog(this._traceLogId); }, get statusBarItems() { return []; }, get profile() { return this._profile; }, elementsToRestoreScrollPositionsFor: function() { return [this._logGrid.scrollContainer]; }, _enableWaitIcon: function(enable) { function showWaitIcon() { this._replayImageElement.className = "wait"; this._debugInfoElement.textContent = ""; delete this._showWaitIconTimer; } if (enable && this._replayImageElement.src && !this._showWaitIconTimer) this._showWaitIconTimer = setTimeout(showWaitIcon.bind(this), 250); else { if (this._showWaitIconTimer) { clearTimeout(this._showWaitIconTimer); delete this._showWaitIconTimer; } this._replayImageElement.className = enable ? "wait" : ""; this._debugInfoElement.textContent = ""; } }, _replayTraceLog: function() { var callNode = this._logGrid.selectedNode; if (!callNode) return; var time = Date.now(); function didReplayTraceLog(error, dataURL) { this._enableWaitIcon(false); if (error) return; this._debugInfoElement.textContent = "Replay time: " + (Date.now() - time) + "ms"; this._replayImageElement.src = dataURL; } this._enableWaitIcon(true); CanvasAgent.replayTraceLog(this._traceLogId, callNode.index, didReplayTraceLog.bind(this)); }, _didReceiveTraceLog: function(error, traceLog) { this._enableWaitIcon(false); this._logGrid.rootNode().removeChildren(); if (error || !traceLog) return; var calls = traceLog.calls; for (var i = 0, n = calls.length; i < n; ++i) this._logGrid.rootNode().appendChild(this._createCallNode(i, calls[i])); var lastNode = this._logGrid.rootNode().children[calls.length - 1]; if (lastNode) { lastNode.reveal(); lastNode.select(); } }, _createCallNode: function(index, call) { var traceLogItem = document.createElement("div"); var data = {}; data[0] = index + 1; data[1] = call.functionName || "context." + call.property; data[2] = ""; if (call.sourceURL) { var lineNumber = Math.max(0, call.lineNumber - 1) || 0; var columnNumber = Math.max(0, call.columnNumber - 1) || 0; data[2] = this._linkifier.linkifyLocation(call.sourceURL, lineNumber, columnNumber); } if (call.arguments) data[1] += "(" + call.arguments.join(", ") + ")"; else data[1] += " = " + call.value; if (typeof call.result !== "undefined") data[1] += " => " + call.result; var node = new WebInspector.DataGridNode(data); node.call = call; node.index = index; node.selectable = true; return node; }, __proto__: WebInspector.View.prototype } WebInspector.CanvasProfileType = function() { WebInspector.ProfileType.call(this, WebInspector.CanvasProfileType.TypeId, WebInspector.UIString("Capture Canvas Frame")); this._nextProfileUid = 1; CanvasAgent.enable(); } WebInspector.CanvasProfileType.TypeId = "CANVAS_PROFILE"; WebInspector.CanvasProfileType.prototype = { get buttonTooltip() { return WebInspector.UIString("Capture Canvas Frame."); }, buttonClicked: function(profilesPanel) { var profileHeader = new WebInspector.CanvasProfileHeader(this, WebInspector.UIString("Trace Log %d", this._nextProfileUid), this._nextProfileUid); ++this._nextProfileUid; profileHeader.isTemporary = true; profilesPanel.addProfileHeader(profileHeader); function didStartCapturingFrame(error, traceLogId) { profileHeader._traceLogId = traceLogId; profileHeader.isTemporary = false; } CanvasAgent.captureFrame(didStartCapturingFrame.bind(this)); return false; }, get treeItemTitle() { return WebInspector.UIString("CANVAS PROFILE"); }, get description() { return WebInspector.UIString("Canvas calls instrumentation"); }, reset: function() { this._nextProfileUid = 1; }, createTemporaryProfile: function(title) { title = title || WebInspector.UIString("Capturing\u2026"); return new WebInspector.CanvasProfileHeader(this, title); }, createProfile: function(profile) { return new WebInspector.CanvasProfileHeader(this, profile.title, -1); }, __proto__: WebInspector.ProfileType.prototype } WebInspector.CanvasProfileHeader = function(type, title, uid) { WebInspector.ProfileHeader.call(this, type, title, uid); this._traceLogId = null; } WebInspector.CanvasProfileHeader.prototype = { traceLogId: function() { return this._traceLogId; }, createSidebarTreeElement: function() { return new WebInspector.ProfileSidebarTreeElement(this, WebInspector.UIString("Trace Log %d"), "profile-sidebar-tree-item"); }, createView: function(profilesPanel) { return new WebInspector.CanvasProfileView(this); }, __proto__: WebInspector.ProfileHeader.prototype } ;
JavaScript
Object.isEmpty = function(obj) { for (var i in obj) return false; return true; } Object.values = function(obj) { var keys = Object.keys(obj); var result = []; for (var i = 0; i < keys.length; ++i) result.push(obj[keys[i]]); return result; } String.prototype.hasSubstring = function(string, caseInsensitive) { if (!caseInsensitive) return this.indexOf(string) !== -1; return this.match(new RegExp(string.escapeForRegExp(), "i")); } String.prototype.findAll = function(string) { var matches = []; var i = this.indexOf(string); while (i !== -1) { matches.push(i); i = this.indexOf(string, i + string.length); } return matches; } String.prototype.lineEndings = function() { if (!this._lineEndings) { this._lineEndings = this.findAll("\n"); this._lineEndings.push(this.length); } return this._lineEndings; } String.prototype.escapeCharacters = function(chars) { var foundChar = false; for (var i = 0; i < chars.length; ++i) { if (this.indexOf(chars.charAt(i)) !== -1) { foundChar = true; break; } } if (!foundChar) return this; var result = ""; for (var i = 0; i < this.length; ++i) { if (chars.indexOf(this.charAt(i)) !== -1) result += "\\"; result += this.charAt(i); } return result; } String.prototype.escapeForRegExp = function() { return this.escapeCharacters("^[]{}()\\.$*+?|"); } String.prototype.escapeHTML = function() { return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); } String.prototype.collapseWhitespace = function() { return this.replace(/[\s\xA0]+/g, " "); } String.prototype.trimMiddle = function(maxLength) { if (this.length <= maxLength) return this; var leftHalf = maxLength >> 1; var rightHalf = maxLength - leftHalf - 1; return this.substr(0, leftHalf) + "\u2026" + this.substr(this.length - rightHalf, rightHalf); } String.prototype.trimEnd = function(maxLength) { if (this.length <= maxLength) return this; return this.substr(0, maxLength - 1) + "\u2026"; } String.prototype.trimURL = function(baseURLDomain) { var result = this.replace(/^(https|http|file):\/\//i, ""); if (baseURLDomain) result = result.replace(new RegExp("^" + baseURLDomain.escapeForRegExp(), "i"), ""); return result; } function sanitizeHref(href) { return href && href.trim().toLowerCase().startsWith("javascript:") ? "" : href; } String.prototype.removeURLFragment = function() { var fragmentIndex = this.indexOf("#"); if (fragmentIndex == -1) fragmentIndex = this.length; return this.substring(0, fragmentIndex); } String.prototype.startsWith = function(substring) { return !this.lastIndexOf(substring, 0); } String.prototype.endsWith = function(substring) { return this.indexOf(substring, this.length - substring.length) !== -1; } Number.constrain = function(num, min, max) { if (num < min) num = min; else if (num > max) num = max; return num; } Date.prototype.toISO8601Compact = function() { function leadZero(x) { return x > 9 ? '' + x : '0' + x } return this.getFullYear() + leadZero(this.getMonth() + 1) + leadZero(this.getDate()) + 'T' + leadZero(this.getHours()) + leadZero(this.getMinutes()) + leadZero(this.getSeconds()); } Object.defineProperty(Array.prototype, "remove", { value: function(value, onlyFirst) { if (onlyFirst) { var index = this.indexOf(value); if (index !== -1) this.splice(index, 1); return; } var length = this.length; for (var i = 0; i < length; ++i) { if (this[i] === value) this.splice(i, 1); } } }); Object.defineProperty(Array.prototype, "keySet", { value: function() { var keys = {}; for (var i = 0; i < this.length; ++i) keys[this[i]] = true; return keys; } }); Object.defineProperty(Array.prototype, "upperBound", { value: function(value) { var first = 0; var count = this.length; while (count > 0) { var step = count >> 1; var middle = first + step; if (value >= this[middle]) { first = middle + 1; count -= step + 1; } else count = step; } return first; } }); Object.defineProperty(Array.prototype, "rotate", { value: function(index) { var result = []; for (var i = index; i < index + this.length; ++i) result.push(this[i % this.length]); return result; } }); Object.defineProperty(Uint32Array.prototype, "sort", { value: Array.prototype.sort }); (function() { var partition = { value: function(comparator, left, right, pivotIndex) { function swap(array, i1, i2) { var temp = array[i1]; array[i1] = array[i2]; array[i2] = temp; } var pivotValue = this[pivotIndex]; swap(this, right, pivotIndex); var storeIndex = left; for (var i = left; i < right; ++i) { if (comparator(this[i], pivotValue) < 0) { swap(this, storeIndex, i); ++storeIndex; } } swap(this, right, storeIndex); return storeIndex; } }; Object.defineProperty(Array.prototype, "partition", partition); Object.defineProperty(Uint32Array.prototype, "partition", partition); var sortRange = { value: function(comparator, leftBound, rightBound, k) { function quickSortFirstK(array, comparator, left, right, k) { if (right <= left) return; var pivotIndex = Math.floor(Math.random() * (right - left)) + left; var pivotNewIndex = array.partition(comparator, left, right, pivotIndex); quickSortFirstK(array, comparator, left, pivotNewIndex - 1, k); if (pivotNewIndex < left + k - 1) quickSortFirstK(array, comparator, pivotNewIndex + 1, right, k); } if (leftBound === 0 && rightBound === (this.length - 1) && k === this.length) this.sort(comparator); else quickSortFirstK(this, comparator, leftBound, rightBound, k); return this; } } Object.defineProperty(Array.prototype, "sortRange", sortRange); Object.defineProperty(Uint32Array.prototype, "sortRange", sortRange); })(); Object.defineProperty(Array.prototype, "qselect", { value: function(k, comparator) { if (k < 0 || k >= this.length) return; if (!comparator) comparator = function(a, b) { return a - b; } var low = 0; var high = this.length - 1; for (;;) { var pivotPosition = this.partition(comparator, low, high, Math.floor((high + low) / 2)); if (pivotPosition === k) return this[k]; else if (pivotPosition > k) high = pivotPosition - 1; else low = pivotPosition + 1; } } }); function binarySearch(object, array, comparator) { var first = 0; var last = array.length - 1; while (first <= last) { var mid = (first + last) >> 1; var c = comparator(object, array[mid]); if (c > 0) first = mid + 1; else if (c < 0) last = mid - 1; else return mid; } return -(first + 1); } Object.defineProperty(Array.prototype, "binaryIndexOf", { value: function(value, comparator) { var result = binarySearch(value, this, comparator); return result >= 0 ? result : -1; } }); Object.defineProperty(Array.prototype, "select", { value: function(field) { var result = new Array(this.length); for (var i = 0; i < this.length; ++i) result[i] = this[i][field]; return result; } }); function insertionIndexForObjectInListSortedByFunction(anObject, aList, aFunction) { var index = binarySearch(anObject, aList, aFunction); if (index < 0) return -index - 1; else { while (index > 0 && aFunction(anObject, aList[index - 1]) === 0) index--; return index; } } String.sprintf = function(format, var_arg) { return String.vsprintf(format, Array.prototype.slice.call(arguments, 1)); } String.tokenizeFormatString = function(format, formatters) { var tokens = []; var substitutionIndex = 0; function addStringToken(str) { tokens.push({ type: "string", value: str }); } function addSpecifierToken(specifier, precision, substitutionIndex) { tokens.push({ type: "specifier", specifier: specifier, precision: precision, substitutionIndex: substitutionIndex }); } function isDigit(c) { return !!/[0-9]/.exec(c); } var index = 0; for (var precentIndex = format.indexOf("%", index); precentIndex !== -1; precentIndex = format.indexOf("%", index)) { addStringToken(format.substring(index, precentIndex)); index = precentIndex + 1; if (isDigit(format[index])) { var number = parseInt(format.substring(index), 10); while (isDigit(format[index])) ++index; if (number > 0 && format[index] === "$") { substitutionIndex = (number - 1); ++index; } } var precision = -1; if (format[index] === ".") { ++index; precision = parseInt(format.substring(index), 10); if (isNaN(precision)) precision = 0; while (isDigit(format[index])) ++index; } if (!(format[index] in formatters)) { addStringToken(format.substring(precentIndex, index + 1)); ++index; continue; } addSpecifierToken(format[index], precision, substitutionIndex); ++substitutionIndex; ++index; } addStringToken(format.substring(index)); return tokens; } String.standardFormatters = { d: function(substitution) { return !isNaN(substitution) ? substitution : 0; }, f: function(substitution, token) { if (substitution && token.precision > -1) substitution = substitution.toFixed(token.precision); return !isNaN(substitution) ? substitution : (token.precision > -1 ? Number(0).toFixed(token.precision) : 0); }, s: function(substitution) { return substitution; } } String.vsprintf = function(format, substitutions) { return String.format(format, substitutions, String.standardFormatters, "", function(a, b) { return a + b; }).formattedResult; } String.format = function(format, substitutions, formatters, initialValue, append) { if (!format || !substitutions || !substitutions.length) return { formattedResult: append(initialValue, format), unusedSubstitutions: substitutions }; function prettyFunctionName() { return "String.format(\"" + format + "\", \"" + substitutions.join("\", \"") + "\")"; } function warn(msg) { console.warn(prettyFunctionName() + ": " + msg); } function error(msg) { console.error(prettyFunctionName() + ": " + msg); } var result = initialValue; var tokens = String.tokenizeFormatString(format, formatters); var usedSubstitutionIndexes = {}; for (var i = 0; i < tokens.length; ++i) { var token = tokens[i]; if (token.type === "string") { result = append(result, token.value); continue; } if (token.type !== "specifier") { error("Unknown token type \"" + token.type + "\" found."); continue; } if (token.substitutionIndex >= substitutions.length) { error("not enough substitution arguments. Had " + substitutions.length + " but needed " + (token.substitutionIndex + 1) + ", so substitution was skipped."); result = append(result, "%" + (token.precision > -1 ? token.precision : "") + token.specifier); continue; } usedSubstitutionIndexes[token.substitutionIndex] = true; if (!(token.specifier in formatters)) { warn("unsupported format character \u201C" + token.specifier + "\u201D. Treating as a string."); result = append(result, substitutions[token.substitutionIndex]); continue; } result = append(result, formatters[token.specifier](substitutions[token.substitutionIndex], token)); } var unusedSubstitutions = []; for (var i = 0; i < substitutions.length; ++i) { if (i in usedSubstitutionIndexes) continue; unusedSubstitutions.push(substitutions[i]); } return { formattedResult: result, unusedSubstitutions: unusedSubstitutions }; } function createSearchRegex(query, caseSensitive, isRegex) { var regexFlags = caseSensitive ? "g" : "gi"; var regexObject; if (isRegex) { try { regexObject = new RegExp(query, regexFlags); } catch (e) { } } if (!regexObject) regexObject = createPlainTextSearchRegex(query, regexFlags); return regexObject; } function createPlainTextSearchRegex(query, flags) { var regexSpecialCharacters = "[](){}+-*.,?\\^$|"; var regex = ""; for (var i = 0; i < query.length; ++i) { var c = query.charAt(i); if (regexSpecialCharacters.indexOf(c) != -1) regex += "\\"; regex += c; } return new RegExp(regex, flags || ""); } function countRegexMatches(regex, content) { var text = content; var result = 0; var match; while (text && (match = regex.exec(text))) { if (match[0].length > 0) ++result; text = text.substring(match.index + 1); } return result; } function numberToStringWithSpacesPadding(value, symbolsCount) { var numberString = value.toString(); var paddingLength = Math.max(0, symbolsCount - numberString.length); var paddingString = Array(paddingLength + 1).join("\u00a0"); return paddingString + numberString; } var Map = function() { this._map = {}; this._size = 0; } Map._lastObjectIdentifier = 0; Map.prototype = { put: function(key, value) { var objectIdentifier = key.__identifier; if (!objectIdentifier) { objectIdentifier = ++Map._lastObjectIdentifier; key.__identifier = objectIdentifier; } if (!this._map[objectIdentifier]) ++this._size; this._map[objectIdentifier] = [key, value]; }, remove: function(key) { var result = this._map[key.__identifier]; delete this._map[key.__identifier]; --this._size; return result ? result[1] : undefined; }, keys: function() { return this._list(0); }, values: function() { return this._list(1); }, _list: function(index) { var result = new Array(this._size); var i = 0; for (var objectIdentifier in this._map) result[i++] = this._map[objectIdentifier][index]; return result; }, get: function(key) { var entry = this._map[key.__identifier]; return entry ? entry[1] : undefined; }, size: function() { return this._size; }, clear: function() { this._map = {}; this._size = 0; } } function loadXHR(url, async, callback) { function onReadyStateChanged() { if (xhr.readyState !== XMLHttpRequest.DONE) return; if (xhr.status === 200) { callback(xhr.responseText); return; } callback(null); } var xhr = new XMLHttpRequest(); xhr.open("GET", url, async); if (async) xhr.onreadystatechange = onReadyStateChanged; xhr.send(null); if (!async) { if (xhr.status === 200) return xhr.responseText; return null; } return null; } function StringPool() { this.reset(); } StringPool.prototype = { intern: function(string) { if (string === "__proto__") return "__proto__"; var result = this._strings[string]; if (result === undefined) { this._strings[string] = string; result = string; } return result; }, reset: function() { this._strings = Object.create(null); }, internObjectStrings: function(obj, depthLimit) { if (typeof depthLimit !== "number") depthLimit = 100; else if (--depthLimit < 0) throw "recursion depth limit reached in StringPool.deepIntern(), perhaps attempting to traverse cyclical references?"; for (var field in obj) { switch (typeof obj[field]) { case "string": obj[field] = this.intern(obj[field]); break; case "object": this.internObjectStrings(obj[field], depthLimit); break; } } } } var _importedScripts = {}; function importScript(scriptName) { if (_importedScripts[scriptName]) return; _importedScripts[scriptName] = true; var xhr = new XMLHttpRequest(); xhr.open("GET", scriptName, false); xhr.send(null); var sourceURL = WebInspector.ParsedURL.completeURL(window.location.href, scriptName); window.eval(xhr.responseText + "\n//@ sourceURL=" + sourceURL); } __whitespace = {" ":true, "\t":true, "\n":true, "\f":true, "\r":true}; difflib = { defaultJunkFunction: function (c) { return __whitespace.hasOwnProperty(c); }, stripLinebreaks: function (str) { return str.replace(/^[\n\r]*|[\n\r]*$/g, ""); }, stringAsLines: function (str) { var lfpos = str.indexOf("\n"); var crpos = str.indexOf("\r"); var linebreak = ((lfpos > -1 && crpos > -1) || crpos < 0) ? "\n" : "\r"; var lines = str.split(linebreak); for (var i = 0; i < lines.length; i++) { lines[i] = difflib.stripLinebreaks(lines[i]); } return lines; }, __reduce: function (func, list, initial) { if (initial != null) { var value = initial; var idx = 0; } else if (list) { var value = list[0]; var idx = 1; } else { return null; } for (; idx < list.length; idx++) { value = func(value, list[idx]); } return value; }, __ntuplecomp: function (a, b) { var mlen = Math.max(a.length, b.length); for (var i = 0; i < mlen; i++) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; } return a.length == b.length ? 0 : (a.length < b.length ? -1 : 1); }, __calculate_ratio: function (matches, length) { return length ? 2.0 * matches / length : 1.0; }, __isindict: function (dict) { return function (key) { return dict.hasOwnProperty(key); }; }, __dictget: function (dict, key, defaultValue) { return dict.hasOwnProperty(key) ? dict[key] : defaultValue; }, SequenceMatcher: function (a, b, isjunk) { this.set_seqs = function (a, b) { this.set_seq1(a); this.set_seq2(b); } this.set_seq1 = function (a) { if (a == this.a) return; this.a = a; this.matching_blocks = this.opcodes = null; } this.set_seq2 = function (b) { if (b == this.b) return; this.b = b; this.matching_blocks = this.opcodes = this.fullbcount = null; this.__chain_b(); } this.__chain_b = function () { var b = this.b; var n = b.length; var b2j = this.b2j = {}; var populardict = {}; for (var i = 0; i < b.length; i++) { var elt = b[i]; if (b2j.hasOwnProperty(elt)) { var indices = b2j[elt]; if (n >= 200 && indices.length * 100 > n) { populardict[elt] = 1; delete b2j[elt]; } else { indices.push(i); } } else { b2j[elt] = [i]; } } for (var elt in populardict) { if (populardict.hasOwnProperty(elt)) { delete b2j[elt]; } } var isjunk = this.isjunk; var junkdict = {}; if (isjunk) { for (var elt in populardict) { if (populardict.hasOwnProperty(elt) && isjunk(elt)) { junkdict[elt] = 1; delete populardict[elt]; } } for (var elt in b2j) { if (b2j.hasOwnProperty(elt) && isjunk(elt)) { junkdict[elt] = 1; delete b2j[elt]; } } } this.isbjunk = difflib.__isindict(junkdict); this.isbpopular = difflib.__isindict(populardict); } this.find_longest_match = function (alo, ahi, blo, bhi) { var a = this.a; var b = this.b; var b2j = this.b2j; var isbjunk = this.isbjunk; var besti = alo; var bestj = blo; var bestsize = 0; var j = null; var j2len = {}; var nothing = []; for (var i = alo; i < ahi; i++) { var newj2len = {}; var jdict = difflib.__dictget(b2j, a[i], nothing); for (var jkey in jdict) { if (jdict.hasOwnProperty(jkey)) { j = jdict[jkey]; if (j < blo) continue; if (j >= bhi) break; newj2len[j] = k = difflib.__dictget(j2len, j - 1, 0) + 1; if (k > bestsize) { besti = i - k + 1; bestj = j - k + 1; bestsize = k; } } } j2len = newj2len; } while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) { besti--; bestj--; bestsize++; } while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] == b[bestj + bestsize]) { bestsize++; } while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) { besti--; bestj--; bestsize++; } while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] == b[bestj + bestsize]) { bestsize++; } return [besti, bestj, bestsize]; } this.get_matching_blocks = function () { if (this.matching_blocks != null) return this.matching_blocks; var la = this.a.length; var lb = this.b.length; var queue = [[0, la, 0, lb]]; var matching_blocks = []; var alo, ahi, blo, bhi, qi, i, j, k, x; while (queue.length) { qi = queue.pop(); alo = qi[0]; ahi = qi[1]; blo = qi[2]; bhi = qi[3]; x = this.find_longest_match(alo, ahi, blo, bhi); i = x[0]; j = x[1]; k = x[2]; if (k) { matching_blocks.push(x); if (alo < i && blo < j) queue.push([alo, i, blo, j]); if (i+k < ahi && j+k < bhi) queue.push([i + k, ahi, j + k, bhi]); } } matching_blocks.sort(difflib.__ntuplecomp); var i1 = j1 = k1 = block = 0; var non_adjacent = []; for (var idx in matching_blocks) { if (matching_blocks.hasOwnProperty(idx)) { block = matching_blocks[idx]; i2 = block[0]; j2 = block[1]; k2 = block[2]; if (i1 + k1 == i2 && j1 + k1 == j2) { k1 += k2; } else { if (k1) non_adjacent.push([i1, j1, k1]); i1 = i2; j1 = j2; k1 = k2; } } } if (k1) non_adjacent.push([i1, j1, k1]); non_adjacent.push([la, lb, 0]); this.matching_blocks = non_adjacent; return this.matching_blocks; } this.get_opcodes = function () { if (this.opcodes != null) return this.opcodes; var i = 0; var j = 0; var answer = []; this.opcodes = answer; var block, ai, bj, size, tag; var blocks = this.get_matching_blocks(); for (var idx in blocks) { if (blocks.hasOwnProperty(idx)) { block = blocks[idx]; ai = block[0]; bj = block[1]; size = block[2]; tag = ''; if (i < ai && j < bj) { tag = 'replace'; } else if (i < ai) { tag = 'delete'; } else if (j < bj) { tag = 'insert'; } if (tag) answer.push([tag, i, ai, j, bj]); i = ai + size; j = bj + size; if (size) answer.push(['equal', ai, i, bj, j]); } } return answer; } this.get_grouped_opcodes = function (n) { if (!n) n = 3; var codes = this.get_opcodes(); if (!codes) codes = [["equal", 0, 1, 0, 1]]; var code, tag, i1, i2, j1, j2; if (codes[0][0] == 'equal') { code = codes[0]; tag = code[0]; i1 = code[1]; i2 = code[2]; j1 = code[3]; j2 = code[4]; codes[0] = [tag, Math.max(i1, i2 - n), i2, Math.max(j1, j2 - n), j2]; } if (codes[codes.length - 1][0] == 'equal') { code = codes[codes.length - 1]; tag = code[0]; i1 = code[1]; i2 = code[2]; j1 = code[3]; j2 = code[4]; codes[codes.length - 1] = [tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]; } var nn = n + n; var groups = []; for (var idx in codes) { if (codes.hasOwnProperty(idx)) { code = codes[idx]; tag = code[0]; i1 = code[1]; i2 = code[2]; j1 = code[3]; j2 = code[4]; if (tag == 'equal' && i2 - i1 > nn) { groups.push([tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]); i1 = Math.max(i1, i2-n); j1 = Math.max(j1, j2-n); } groups.push([tag, i1, i2, j1, j2]); } } if (groups && groups[groups.length - 1][0] == 'equal') groups.pop(); return groups; } this.ratio = function () { matches = difflib.__reduce( function (sum, triple) { return sum + triple[triple.length - 1]; }, this.get_matching_blocks(), 0); return difflib.__calculate_ratio(matches, this.a.length + this.b.length); } this.quick_ratio = function () { var fullbcount, elt; if (this.fullbcount == null) { this.fullbcount = fullbcount = {}; for (var i = 0; i < this.b.length; i++) { elt = this.b[i]; fullbcount[elt] = difflib.__dictget(fullbcount, elt, 0) + 1; } } fullbcount = this.fullbcount; var avail = {}; var availhas = difflib.__isindict(avail); var matches = numb = 0; for (var i = 0; i < this.a.length; i++) { elt = this.a[i]; if (availhas(elt)) { numb = avail[elt]; } else { numb = difflib.__dictget(fullbcount, elt, 0); } avail[elt] = numb - 1; if (numb > 0) matches++; } return difflib.__calculate_ratio(matches, this.a.length + this.b.length); } this.real_quick_ratio = function () { var la = this.a.length; var lb = this.b.length; return _calculate_ratio(Math.min(la, lb), la + lb); } this.isjunk = isjunk ? isjunk : difflib.defaultJunkFunction; this.a = this.b = null; this.set_seqs(a, b); } } Node.prototype.rangeOfWord = function(offset, stopCharacters, stayWithinNode, direction) { var startNode; var startOffset = 0; var endNode; var endOffset = 0; if (!stayWithinNode) stayWithinNode = this; if (!direction || direction === "backward" || direction === "both") { var node = this; while (node) { if (node === stayWithinNode) { if (!startNode) startNode = stayWithinNode; break; } if (node.nodeType === Node.TEXT_NODE) { var start = (node === this ? (offset - 1) : (node.nodeValue.length - 1)); for (var i = start; i >= 0; --i) { if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) { startNode = node; startOffset = i + 1; break; } } } if (startNode) break; node = node.traversePreviousNode(stayWithinNode); } if (!startNode) { startNode = stayWithinNode; startOffset = 0; } } else { startNode = this; startOffset = offset; } if (!direction || direction === "forward" || direction === "both") { node = this; while (node) { if (node === stayWithinNode) { if (!endNode) endNode = stayWithinNode; break; } if (node.nodeType === Node.TEXT_NODE) { var start = (node === this ? offset : 0); for (var i = start; i < node.nodeValue.length; ++i) { if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) { endNode = node; endOffset = i; break; } } } if (endNode) break; node = node.traverseNextNode(stayWithinNode); } if (!endNode) { endNode = stayWithinNode; endOffset = stayWithinNode.nodeType === Node.TEXT_NODE ? stayWithinNode.nodeValue.length : stayWithinNode.childNodes.length; } } else { endNode = this; endOffset = offset; } var result = this.ownerDocument.createRange(); result.setStart(startNode, startOffset); result.setEnd(endNode, endOffset); return result; } Node.prototype.traverseNextTextNode = function(stayWithin) { var node = this.traverseNextNode(stayWithin); if (!node) return; while (node && node.nodeType !== Node.TEXT_NODE) node = node.traverseNextNode(stayWithin); return node; } Node.prototype.rangeBoundaryForOffset = function(offset) { var node = this.traverseNextTextNode(this); while (node && offset > node.nodeValue.length) { offset -= node.nodeValue.length; node = node.traverseNextTextNode(this); } if (!node) return { container: this, offset: 0 }; return { container: node, offset: offset }; } Element.prototype.removeStyleClass = function(className) { this.classList.remove(className); } Element.prototype.removeMatchingStyleClasses = function(classNameRegex) { var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)"); if (regex.test(this.className)) this.className = this.className.replace(regex, " "); } Element.prototype.addStyleClass = function(className) { this.classList.add(className); } Element.prototype.hasStyleClass = function(className) { return this.classList.contains(className); } Element.prototype.positionAt = function(x, y) { if (typeof x === "number") this.style.setProperty("left", x + "px"); else this.style.removeProperty("left"); if (typeof y === "number") this.style.setProperty("top", y + "px"); else this.style.removeProperty("top"); } Element.prototype.isScrolledToBottom = function() { return this.scrollTop + this.clientHeight === this.scrollHeight; } Element.prototype.remove = function() { if (this.parentElement) this.parentElement.removeChild(this); } function removeSubsequentNodes(fromNode, toNode) { for (var node = fromNode; node && node !== toNode; ) { var nodeToRemove = node; node = node.nextSibling; nodeToRemove.remove(); } } function Size(width, height) { this.width = width; this.height = height; } Element.prototype.measurePreferredSize = function() { document.body.appendChild(this); this.positionAt(0, 0); var result = new Size(this.offsetWidth, this.offsetHeight); this.positionAt(undefined, undefined); document.body.removeChild(this); return result; } Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray) { for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) for (var i = 0; i < nameArray.length; ++i) if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase()) return node; return null; } Node.prototype.enclosingNodeOrSelfWithNodeName = function(nodeName) { return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]); } Node.prototype.enclosingNodeOrSelfWithClass = function(className) { for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) if (node.nodeType === Node.ELEMENT_NODE && node.hasStyleClass(className)) return node; return null; } Element.prototype.query = function(query) { return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; } Element.prototype.removeChildren = function() { if (this.firstChild) this.textContent = ""; } Element.prototype.isInsertionCaretInside = function() { var selection = window.getSelection(); if (!selection.rangeCount || !selection.isCollapsed) return false; var selectionRange = selection.getRangeAt(0); return selectionRange.startContainer.isSelfOrDescendant(this); } Element.prototype.createChild = function(elementName, className) { var element = this.ownerDocument.createElement(elementName); if (className) element.className = className; this.appendChild(element); return element; } DocumentFragment.prototype.createChild = Element.prototype.createChild; Element.prototype.createTextChild = function(text) { var element = this.ownerDocument.createTextNode(text); this.appendChild(element); return element; } DocumentFragment.prototype.createTextChild = Element.prototype.createTextChild; Element.prototype.totalOffsetLeft = function() { return this.totalOffset().left; } Element.prototype.totalOffsetTop = function() { return this.totalOffset().top; } Element.prototype.totalOffset = function() { var totalLeft = 0; var totalTop = 0; for (var element = this; element; element = element.offsetParent) { totalLeft += element.offsetLeft; totalTop += element.offsetTop; if (this !== element) { totalLeft += element.clientLeft - element.scrollLeft; totalTop += element.clientTop - element.scrollTop; } } return { left: totalLeft, top: totalTop }; } Element.prototype.scrollOffset = function() { var curLeft = 0; var curTop = 0; for (var element = this; element; element = element.scrollParent) { curLeft += element.scrollLeft; curTop += element.scrollTop; } return { left: curLeft, top: curTop }; } function AnchorBox(x, y, width, height) { this.x = x || 0; this.y = y || 0; this.width = width || 0; this.height = height || 0; } Element.prototype.offsetRelativeToWindow = function(targetWindow) { var elementOffset = new AnchorBox(); var curElement = this; var curWindow = this.ownerDocument.defaultView; while (curWindow && curElement) { elementOffset.x += curElement.totalOffsetLeft(); elementOffset.y += curElement.totalOffsetTop(); if (curWindow === targetWindow) break; curElement = curWindow.frameElement; curWindow = curWindow.parent; } return elementOffset; } Element.prototype.boxInWindow = function(targetWindow) { targetWindow = targetWindow || this.ownerDocument.defaultView; var anchorBox = this.offsetRelativeToWindow(window); anchorBox.width = Math.min(this.offsetWidth, window.innerWidth - anchorBox.x); anchorBox.height = Math.min(this.offsetHeight, window.innerHeight - anchorBox.y); return anchorBox; } Element.prototype.setTextAndTitle = function(text) { this.textContent = text; this.title = text; } KeyboardEvent.prototype.__defineGetter__("data", function() { switch (this.type) { case "keypress": if (!this.ctrlKey && !this.metaKey) return String.fromCharCode(this.charCode); else return ""; case "keydown": case "keyup": if (!this.ctrlKey && !this.metaKey && !this.altKey) return String.fromCharCode(this.which); else return ""; } }); Event.prototype.consume = function(preventDefault) { this.stopImmediatePropagation(); if (preventDefault) this.preventDefault(); this.handled = true; } Text.prototype.select = function(start, end) { start = start || 0; end = end || this.textContent.length; if (start < 0) start = end + start; var selection = this.ownerDocument.defaultView.getSelection(); selection.removeAllRanges(); var range = this.ownerDocument.createRange(); range.setStart(this, start); range.setEnd(this, end); selection.addRange(range); return this; } Element.prototype.selectionLeftOffset = function() { var selection = window.getSelection(); if (!selection.containsNode(this, true)) return null; var leftOffset = selection.anchorOffset; var node = selection.anchorNode; while (node !== this) { while (node.previousSibling) { node = node.previousSibling; leftOffset += node.textContent.length; } node = node.parentNode; } return leftOffset; } Node.prototype.isAncestor = function(node) { if (!node) return false; var currentNode = node.parentNode; while (currentNode) { if (this === currentNode) return true; currentNode = currentNode.parentNode; } return false; } Node.prototype.isDescendant = function(descendant) { return !!descendant && descendant.isAncestor(this); } Node.prototype.isSelfOrAncestor = function(node) { return !!node && (node === this || this.isAncestor(node)); } Node.prototype.isSelfOrDescendant = function(node) { return !!node && (node === this || this.isDescendant(node)); } Node.prototype.traverseNextNode = function(stayWithin) { var node = this.firstChild; if (node) return node; if (stayWithin && this === stayWithin) return null; node = this.nextSibling; if (node) return node; node = this; while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin)) node = node.parentNode; if (!node) return null; return node.nextSibling; } Node.prototype.traversePreviousNode = function(stayWithin) { if (stayWithin && this === stayWithin) return null; var node = this.previousSibling; while (node && node.lastChild) node = node.lastChild; if (node) return node; return this.parentNode; } function isEnterKey(event) { return event.keyCode !== 229 && event.keyIdentifier === "Enter"; } function consumeEvent(e) { e.consume(); } window.isUnderTest = false; function NonLeakingMutationObserver(handler) { this._observer = new WebKitMutationObserver(handler); NonLeakingMutationObserver._instances.push(this); if (!window.testRunner && !window.isUnderTest && !NonLeakingMutationObserver._unloadListener) { NonLeakingMutationObserver._unloadListener = function() { while (NonLeakingMutationObserver._instances.length) NonLeakingMutationObserver._instances[NonLeakingMutationObserver._instances.length - 1].disconnect(); }; window.addEventListener("unload", NonLeakingMutationObserver._unloadListener, false); } } NonLeakingMutationObserver._instances = []; NonLeakingMutationObserver.prototype = { observe: function(element, config) { if (this._observer) this._observer.observe(element, config); }, disconnect: function() { if (this._observer) this._observer.disconnect(); NonLeakingMutationObserver._instances.remove(this); delete this._observer; } } function TreeOutline(listNode, nonFocusable) { this.children = []; this.selectedTreeElement = null; this._childrenListNode = listNode; this.childrenListElement = this._childrenListNode; this._childrenListNode.removeChildren(); this.expandTreeElementsWhenArrowing = false; this.root = true; this.hasChildren = false; this.expanded = true; this.selected = false; this.treeOutline = this; this.comparator = null; this.searchable = false; this.searchInputElement = null; this.setFocusable(!nonFocusable); this._childrenListNode.addEventListener("keydown", this._treeKeyDown.bind(this), true); this._childrenListNode.addEventListener("keypress", this._treeKeyPress.bind(this), true); this._treeElementsMap = new Map(); this._expandedStateMap = new Map(); } TreeOutline.prototype.setFocusable = function(focusable) { if (focusable) this._childrenListNode.setAttribute("tabIndex", 0); else this._childrenListNode.removeAttribute("tabIndex"); } TreeOutline.prototype.appendChild = function(child) { var insertionIndex; if (this.treeOutline.comparator) insertionIndex = insertionIndexForObjectInListSortedByFunction(child, this.children, this.treeOutline.comparator); else insertionIndex = this.children.length; this.insertChild(child, insertionIndex); } TreeOutline.prototype.insertChild = function(child, index) { if (!child) throw("child can't be undefined or null"); var previousChild = (index > 0 ? this.children[index - 1] : null); if (previousChild) { previousChild.nextSibling = child; child.previousSibling = previousChild; } else { child.previousSibling = null; } var nextChild = this.children[index]; if (nextChild) { nextChild.previousSibling = child; child.nextSibling = nextChild; } else { child.nextSibling = null; } this.children.splice(index, 0, child); this.hasChildren = true; child.parent = this; child.treeOutline = this.treeOutline; child.treeOutline._rememberTreeElement(child); var current = child.children[0]; while (current) { current.treeOutline = this.treeOutline; current.treeOutline._rememberTreeElement(current); current = current.traverseNextTreeElement(false, child, true); } if (child.hasChildren && typeof(child.treeOutline._expandedStateMap.get(child.representedObject)) !== "undefined") child.expanded = child.treeOutline._expandedStateMap.get(child.representedObject); if (!this._childrenListNode) { this._childrenListNode = this.treeOutline._childrenListNode.ownerDocument.createElement("ol"); this._childrenListNode.parentTreeElement = this; this._childrenListNode.classList.add("children"); if (this.hidden) this._childrenListNode.classList.add("hidden"); } child._attach(); } TreeOutline.prototype.removeChildAtIndex = function(childIndex) { if (childIndex < 0 || childIndex >= this.children.length) throw("childIndex out of range"); var child = this.children[childIndex]; this.children.splice(childIndex, 1); var parent = child.parent; if (child.deselect()) { if (child.previousSibling) child.previousSibling.select(); else if (child.nextSibling) child.nextSibling.select(); else parent.select(); } if (child.previousSibling) child.previousSibling.nextSibling = child.nextSibling; if (child.nextSibling) child.nextSibling.previousSibling = child.previousSibling; if (child.treeOutline) { child.treeOutline._forgetTreeElement(child); child.treeOutline._forgetChildrenRecursive(child); } child._detach(); child.treeOutline = null; child.parent = null; child.nextSibling = null; child.previousSibling = null; } TreeOutline.prototype.removeChild = function(child) { if (!child) throw("child can't be undefined or null"); var childIndex = this.children.indexOf(child); if (childIndex === -1) throw("child not found in this node's children"); this.removeChildAtIndex.call(this, childIndex); } TreeOutline.prototype.removeChildren = function() { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; child.deselect(); if (child.treeOutline) { child.treeOutline._forgetTreeElement(child); child.treeOutline._forgetChildrenRecursive(child); } child._detach(); child.treeOutline = null; child.parent = null; child.nextSibling = null; child.previousSibling = null; } this.children = []; } TreeOutline.prototype._rememberTreeElement = function(element) { if (!this._treeElementsMap.get(element.representedObject)) this._treeElementsMap.put(element.representedObject, []); var elements = this._treeElementsMap.get(element.representedObject); if (elements.indexOf(element) !== -1) return; elements.push(element); } TreeOutline.prototype._forgetTreeElement = function(element) { if (this._treeElementsMap.get(element.representedObject)) { var elements = this._treeElementsMap.get(element.representedObject); elements.remove(element, true); if (!elements.length) this._treeElementsMap.remove(element.representedObject); } } TreeOutline.prototype._forgetChildrenRecursive = function(parentElement) { var child = parentElement.children[0]; while (child) { this._forgetTreeElement(child); child = child.traverseNextTreeElement(false, parentElement, true); } } TreeOutline.prototype.getCachedTreeElement = function(representedObject) { if (!representedObject) return null; var elements = this._treeElementsMap.get(representedObject); if (elements && elements.length) return elements[0]; return null; } TreeOutline.prototype.findTreeElement = function(representedObject, isAncestor, getParent) { if (!representedObject) return null; var cachedElement = this.getCachedTreeElement(representedObject); if (cachedElement) return cachedElement; var ancestors = []; for (var currentObject = getParent(representedObject); currentObject; currentObject = getParent(currentObject)) { ancestors.push(currentObject); if (this.getCachedTreeElement(currentObject)) break; } if (!currentObject) return null; for (var i = ancestors.length - 1; i >= 0; --i) { var treeElement = this.getCachedTreeElement(ancestors[i]); if (treeElement) treeElement.onpopulate(); } return this.getCachedTreeElement(representedObject); } TreeOutline.prototype.treeElementFromPoint = function(x, y) { var node = this._childrenListNode.ownerDocument.elementFromPoint(x, y); if (!node) return null; var listNode = node.enclosingNodeOrSelfWithNodeNameInArray(["ol", "li"]); if (listNode) return listNode.parentTreeElement || listNode.treeElement; return null; } TreeOutline.prototype._treeKeyPress = function(event) { if (!this.searchable || WebInspector.isBeingEdited(this._childrenListNode)) return; var searchText = String.fromCharCode(event.charCode); if (searchText.trim() !== searchText) return; this._startSearch(searchText); event.consume(true); } TreeOutline.prototype._treeKeyDown = function(event) { if (event.target !== this._childrenListNode) return; if (!this.selectedTreeElement || event.shiftKey || event.metaKey || event.ctrlKey) return; var handled = false; var nextSelectedElement; if (event.keyIdentifier === "Up" && !event.altKey) { nextSelectedElement = this.selectedTreeElement.traversePreviousTreeElement(true); while (nextSelectedElement && !nextSelectedElement.selectable) nextSelectedElement = nextSelectedElement.traversePreviousTreeElement(!this.expandTreeElementsWhenArrowing); handled = nextSelectedElement ? true : false; } else if (event.keyIdentifier === "Down" && !event.altKey) { nextSelectedElement = this.selectedTreeElement.traverseNextTreeElement(true); while (nextSelectedElement && !nextSelectedElement.selectable) nextSelectedElement = nextSelectedElement.traverseNextTreeElement(!this.expandTreeElementsWhenArrowing); handled = nextSelectedElement ? true : false; } else if (event.keyIdentifier === "Left") { if (this.selectedTreeElement.expanded) { if (event.altKey) this.selectedTreeElement.collapseRecursively(); else this.selectedTreeElement.collapse(); handled = true; } else if (this.selectedTreeElement.parent && !this.selectedTreeElement.parent.root) { handled = true; if (this.selectedTreeElement.parent.selectable) { nextSelectedElement = this.selectedTreeElement.parent; while (nextSelectedElement && !nextSelectedElement.selectable) nextSelectedElement = nextSelectedElement.parent; handled = nextSelectedElement ? true : false; } else if (this.selectedTreeElement.parent) this.selectedTreeElement.parent.collapse(); } } else if (event.keyIdentifier === "Right") { if (!this.selectedTreeElement.revealed()) { this.selectedTreeElement.reveal(); handled = true; } else if (this.selectedTreeElement.hasChildren) { handled = true; if (this.selectedTreeElement.expanded) { nextSelectedElement = this.selectedTreeElement.children[0]; while (nextSelectedElement && !nextSelectedElement.selectable) nextSelectedElement = nextSelectedElement.nextSibling; handled = nextSelectedElement ? true : false; } else { if (event.altKey) this.selectedTreeElement.expandRecursively(); else this.selectedTreeElement.expand(); } } } else if (event.keyCode === 8 || event.keyCode === 46 ) handled = this.selectedTreeElement.ondelete(); else if (isEnterKey(event)) handled = this.selectedTreeElement.onenter(); else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Space.code) handled = this.selectedTreeElement.onspace(); if (nextSelectedElement) { nextSelectedElement.reveal(); nextSelectedElement.select(false, true); } if (handled) event.consume(true); } TreeOutline.prototype.expand = function() { } TreeOutline.prototype.collapse = function() { } TreeOutline.prototype.revealed = function() { return true; } TreeOutline.prototype.reveal = function() { } TreeOutline.prototype.select = function() { } TreeOutline.prototype.revealAndSelect = function(omitFocus) { } TreeOutline.prototype._startSearch = function(searchText) { if (!this.searchInputElement || !this.searchable) return; this._searching = true; if (this.searchStarted) this.searchStarted(); this.searchInputElement.value = searchText; function focusSearchInput() { this.searchInputElement.focus(); } window.setTimeout(focusSearchInput.bind(this), 0); this._searchTextChanged(); this._boundSearchTextChanged = this._searchTextChanged.bind(this); this.searchInputElement.addEventListener("paste", this._boundSearchTextChanged); this.searchInputElement.addEventListener("cut", this._boundSearchTextChanged); this.searchInputElement.addEventListener("keypress", this._boundSearchTextChanged); this._boundSearchInputKeyDown = this._searchInputKeyDown.bind(this); this.searchInputElement.addEventListener("keydown", this._boundSearchInputKeyDown); this._boundSearchInputBlur = this._searchInputBlur.bind(this); this.searchInputElement.addEventListener("blur", this._boundSearchInputBlur); } TreeOutline.prototype._searchTextChanged = function() { function updateSearch() { var nextSelectedElement = this._nextSearchMatch(this.searchInputElement.value, this.selectedTreeElement, false); if (!nextSelectedElement) nextSelectedElement = this._nextSearchMatch(this.searchInputElement.value, this.children[0], false); this._showSearchMatchElement(nextSelectedElement); } window.setTimeout(updateSearch.bind(this), 0); } TreeOutline.prototype._showSearchMatchElement = function(treeElement) { this._currentSearchMatchElement = treeElement; if (treeElement) { this._childrenListNode.classList.add("search-match-found"); this._childrenListNode.classList.remove("search-match-not-found"); treeElement.revealAndSelect(true); } else { this._childrenListNode.classList.remove("search-match-found"); this._childrenListNode.classList.add("search-match-not-found"); } } TreeOutline.prototype._searchInputKeyDown = function(event) { if (event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) return; var handled = false; var nextSelectedElement; if (event.keyIdentifier === "Down") { nextSelectedElement = this._nextSearchMatch(this.searchInputElement.value, this.selectedTreeElement, true); handled = true; } else if (event.keyIdentifier === "Up") { nextSelectedElement = this._previousSearchMatch(this.searchInputElement.value, this.selectedTreeElement); handled = true; } else if (event.keyCode === 27 ) { this._searchFinished(); handled = true; } else if (isEnterKey(event)) { var lastSearchMatchElement = this._currentSearchMatchElement; this._searchFinished(); lastSearchMatchElement.onenter(); handled = true; } if (nextSelectedElement) this._showSearchMatchElement(nextSelectedElement); if (handled) event.consume(true); else window.setTimeout(this._boundSearchTextChanged, 0); } TreeOutline.prototype._nextSearchMatch = function(searchText, startTreeElement, skipStartTreeElement) { var currentTreeElement = startTreeElement; var skipCurrentTreeElement = skipStartTreeElement; while (currentTreeElement && (skipCurrentTreeElement || !currentTreeElement.matchesSearchText || !currentTreeElement.matchesSearchText(searchText))) { currentTreeElement = currentTreeElement.traverseNextTreeElement(true, null, true); skipCurrentTreeElement = false; } return currentTreeElement; } TreeOutline.prototype._previousSearchMatch = function(searchText, startTreeElement) { var currentTreeElement = startTreeElement; var skipCurrentTreeElement = true; while (currentTreeElement && (skipCurrentTreeElement || !currentTreeElement.matchesSearchText || !currentTreeElement.matchesSearchText(searchText))) { currentTreeElement = currentTreeElement.traversePreviousTreeElement(true, true); skipCurrentTreeElement = false; } return currentTreeElement; } TreeOutline.prototype._searchInputBlur = function(event) { this._searchFinished(); } TreeOutline.prototype._searchFinished = function() { if (!this._searching) return; delete this._searching; this._childrenListNode.classList.remove("search-match-found"); this._childrenListNode.classList.remove("search-match-not-found"); delete this._currentSearchMatchElement; this.searchInputElement.value = ""; this.searchInputElement.removeEventListener("paste", this._boundSearchTextChanged); this.searchInputElement.removeEventListener("cut", this._boundSearchTextChanged); delete this._boundSearchTextChanged; this.searchInputElement.removeEventListener("keydown", this._boundSearchInputKeyDown); delete this._boundSearchInputKeyDown; this.searchInputElement.removeEventListener("blur", this._boundSearchInputBlur); delete this._boundSearchInputBlur; if (this.searchFinished) this.searchFinished(); this.treeOutline._childrenListNode.focus(); } TreeOutline.prototype.stopSearch = function() { this._searchFinished(); } function TreeElement(title, representedObject, hasChildren) { this._title = title; this.representedObject = (representedObject || {}); this._hidden = false; this._selectable = true; this.expanded = false; this.selected = false; this.hasChildren = hasChildren; this.children = []; this.treeOutline = null; this.parent = null; this.previousSibling = null; this.nextSibling = null; this._listItemNode = null; } TreeElement.prototype = { arrowToggleWidth: 10, get selectable() { if (this._hidden) return false; return this._selectable; }, set selectable(x) { this._selectable = x; }, get listItemElement() { return this._listItemNode; }, get childrenListElement() { return this._childrenListNode; }, get title() { return this._title; }, set title(x) { this._title = x; this._setListItemNodeContent(); }, get tooltip() { return this._tooltip; }, set tooltip(x) { this._tooltip = x; if (this._listItemNode) this._listItemNode.title = x ? x : ""; }, get hasChildren() { return this._hasChildren; }, set hasChildren(x) { if (this._hasChildren === x) return; this._hasChildren = x; if (!this._listItemNode) return; if (x) this._listItemNode.classList.add("parent"); else { this._listItemNode.classList.remove("parent"); this.collapse(); } }, get hidden() { return this._hidden; }, set hidden(x) { if (this._hidden === x) return; this._hidden = x; if (x) { if (this._listItemNode) this._listItemNode.classList.add("hidden"); if (this._childrenListNode) this._childrenListNode.classList.add("hidden"); } else { if (this._listItemNode) this._listItemNode.classList.remove("hidden"); if (this._childrenListNode) this._childrenListNode.classList.remove("hidden"); } }, get shouldRefreshChildren() { return this._shouldRefreshChildren; }, set shouldRefreshChildren(x) { this._shouldRefreshChildren = x; if (x && this.expanded) this.expand(); }, _setListItemNodeContent: function() { if (!this._listItemNode) return; if (typeof this._title === "string") this._listItemNode.textContent = this._title; else { this._listItemNode.removeChildren(); if (this._title) this._listItemNode.appendChild(this._title); } } } TreeElement.prototype.appendChild = TreeOutline.prototype.appendChild; TreeElement.prototype.insertChild = TreeOutline.prototype.insertChild; TreeElement.prototype.removeChild = TreeOutline.prototype.removeChild; TreeElement.prototype.removeChildAtIndex = TreeOutline.prototype.removeChildAtIndex; TreeElement.prototype.removeChildren = TreeOutline.prototype.removeChildren; TreeElement.prototype._attach = function() { if (!this._listItemNode || this.parent._shouldRefreshChildren) { if (this._listItemNode && this._listItemNode.parentNode) this._listItemNode.parentNode.removeChild(this._listItemNode); this._listItemNode = this.treeOutline._childrenListNode.ownerDocument.createElement("li"); this._listItemNode.treeElement = this; this._setListItemNodeContent(); this._listItemNode.title = this._tooltip ? this._tooltip : ""; if (this.hidden) this._listItemNode.classList.add("hidden"); if (this.hasChildren) this._listItemNode.classList.add("parent"); if (this.expanded) this._listItemNode.classList.add("expanded"); if (this.selected) this._listItemNode.classList.add("selected"); this._listItemNode.addEventListener("mousedown", TreeElement.treeElementMouseDown, false); this._listItemNode.addEventListener("click", TreeElement.treeElementToggled, false); this._listItemNode.addEventListener("dblclick", TreeElement.treeElementDoubleClicked, false); this.onattach(); } var nextSibling = null; if (this.nextSibling && this.nextSibling._listItemNode && this.nextSibling._listItemNode.parentNode === this.parent._childrenListNode) nextSibling = this.nextSibling._listItemNode; this.parent._childrenListNode.insertBefore(this._listItemNode, nextSibling); if (this._childrenListNode) this.parent._childrenListNode.insertBefore(this._childrenListNode, this._listItemNode.nextSibling); if (this.selected) this.select(); if (this.expanded) this.expand(); } TreeElement.prototype._detach = function() { if (this._listItemNode && this._listItemNode.parentNode) this._listItemNode.parentNode.removeChild(this._listItemNode); if (this._childrenListNode && this._childrenListNode.parentNode) this._childrenListNode.parentNode.removeChild(this._childrenListNode); } TreeElement.treeElementMouseDown = function(event) { var element = event.currentTarget; if (!element || !element.treeElement || !element.treeElement.selectable) return; if (element.treeElement.isEventWithinDisclosureTriangle(event)) return; element.treeElement.selectOnMouseDown(event); } TreeElement.treeElementToggled = function(event) { var element = event.currentTarget; if (!element || !element.treeElement) return; var toggleOnClick = element.treeElement.toggleOnClick && !element.treeElement.selectable; var isInTriangle = element.treeElement.isEventWithinDisclosureTriangle(event); if (!toggleOnClick && !isInTriangle) return; if (element.treeElement.expanded) { if (event.altKey) element.treeElement.collapseRecursively(); else element.treeElement.collapse(); } else { if (event.altKey) element.treeElement.expandRecursively(); else element.treeElement.expand(); } event.consume(); } TreeElement.treeElementDoubleClicked = function(event) { var element = event.currentTarget; if (!element || !element.treeElement) return; var handled = element.treeElement.ondblclick.call(element.treeElement, event); if (handled) return; if (element.treeElement.hasChildren && !element.treeElement.expanded) element.treeElement.expand(); } TreeElement.prototype.collapse = function() { if (this._listItemNode) this._listItemNode.classList.remove("expanded"); if (this._childrenListNode) this._childrenListNode.classList.remove("expanded"); this.expanded = false; if (this.treeOutline) this.treeOutline._expandedStateMap.put(this.representedObject, false); this.oncollapse(); } TreeElement.prototype.collapseRecursively = function() { var item = this; while (item) { if (item.expanded) item.collapse(); item = item.traverseNextTreeElement(false, this, true); } } TreeElement.prototype.expand = function() { if (!this.hasChildren || (this.expanded && !this._shouldRefreshChildren && this._childrenListNode)) return; this.expanded = true; if (this.treeOutline) this.treeOutline._expandedStateMap.put(this.representedObject, true); if (this.treeOutline && (!this._childrenListNode || this._shouldRefreshChildren)) { if (this._childrenListNode && this._childrenListNode.parentNode) this._childrenListNode.parentNode.removeChild(this._childrenListNode); this._childrenListNode = this.treeOutline._childrenListNode.ownerDocument.createElement("ol"); this._childrenListNode.parentTreeElement = this; this._childrenListNode.classList.add("children"); if (this.hidden) this._childrenListNode.classList.add("hidden"); this.onpopulate(); for (var i = 0; i < this.children.length; ++i) this.children[i]._attach(); delete this._shouldRefreshChildren; } if (this._listItemNode) { this._listItemNode.classList.add("expanded"); if (this._childrenListNode && this._childrenListNode.parentNode != this._listItemNode.parentNode) this.parent._childrenListNode.insertBefore(this._childrenListNode, this._listItemNode.nextSibling); } if (this._childrenListNode) this._childrenListNode.classList.add("expanded"); this.onexpand(); } TreeElement.prototype.expandRecursively = function(maxDepth) { var item = this; var info = {}; var depth = 0; if (isNaN(maxDepth)) maxDepth = 3; while (item) { if (depth < maxDepth) item.expand(); item = item.traverseNextTreeElement(false, this, (depth >= maxDepth), info); depth += info.depthChange; } } TreeElement.prototype.hasAncestor = function(ancestor) { if (!ancestor) return false; var currentNode = this.parent; while (currentNode) { if (ancestor === currentNode) return true; currentNode = currentNode.parent; } return false; } TreeElement.prototype.reveal = function() { var currentAncestor = this.parent; while (currentAncestor && !currentAncestor.root) { if (!currentAncestor.expanded) currentAncestor.expand(); currentAncestor = currentAncestor.parent; } this.onreveal(this); } TreeElement.prototype.revealed = function() { var currentAncestor = this.parent; while (currentAncestor && !currentAncestor.root) { if (!currentAncestor.expanded) return false; currentAncestor = currentAncestor.parent; } return true; } TreeElement.prototype.selectOnMouseDown = function(event) { if (this.select(false, true)) event.consume(true); } TreeElement.prototype.select = function(omitFocus, selectedByUser) { if (!this.treeOutline || !this.selectable || this.selected) return false; if (this.treeOutline.selectedTreeElement) this.treeOutline.selectedTreeElement.deselect(); this.selected = true; if(!omitFocus) this.treeOutline._childrenListNode.focus(); if (!this.treeOutline) return false; this.treeOutline.selectedTreeElement = this; if (this._listItemNode) this._listItemNode.classList.add("selected"); return this.onselect(selectedByUser); } TreeElement.prototype.revealAndSelect = function(omitFocus) { this.reveal(); this.select(omitFocus); } TreeElement.prototype.deselect = function(supressOnDeselect) { if (!this.treeOutline || this.treeOutline.selectedTreeElement !== this || !this.selected) return false; this.selected = false; this.treeOutline.selectedTreeElement = null; if (this._listItemNode) this._listItemNode.classList.remove("selected"); return true; } TreeElement.prototype.onpopulate = function() { } TreeElement.prototype.onenter = function() { } TreeElement.prototype.ondelete = function() { } TreeElement.prototype.onspace = function() { } TreeElement.prototype.onattach = function() { } TreeElement.prototype.onexpand = function() { } TreeElement.prototype.oncollapse = function() { } TreeElement.prototype.ondblclick = function() { } TreeElement.prototype.onreveal = function() { } TreeElement.prototype.onselect = function(selectedByUser) { } TreeElement.prototype.traverseNextTreeElement = function(skipUnrevealed, stayWithin, dontPopulate, info) { if (!dontPopulate && this.hasChildren) this.onpopulate(); if (info) info.depthChange = 0; var element = skipUnrevealed ? (this.revealed() ? this.children[0] : null) : this.children[0]; if (element && (!skipUnrevealed || (skipUnrevealed && this.expanded))) { if (info) info.depthChange = 1; return element; } if (this === stayWithin) return null; element = skipUnrevealed ? (this.revealed() ? this.nextSibling : null) : this.nextSibling; if (element) return element; element = this; while (element && !element.root && !(skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling) && element.parent !== stayWithin) { if (info) info.depthChange -= 1; element = element.parent; } if (!element) return null; return (skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling); } TreeElement.prototype.traversePreviousTreeElement = function(skipUnrevealed, dontPopulate) { var element = skipUnrevealed ? (this.revealed() ? this.previousSibling : null) : this.previousSibling; if (!dontPopulate && element && element.hasChildren) element.onpopulate(); while (element && (skipUnrevealed ? (element.revealed() && element.expanded ? element.children[element.children.length - 1] : null) : element.children[element.children.length - 1])) { if (!dontPopulate && element.hasChildren) element.onpopulate(); element = (skipUnrevealed ? (element.revealed() && element.expanded ? element.children[element.children.length - 1] : null) : element.children[element.children.length - 1]); } if (element) return element; if (!this.parent || this.parent.root) return null; return this.parent; } TreeElement.prototype.isEventWithinDisclosureTriangle = function(event) { var paddingLeftValue = window.getComputedStyle(this._listItemNode).getPropertyCSSValue("padding-left"); var computedLeftPadding = paddingLeftValue ? paddingLeftValue.getFloatValue(CSSPrimitiveValue.CSS_PX) : 0; var left = this._listItemNode.totalOffsetLeft() + computedLeftPadding; return event.pageX >= left && event.pageX <= left + this.arrowToggleWidth && this.hasChildren; } var WebInspector = { _panelDescriptors: function() { this.panels = {}; WebInspector.inspectorView = new WebInspector.InspectorView(); var parentElement = document.getElementById("main"); WebInspector.inspectorView.show(parentElement); WebInspector.inspectorView.addEventListener(WebInspector.InspectorView.Events.PanelSelected, this._panelSelected, this); var elements = new WebInspector.ElementsPanelDescriptor(); var resources = new WebInspector.PanelDescriptor("resources", WebInspector.UIString("Resources"), "ResourcesPanel", "ResourcesPanel.js"); var network = new WebInspector.NetworkPanelDescriptor(); var scripts = new WebInspector.ScriptsPanelDescriptor(); var timeline = new WebInspector.TimelinePanelDescriptor(); var profiles = new WebInspector.PanelDescriptor("profiles", WebInspector.UIString("Profiles"), "ProfilesPanel", "ProfilesPanel.js"); var audits = new WebInspector.PanelDescriptor("audits", WebInspector.UIString("Audits"), "AuditsPanel", "AuditsPanel.js"); var console = new WebInspector.PanelDescriptor("console", WebInspector.UIString("Console"), "ConsolePanel"); var allDescriptors = [elements, resources, network, scripts, timeline, profiles, audits, console]; var panelDescriptors = []; if (WebInspector.WorkerManager.isWorkerFrontend()) { panelDescriptors.push(scripts); panelDescriptors.push(timeline); panelDescriptors.push(profiles); panelDescriptors.push(console); return panelDescriptors; } var hiddenPanels = InspectorFrontendHost.hiddenPanels(); for (var i = 0; i < allDescriptors.length; ++i) { if (hiddenPanels.indexOf(allDescriptors[i].name()) === -1) panelDescriptors.push(allDescriptors[i]); } return panelDescriptors; }, _panelSelected: function() { this._toggleConsoleButton.setEnabled(WebInspector.inspectorView.currentPanel().name !== "console"); }, _createGlobalStatusBarItems: function() { var bottomStatusBarContainer = document.getElementById("bottom-status-bar-container"); var mainStatusBar = document.getElementById("main-status-bar"); mainStatusBar.insertBefore(this.dockController.element, bottomStatusBarContainer); this._toggleConsoleButton = new WebInspector.StatusBarButton(WebInspector.UIString("Show console."), "console-status-bar-item"); this._toggleConsoleButton.addEventListener("click", this._toggleConsoleButtonClicked.bind(this), false); mainStatusBar.insertBefore(this._toggleConsoleButton.element, bottomStatusBarContainer); if (!WebInspector.WorkerManager.isWorkerFrontend()) { this._nodeSearchButton = new WebInspector.StatusBarButton(WebInspector.UIString("Select an element in the page to inspect it."), "node-search-status-bar-item"); this._nodeSearchButton.addEventListener("click", this.toggleSearchingForNode, this); mainStatusBar.insertBefore(this._nodeSearchButton.element, bottomStatusBarContainer); } mainStatusBar.appendChild(this.settingsController.statusBarItem); }, _toggleConsoleButtonClicked: function() { if (!this._toggleConsoleButton.enabled()) return; this._toggleConsoleButton.toggled = !this._toggleConsoleButton.toggled; var animationType = window.event && window.event.shiftKey ? WebInspector.Drawer.AnimationType.Slow : WebInspector.Drawer.AnimationType.Normal; if (this._toggleConsoleButton.toggled) { this._toggleConsoleButton.title = WebInspector.UIString("Hide console."); this.drawer.show(this.consoleView, animationType); this._consoleWasShown = true; } else { this._toggleConsoleButton.title = WebInspector.UIString("Show console."); this.drawer.hide(animationType); delete this._consoleWasShown; } }, showViewInDrawer: function(statusBarElement, view, onclose) { this._toggleConsoleButton.title = WebInspector.UIString("Hide console."); this._toggleConsoleButton.toggled = false; this._closePreviousDrawerView(); var drawerStatusBarHeader = document.createElement("div"); drawerStatusBarHeader.className = "drawer-header status-bar-item"; drawerStatusBarHeader.appendChild(statusBarElement); drawerStatusBarHeader.onclose = onclose; var closeButton = drawerStatusBarHeader.createChild("span"); closeButton.textContent = WebInspector.UIString("\u00D7"); closeButton.addStyleClass("drawer-header-close-button"); closeButton.addEventListener("click", this.closeViewInDrawer.bind(this), false); document.getElementById("panel-status-bar").firstElementChild.appendChild(drawerStatusBarHeader); this._drawerStatusBarHeader = drawerStatusBarHeader; this.drawer.show(view, WebInspector.Drawer.AnimationType.Immediately); }, closeViewInDrawer: function() { if (this._drawerStatusBarHeader) { this._closePreviousDrawerView(); if (!this._consoleWasShown) this.drawer.hide(WebInspector.Drawer.AnimationType.Immediately); else this._toggleConsoleButtonClicked(); } }, _closePreviousDrawerView: function() { if (this._drawerStatusBarHeader) { this._drawerStatusBarHeader.parentElement.removeChild(this._drawerStatusBarHeader); if (this._drawerStatusBarHeader.onclose) this._drawerStatusBarHeader.onclose(); delete this._drawerStatusBarHeader; } }, _updateErrorAndWarningCounts: function() { var errorWarningElement = document.getElementById("error-warning-count"); if (!errorWarningElement) return; var errors = WebInspector.console.errors; var warnings = WebInspector.console.warnings; if (!errors && !warnings) { errorWarningElement.addStyleClass("hidden"); return; } errorWarningElement.removeStyleClass("hidden"); errorWarningElement.removeChildren(); if (errors) { var errorImageElement = document.createElement("img"); errorImageElement.id = "error-count-img"; errorWarningElement.appendChild(errorImageElement); var errorElement = document.createElement("span"); errorElement.id = "error-count"; errorElement.textContent = errors; errorWarningElement.appendChild(errorElement); } if (warnings) { var warningsImageElement = document.createElement("img"); warningsImageElement.id = "warning-count-img"; errorWarningElement.appendChild(warningsImageElement); var warningsElement = document.createElement("span"); warningsElement.id = "warning-count"; warningsElement.textContent = warnings; errorWarningElement.appendChild(warningsElement); } if (errors) { if (warnings) { if (errors == 1) { if (warnings == 1) errorWarningElement.title = WebInspector.UIString("%d error, %d warning", errors, warnings); else errorWarningElement.title = WebInspector.UIString("%d error, %d warnings", errors, warnings); } else if (warnings == 1) errorWarningElement.title = WebInspector.UIString("%d errors, %d warning", errors, warnings); else errorWarningElement.title = WebInspector.UIString("%d errors, %d warnings", errors, warnings); } else if (errors == 1) errorWarningElement.title = WebInspector.UIString("%d error", errors); else errorWarningElement.title = WebInspector.UIString("%d errors", errors); } else if (warnings == 1) errorWarningElement.title = WebInspector.UIString("%d warning", warnings); else if (warnings) errorWarningElement.title = WebInspector.UIString("%d warnings", warnings); else errorWarningElement.title = null; }, get inspectedPageDomain() { var parsedURL = WebInspector.inspectedPageURL && WebInspector.inspectedPageURL.asParsedURL(); return parsedURL ? parsedURL.host : ""; }, _initializeCapability: function(name, callback, error, result) { Capabilities[name] = result; if (callback) callback(); }, _zoomIn: function() { this._zoomLevel = Math.min(this._zoomLevel + 1, WebInspector.Zoom.Table.length - WebInspector.Zoom.DefaultOffset - 1); this._requestZoom(); }, _zoomOut: function() { this._zoomLevel = Math.max(this._zoomLevel - 1, -WebInspector.Zoom.DefaultOffset); this._requestZoom(); }, _resetZoom: function() { this._zoomLevel = 0; this._requestZoom(); }, _requestZoom: function() { WebInspector.settings.zoomLevel.set(this._zoomLevel); var index = this._zoomLevel + WebInspector.Zoom.DefaultOffset; index = Math.min(WebInspector.Zoom.Table.length - 1, index); index = Math.max(0, index); InspectorFrontendHost.setZoomFactor(WebInspector.Zoom.Table[index]); }, toggleSearchingForNode: function() { var enabled = !this._nodeSearchButton.toggled; function callback(error) { if (!error) this._nodeSearchButton.toggled = enabled; } WebInspector.domAgent.setInspectModeEnabled(enabled, callback.bind(this)); }, _profilesLinkifier: function(title) { var profileStringMatches = WebInspector.ProfileURLRegExp.exec(title); if (profileStringMatches) { var profilesPanel = WebInspector.panel("profiles"); title = WebInspector.ProfilesPanel._instance.displayTitleForProfileLink(profileStringMatches[2], profileStringMatches[1]); } return title; }, _debuggerPaused: function() { WebInspector.panel("scripts"); } } WebInspector.Events = { InspectorLoaded: "InspectorLoaded", InspectorClosing: "InspectorClosing" } {(function parseQueryParameters() { WebInspector.queryParamsObject = {}; var queryParams = window.location.search; if (!queryParams) return; var params = queryParams.substring(1).split("&"); for (var i = 0; i < params.length; ++i) { var pair = params[i].split("="); WebInspector.queryParamsObject[pair[0]] = pair[1]; } })();} WebInspector.loaded = function() { InspectorBackend.loadFromJSONIfNeeded("../Inspector.json"); WebInspector.dockController = new WebInspector.DockController(); if (WebInspector.WorkerManager.isDedicatedWorkerFrontend()) { WebInspector.doLoadedDone(); return; } var ws; if ("ws" in WebInspector.queryParamsObject) ws = "ws://" + WebInspector.queryParamsObject.ws; else if ("page" in WebInspector.queryParamsObject) { var page = WebInspector.queryParamsObject.page; var host = "host" in WebInspector.queryParamsObject ? WebInspector.queryParamsObject.host : window.location.host; ws = "ws://" + host + "/devtools/page/" + page; } if (ws) { WebInspector.socket = new WebSocket(ws); WebInspector.socket.onmessage = function(message) { InspectorBackend.dispatch(message.data); } WebInspector.socket.onerror = function(error) { console.error(error); } WebInspector.socket.onopen = function() { InspectorFrontendHost.sendMessageToBackend = WebInspector.socket.send.bind(WebInspector.socket); WebInspector.doLoadedDone(); } WebInspector.socket.onclose = function() { if (!WebInspector.socket._detachReason) (new WebInspector.RemoteDebuggingTerminatedScreen("websocket_closed")).showModal(); } return; } WebInspector.doLoadedDone(); if (InspectorFrontendHost.isStub) { InspectorFrontendAPI.dispatchQueryParameters(); WebInspector._doLoadedDoneWithCapabilities(); } } WebInspector.doLoadedDone = function() { WebInspector.installPortStyles(); if (WebInspector.socket) document.body.addStyleClass("remote"); if (WebInspector.queryParamsObject.toolbarColor && WebInspector.queryParamsObject.textColor) WebInspector.setToolbarColors(WebInspector.queryParamsObject.toolbarColor, WebInspector.queryParamsObject.textColor); InspectorFrontendHost.loaded(); WebInspector.WorkerManager.loaded(); DebuggerAgent.causesRecompilation(WebInspector._initializeCapability.bind(WebInspector, "debuggerCausesRecompilation", null)); DebuggerAgent.supportsSeparateScriptCompilationAndExecution(WebInspector._initializeCapability.bind(WebInspector, "separateScriptCompilationAndExecutionEnabled", null)); ProfilerAgent.causesRecompilation(WebInspector._initializeCapability.bind(WebInspector, "profilerCausesRecompilation", null)); ProfilerAgent.isSampling(WebInspector._initializeCapability.bind(WebInspector, "samplingCPUProfiler", null)); ProfilerAgent.hasHeapProfiler(WebInspector._initializeCapability.bind(WebInspector, "heapProfilerPresent", null)); TimelineAgent.supportsFrameInstrumentation(WebInspector._initializeCapability.bind(WebInspector, "timelineSupportsFrameInstrumentation", null)); TimelineAgent.canMonitorMainThread(WebInspector._initializeCapability.bind(WebInspector, "timelineCanMonitorMainThread", null)); PageAgent.canShowFPSCounter(WebInspector._initializeCapability.bind(WebInspector, "canShowFPSCounter", null)); PageAgent.canOverrideDeviceMetrics(WebInspector._initializeCapability.bind(WebInspector, "canOverrideDeviceMetrics", null)); PageAgent.canOverrideGeolocation(WebInspector._initializeCapability.bind(WebInspector, "canOverrideGeolocation", null)); PageAgent.canOverrideDeviceOrientation(WebInspector._initializeCapability.bind(WebInspector, "canOverrideDeviceOrientation", WebInspector._doLoadedDoneWithCapabilities.bind(WebInspector))); } WebInspector._doLoadedDoneWithCapabilities = function() { WebInspector.shortcutsScreen = new WebInspector.ShortcutsScreen(); this._registerShortcuts(); WebInspector.shortcutsScreen.section(WebInspector.UIString("Console")); WebInspector.shortcutsScreen.section(WebInspector.UIString("Elements Panel")); var panelDescriptors = this._panelDescriptors(); for (var i = 0; i < panelDescriptors.length; ++i) panelDescriptors[i].registerShortcuts(); this.console = new WebInspector.ConsoleModel(); this.console.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._updateErrorAndWarningCounts, this); this.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._updateErrorAndWarningCounts, this); this.console.addEventListener(WebInspector.ConsoleModel.Events.RepeatCountUpdated, this._updateErrorAndWarningCounts, this); WebInspector.CSSMetadata.requestCSSShorthandData(); this.drawer = new WebInspector.Drawer(); this.networkManager = new WebInspector.NetworkManager(); this.resourceTreeModel = new WebInspector.ResourceTreeModel(this.networkManager); this.debuggerModel = new WebInspector.DebuggerModel(); this.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this); this.networkLog = new WebInspector.NetworkLog(); this.domAgent = new WebInspector.DOMAgent(); this.runtimeModel = new WebInspector.RuntimeModel(this.resourceTreeModel); this.consoleView = new WebInspector.ConsoleView(WebInspector.WorkerManager.isWorkerFrontend()); InspectorBackend.registerInspectorDispatcher(this); this.cssModel = new WebInspector.CSSStyleModel(); this.timelineManager = new WebInspector.TimelineManager(); this.userAgentSupport = new WebInspector.UserAgentSupport(); this.searchController = new WebInspector.SearchController(); this.advancedSearchController = new WebInspector.AdvancedSearchController(); this.settingsController = new WebInspector.SettingsController(); this.domBreakpointsSidebarPane = new WebInspector.DOMBreakpointsSidebarPane(); this._zoomLevel = WebInspector.settings.zoomLevel.get(); if (this._zoomLevel) this._requestZoom(); var autoselectPanel = WebInspector.UIString("a panel chosen automatically"); var openAnchorLocationSetting = WebInspector.settings.createSetting("openLinkHandler", autoselectPanel); this.openAnchorLocationRegistry = new WebInspector.HandlerRegistry(openAnchorLocationSetting); this.openAnchorLocationRegistry.registerHandler(autoselectPanel, function() { return false; }); this.networkWorkspaceProvider = new WebInspector.NetworkWorkspaceProvider(); this.workspace = new WebInspector.Workspace(); this.workspace.addProject("network", this.networkWorkspaceProvider); this.workspaceController = new WebInspector.WorkspaceController(this.workspace); this.breakpointManager = new WebInspector.BreakpointManager(WebInspector.settings.breakpoints, this.debuggerModel, this.workspace); this.scriptSnippetModel = new WebInspector.ScriptSnippetModel(this.workspace, this.networkWorkspaceProvider); new WebInspector.DebuggerScriptMapping(this.workspace, this.networkWorkspaceProvider); this.styleContentBinding = new WebInspector.StyleContentBinding(this.cssModel); new WebInspector.NetworkUISourceCodeProvider(this.workspace, this.networkWorkspaceProvider); new WebInspector.StylesSourceMapping(this.workspace); if (WebInspector.experimentsSettings.sass.isEnabled()) new WebInspector.SASSSourceMapping(this.workspace, this.networkWorkspaceProvider); new WebInspector.PresentationConsoleMessageHelper(this.workspace); this._createGlobalStatusBarItems(); this.toolbar = new WebInspector.Toolbar(); WebInspector.startBatchUpdate(); for (var i = 0; i < panelDescriptors.length; ++i) WebInspector.inspectorView.addPanel(panelDescriptors[i]); WebInspector.endBatchUpdate(); this.addMainEventListeners(document); WebInspector.registerLinkifierPlugin(this._profilesLinkifier.bind(this)); window.addEventListener("resize", this.windowResize.bind(this), true); var errorWarningCount = document.getElementById("error-warning-count"); errorWarningCount.addEventListener("click", this.showConsole.bind(this), false); this._updateErrorAndWarningCounts(); this.extensionServer.initExtensions(); this.console.enableAgent(); function showInitialPanel() { if (!WebInspector.inspectorView.currentPanel()) WebInspector.showPanel(WebInspector.settings.lastActivePanel.get()); } InspectorAgent.enable(showInitialPanel); this.databaseModel = new WebInspector.DatabaseModel(); this.domStorageModel = new WebInspector.DOMStorageModel(); if (!Capabilities.profilerCausesRecompilation || WebInspector.settings.profilerEnabled.get()) ProfilerAgent.enable(); if (WebInspector.settings.showPaintRects.get()) PageAgent.setShowPaintRects(true); if (WebInspector.settings.javaScriptDisabled.get()) PageAgent.setScriptExecutionDisabled(true); if (WebInspector.settings.showFPSCounter.get()) PageAgent.setShowFPSCounter(true); this.domAgent._emulateTouchEventsChanged(); WebInspector.WorkerManager.loadCompleted(); InspectorFrontendAPI.loadCompleted(); WebInspector.notifications.dispatchEventToListeners(WebInspector.Events.InspectorLoaded); } var windowLoaded = function() { var localizedStringsURL = InspectorFrontendHost.localizedStringsURL(); if (localizedStringsURL) { var localizedStringsScriptElement = document.createElement("script"); localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false); localizedStringsScriptElement.type = "text/javascript"; localizedStringsScriptElement.src = localizedStringsURL; document.head.appendChild(localizedStringsScriptElement); } else WebInspector.loaded(); window.removeEventListener("DOMContentLoaded", windowLoaded, false); delete windowLoaded; }; window.addEventListener("DOMContentLoaded", windowLoaded, false); var messagesToDispatch = []; WebInspector.dispatchQueueIsEmpty = function() { return messagesToDispatch.length == 0; } WebInspector.dispatch = function(message) { messagesToDispatch.push(message); setTimeout(function() { InspectorBackend.dispatch(messagesToDispatch.shift()); }, 0); } WebInspector.windowResize = function(event) { if (WebInspector.inspectorView) WebInspector.inspectorView.doResize(); if (WebInspector.drawer) WebInspector.drawer.resize(); if (WebInspector.toolbar) WebInspector.toolbar.resize(); if (WebInspector.settingsController) WebInspector.settingsController.resize(); } WebInspector.setDockingUnavailable = function(unavailable) { if (this.dockController) this.dockController.setDockingUnavailable(unavailable); } WebInspector.close = function(event) { if (this._isClosing) return; this._isClosing = true; this.notifications.dispatchEventToListeners(WebInspector.Events.InspectorClosing); InspectorFrontendHost.closeWindow(); } WebInspector.documentClick = function(event) { var anchor = event.target.enclosingNodeOrSelfWithNodeName("a"); if (!anchor || anchor.target === "_blank") return; event.consume(true); function followLink() { if (WebInspector.isBeingEdited(event.target) || WebInspector._showAnchorLocation(anchor)) return; const profileMatch = WebInspector.ProfileURLRegExp.exec(anchor.href); if (profileMatch) { WebInspector.showProfileForURL(anchor.href); return; } var parsedURL = anchor.href.asParsedURL(); if (parsedURL && parsedURL.scheme === "webkit-link-action") { if (parsedURL.host === "show-panel") { var panel = parsedURL.path.substring(1); if (WebInspector.panel(panel)) WebInspector.showPanel(panel); } return; } InspectorFrontendHost.openInNewTab(anchor.href); } if (WebInspector.followLinkTimeout) clearTimeout(WebInspector.followLinkTimeout); if (anchor.preventFollowOnDoubleClick) { if (event.detail === 1) WebInspector.followLinkTimeout = setTimeout(followLink, 333); return; } followLink(); } WebInspector.openResource = function(resourceURL, inResourcesPanel) { var resource = WebInspector.resourceForURL(resourceURL); if (inResourcesPanel && resource) WebInspector.showPanel("resources").showResource(resource); else InspectorFrontendHost.openInNewTab(resourceURL); } WebInspector._registerShortcuts = function() { var shortcut = WebInspector.KeyboardShortcut; var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("All Panels")); var keys = [ shortcut.makeDescriptor("[", shortcut.Modifiers.CtrlOrMeta), shortcut.makeDescriptor("]", shortcut.Modifiers.CtrlOrMeta) ]; section.addRelatedKeys(keys, WebInspector.UIString("Go to the panel to the left/right")); var keys = [ shortcut.makeDescriptor("[", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Alt), shortcut.makeDescriptor("]", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Alt) ]; section.addRelatedKeys(keys, WebInspector.UIString("Go back/forward in panel history")); section.addKey(shortcut.makeDescriptor(shortcut.Keys.Esc), WebInspector.UIString("Toggle console")); section.addKey(shortcut.makeDescriptor("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search")); var advancedSearchShortcut = WebInspector.AdvancedSearchController.createShortcut(); section.addKey(advancedSearchShortcut, WebInspector.UIString("Search across all sources")); var openResourceShortcut = WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta); section.addKey(openResourceShortcut, WebInspector.UIString("Go to source")); if (WebInspector.isMac()) { keys = [ shortcut.makeDescriptor("g", shortcut.Modifiers.Meta), shortcut.makeDescriptor("g", shortcut.Modifiers.Meta | shortcut.Modifiers.Shift) ]; section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous")); } var goToShortcut = WebInspector.GoToLineDialog.createShortcut(); section.addKey(goToShortcut, WebInspector.UIString("Go to line")); } WebInspector.documentKeyDown = function(event) { const helpKey = WebInspector.isMac() ? "U+003F" : "U+00BF"; if (event.keyIdentifier === "F1" || (event.keyIdentifier === helpKey && event.shiftKey && (!WebInspector.isBeingEdited(event.target) || event.metaKey))) { this.settingsController.showSettingsScreen(WebInspector.SettingsScreen.Tabs.Shortcuts); event.consume(true); return; } if (WebInspector.currentFocusElement() && WebInspector.currentFocusElement().handleKeyEvent) { WebInspector.currentFocusElement().handleKeyEvent(event); if (event.handled) { event.consume(true); return; } } if (WebInspector.inspectorView.currentPanel()) { WebInspector.inspectorView.currentPanel().handleShortcut(event); if (event.handled) { event.consume(true); return; } } if (WebInspector.searchController.handleShortcut(event)) return; if (WebInspector.advancedSearchController.handleShortcut(event)) return; switch (event.keyIdentifier) { case "U+004F": if (!event.shiftKey && !event.altKey && WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)) { WebInspector.showPanel("scripts").showGoToSourceDialog(); event.consume(true); } break; case "U+0052": if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)) { PageAgent.reload(event.shiftKey); event.consume(true); } break; case "F5": if (!WebInspector.isMac()) { PageAgent.reload(event.ctrlKey || event.shiftKey); event.consume(true); } break; } var isValidZoomShortcut = WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) && !event.altKey && !InspectorFrontendHost.isStub; switch (event.keyCode) { case 107: case 187: if (isValidZoomShortcut) { WebInspector._zoomIn(); event.consume(true); } break; case 109: case 189: if (isValidZoomShortcut) { WebInspector._zoomOut(); event.consume(true); } break; case 48: if (isValidZoomShortcut && !event.shiftKey) { WebInspector._resetZoom(); event.consume(true); } break; } if (event.keyIdentifier === "U+0043") { if (WebInspector.isMac()) var isNodeSearchKey = event.metaKey && !event.ctrlKey && !event.altKey && event.shiftKey; else var isNodeSearchKey = event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey; if (isNodeSearchKey) { this.toggleSearchingForNode(); event.consume(true); return; } return; } } WebInspector.postDocumentKeyDown = function(event) { if (event.handled) return; if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) { if (!this._toggleConsoleButton.toggled && WebInspector.drawer.visible) this.closeViewInDrawer(); else this._toggleConsoleButtonClicked(); } } WebInspector.documentCanCopy = function(event) { if (WebInspector.inspectorView.currentPanel() && WebInspector.inspectorView.currentPanel().handleCopyEvent) event.preventDefault(); } WebInspector.documentCopy = function(event) { if (WebInspector.inspectorView.currentPanel() && WebInspector.inspectorView.currentPanel().handleCopyEvent) WebInspector.inspectorView.currentPanel().handleCopyEvent(event); WebInspector.documentCopyEventFired(event); } WebInspector.documentCopyEventFired = function(event) { } WebInspector.contextMenuEventFired = function(event) { if (event.handled || event.target.hasStyleClass("popup-glasspane")) event.preventDefault(); } WebInspector.showConsole = function() { if (WebInspector._toggleConsoleButton && !WebInspector._toggleConsoleButton.toggled) { if (WebInspector.drawer.visible) this._closePreviousDrawerView(); WebInspector._toggleConsoleButtonClicked(); } } WebInspector.showPanel = function(panel) { return WebInspector.inspectorView.showPanel(panel); } WebInspector.panel = function(panel) { return WebInspector.inspectorView.panel(panel); } WebInspector.bringToFront = function() { InspectorFrontendHost.bringToFront(); } WebInspector.log = function(message, messageLevel, showConsole) { var self = this; function isLogAvailable() { return WebInspector.ConsoleMessage && WebInspector.RemoteObject && self.console; } function flushQueue() { var queued = WebInspector.log.queued; if (!queued) return; for (var i = 0; i < queued.length; ++i) logMessage(queued[i]); delete WebInspector.log.queued; } function flushQueueIfAvailable() { if (!isLogAvailable()) return; clearInterval(WebInspector.log.interval); delete WebInspector.log.interval; flushQueue(); } function logMessage(message) { var msg = WebInspector.ConsoleMessage.create( WebInspector.ConsoleMessage.MessageSource.Other, messageLevel || WebInspector.ConsoleMessage.MessageLevel.Debug, message); self.console.addMessage(msg); if (showConsole) WebInspector.showConsole(); } if (!isLogAvailable()) { if (!WebInspector.log.queued) WebInspector.log.queued = []; WebInspector.log.queued.push(message); if (!WebInspector.log.interval) WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000); return; } flushQueue(); logMessage(message); } WebInspector.showErrorMessage = function(error) { WebInspector.log(error, WebInspector.ConsoleMessage.MessageLevel.Error, true); } WebInspector.inspect = function(payload, hints) { var object = WebInspector.RemoteObject.fromPayload(payload); if (object.subtype === "node") { function callback(nodeId) { WebInspector._updateFocusedNode(nodeId); object.release(); } object.pushNodeToFrontend(callback); return; } if (hints.databaseId) WebInspector.showPanel("resources").selectDatabase(WebInspector.databaseModel.databaseForId(hints.databaseId)); else if (hints.domStorageId) WebInspector.showPanel("resources").selectDOMStorage(WebInspector.domStorageModel.storageForId(hints.domStorageId)); object.release(); } WebInspector.detached = function(reason) { WebInspector.socket._detachReason = reason; (new WebInspector.RemoteDebuggingTerminatedScreen(reason)).showModal(); } WebInspector._updateFocusedNode = function(nodeId) { if (WebInspector._nodeSearchButton.toggled) { InspectorFrontendHost.bringToFront(); WebInspector._nodeSearchButton.toggled = false; } WebInspector.showPanel("elements").revealAndSelectNode(nodeId); } WebInspector._showAnchorLocation = function(anchor) { if (WebInspector.openAnchorLocationRegistry.dispatch({ url: anchor.href, lineNumber: anchor.lineNumber})) return true; var preferredPanel = this.panels[anchor.preferredPanel]; if (preferredPanel && WebInspector._showAnchorLocationInPanel(anchor, preferredPanel)) return true; if (WebInspector._showAnchorLocationInPanel(anchor, this.panel("scripts"))) return true; if (WebInspector._showAnchorLocationInPanel(anchor, this.panel("resources"))) return true; if (WebInspector._showAnchorLocationInPanel(anchor, this.panel("network"))) return true; return false; } WebInspector._showAnchorLocationInPanel = function(anchor, panel) { if (!panel || !panel.canShowAnchorLocation(anchor)) return false; if (anchor.hasStyleClass("webkit-html-external-link")) { anchor.removeStyleClass("webkit-html-external-link"); anchor.addStyleClass("webkit-html-resource-link"); } WebInspector.inspectorView.showPanelForAnchorNavigation(panel); panel.showAnchorLocation(anchor); return true; } WebInspector.showProfileForURL = function(url) { WebInspector.showPanel("profiles").showProfileForURL(url); } WebInspector.evaluateInConsole = function(expression, showResultOnly) { this.showConsole(); this.consoleView.evaluateUsingTextPrompt(expression, showResultOnly); } WebInspector.addMainEventListeners = function(doc) { doc.addEventListener("keydown", this.documentKeyDown.bind(this), true); doc.addEventListener("keydown", this.postDocumentKeyDown.bind(this), false); doc.addEventListener("beforecopy", this.documentCanCopy.bind(this), true); doc.addEventListener("copy", this.documentCopy.bind(this), true); doc.addEventListener("contextmenu", this.contextMenuEventFired.bind(this), true); doc.addEventListener("click", this.documentClick.bind(this), true); } WebInspector.ProfileURLRegExp = /webkit-profile:\/\/(.+)\/(.+)#([0-9]+)/; WebInspector.Zoom = { Table: [0.25, 0.33, 0.5, 0.66, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5], DefaultOffset: 6 } WebInspector.UIString = function(string, vararg) { if (Preferences.localizeUI) { if (window.localizedStrings && string in window.localizedStrings) string = window.localizedStrings[string]; else { if (!(string in WebInspector._missingLocalizedStrings)) { console.warn("Localized string \"" + string + "\" not found."); WebInspector._missingLocalizedStrings[string] = true; } if (Preferences.showMissingLocalizedStrings) string += " (not localized)"; } } return String.vsprintf(string, Array.prototype.slice.call(arguments, 1)); } WebInspector._missingLocalizedStrings = {}; WebInspector.installDragHandle = function(element, elementDragStart, elementDrag, elementDragEnd, cursor) { element.addEventListener("mousedown", WebInspector._elementDragStart.bind(WebInspector, elementDragStart, elementDrag, elementDragEnd, cursor), false); } WebInspector._elementDragStart = function(elementDragStart, elementDrag, elementDragEnd, cursor, event) { if (event.button || (WebInspector.isMac() && event.ctrlKey)) return; if (WebInspector._elementDraggingEventListener) return; if (elementDragStart && !elementDragStart(event)) return; if (WebInspector._elementDraggingGlassPane) { WebInspector._elementDraggingGlassPane.dispose(); delete WebInspector._elementDraggingGlassPane; } var targetDocument = event.target.ownerDocument; WebInspector._elementDraggingEventListener = elementDrag; WebInspector._elementEndDraggingEventListener = elementDragEnd; WebInspector._mouseOutWhileDraggingTargetDocument = targetDocument; targetDocument.addEventListener("mousemove", WebInspector._elementDraggingEventListener, true); targetDocument.addEventListener("mouseup", WebInspector._elementDragEnd, true); targetDocument.addEventListener("mouseout", WebInspector._mouseOutWhileDragging, true); targetDocument.body.style.cursor = cursor; event.preventDefault(); } WebInspector._mouseOutWhileDragging = function() { WebInspector._unregisterMouseOutWhileDragging(); WebInspector._elementDraggingGlassPane = new WebInspector.GlassPane(); } WebInspector._unregisterMouseOutWhileDragging = function() { if (!WebInspector._mouseOutWhileDraggingTargetDocument) return; WebInspector._mouseOutWhileDraggingTargetDocument.removeEventListener("mouseout", WebInspector._mouseOutWhileDragging, true); delete WebInspector._mouseOutWhileDraggingTargetDocument; } WebInspector._elementDragEnd = function(event) { var targetDocument = event.target.ownerDocument; targetDocument.removeEventListener("mousemove", WebInspector._elementDraggingEventListener, true); targetDocument.removeEventListener("mouseup", WebInspector._elementDragEnd, true); WebInspector._unregisterMouseOutWhileDragging(); targetDocument.body.style.removeProperty("cursor"); if (WebInspector._elementDraggingGlassPane) WebInspector._elementDraggingGlassPane.dispose(); var elementDragEnd = WebInspector._elementEndDraggingEventListener; delete WebInspector._elementDraggingGlassPane; delete WebInspector._elementDraggingEventListener; delete WebInspector._elementEndDraggingEventListener; event.preventDefault(); if (elementDragEnd) elementDragEnd(event); } WebInspector.GlassPane = function() { this.element = document.createElement("div"); this.element.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;background-color:transparent;z-index:1000;"; this.element.id = "glass-pane-for-drag"; document.body.appendChild(this.element); } WebInspector.GlassPane.prototype = { dispose: function() { if (this.element.parentElement) this.element.parentElement.removeChild(this.element); } } WebInspector.animateStyle = function(animations, duration, callback) { var interval; var complete = 0; var hasCompleted = false; const intervalDuration = (1000 / 30); const animationsLength = animations.length; const propertyUnit = {opacity: ""}; const defaultUnit = "px"; function cubicInOut(t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; } for (var i = 0; i < animationsLength; ++i) { var animation = animations[i]; var element = null, start = null, end = null, key = null; for (key in animation) { if (key === "element") element = animation[key]; else if (key === "start") start = animation[key]; else if (key === "end") end = animation[key]; } if (!element || !end) continue; if (!start) { var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element); start = {}; for (key in end) start[key] = parseInt(computedStyle.getPropertyValue(key), 10); animation.start = start; } else for (key in start) element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit)); } function animateLoop() { if (hasCompleted) return; complete += intervalDuration; var next = complete + intervalDuration; for (var i = 0; i < animationsLength; ++i) { var animation = animations[i]; var element = animation.element; var start = animation.start; var end = animation.end; if (!element || !end) continue; var style = element.style; for (key in end) { var endValue = end[key]; if (next < duration) { var startValue = start[key]; var newValue = cubicInOut(complete, startValue, endValue - startValue, duration); style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit)); } else style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit)); } } if (complete >= duration) { hasCompleted = true; clearInterval(interval); if (callback) callback(); } } function forceComplete() { if (hasCompleted) return; complete = duration; animateLoop(); } function cancel() { hasCompleted = true; clearInterval(interval); } interval = setInterval(animateLoop, intervalDuration); return { cancel: cancel, forceComplete: forceComplete }; } WebInspector.isBeingEdited = function(element) { if (element.hasStyleClass("text-prompt") || element.nodeName === "INPUT") return true; if (!WebInspector.__editingCount) return false; while (element) { if (element.__editing) return true; element = element.parentElement; } return false; } WebInspector.markBeingEdited = function(element, value) { if (value) { if (element.__editing) return false; element.__editing = true; WebInspector.__editingCount = (WebInspector.__editingCount || 0) + 1; } else { if (!element.__editing) return false; delete element.__editing; --WebInspector.__editingCount; } return true; } WebInspector.EditingConfig = function(commitHandler, cancelHandler, context) { this.commitHandler = commitHandler; this.cancelHandler = cancelHandler this.context = context; this.pasteHandler; this.multiline; this.customFinishHandler; } WebInspector.EditingConfig.prototype = { setPasteHandler: function(pasteHandler) { this.pasteHandler = pasteHandler; }, setMultiline: function(multiline) { this.multiline = multiline; }, setCustomFinishHandler: function(customFinishHandler) { this.customFinishHandler = customFinishHandler; } } WebInspector.CSSNumberRegex = /^(-?(?:\d+(?:\.\d+)?|\.\d+))$/; WebInspector.StyleValueDelimiters = " \xA0\t\n\"':;,/()"; WebInspector._valueModificationDirection = function(event) { var direction = null; if (event.type === "mousewheel") { if (event.wheelDeltaY > 0) direction = "Up"; else if (event.wheelDeltaY < 0) direction = "Down"; } else { if (event.keyIdentifier === "Up" || event.keyIdentifier === "PageUp") direction = "Up"; else if (event.keyIdentifier === "Down" || event.keyIdentifier === "PageDown") direction = "Down"; } return direction; } WebInspector._modifiedHexValue = function(hexString, event) { var direction = WebInspector._valueModificationDirection(event); if (!direction) return hexString; var number = parseInt(hexString, 16); if (isNaN(number) || !isFinite(number)) return hexString; var maxValue = Math.pow(16, hexString.length) - 1; var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel"); var delta; if (arrowKeyOrMouseWheelEvent) delta = (direction === "Up") ? 1 : -1; else delta = (event.keyIdentifier === "PageUp") ? 16 : -16; if (event.shiftKey) delta *= 16; var result = number + delta; if (result < 0) result = 0; else if (result > maxValue) return hexString; var resultString = result.toString(16).toUpperCase(); for (var i = 0, lengthDelta = hexString.length - resultString.length; i < lengthDelta; ++i) resultString = "0" + resultString; return resultString; } WebInspector._modifiedFloatNumber = function(number, event) { var direction = WebInspector._valueModificationDirection(event); if (!direction) return number; var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel"); var changeAmount = 1; if (event.shiftKey && !arrowKeyOrMouseWheelEvent) changeAmount = 100; else if (event.shiftKey || !arrowKeyOrMouseWheelEvent) changeAmount = 10; else if (event.altKey) changeAmount = 0.1; if (direction === "Down") changeAmount *= -1; var result = Number((number + changeAmount).toFixed(6)); if (!String(result).match(WebInspector.CSSNumberRegex)) return null; return result; } WebInspector.handleElementValueModifications = function(event, element, finishHandler, suggestionHandler, customNumberHandler) { var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel"); var pageKeyPressed = (event.keyIdentifier === "PageUp" || event.keyIdentifier === "PageDown"); if (!arrowKeyOrMouseWheelEvent && !pageKeyPressed) return false; var selection = window.getSelection(); if (!selection.rangeCount) return false; var selectionRange = selection.getRangeAt(0); if (!selectionRange.commonAncestorContainer.isSelfOrDescendant(element)) return false; var originalValue = element.textContent; var wordRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, WebInspector.StyleValueDelimiters, element); var wordString = wordRange.toString(); if (suggestionHandler && suggestionHandler(wordString)) return false; var replacementString; var prefix, suffix, number; var matches; matches = /(.*#)([\da-fA-F]+)(.*)/.exec(wordString); if (matches && matches.length) { prefix = matches[1]; suffix = matches[3]; number = WebInspector._modifiedHexValue(matches[2], event); if (customNumberHandler) number = customNumberHandler(number); replacementString = prefix + number + suffix; } else { matches = /(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString); if (matches && matches.length) { prefix = matches[1]; suffix = matches[3]; number = WebInspector._modifiedFloatNumber(parseFloat(matches[2]), event); if (number === null) return false; if (customNumberHandler) number = customNumberHandler(number); replacementString = prefix + number + suffix; } } if (replacementString) { var replacementTextNode = document.createTextNode(replacementString); wordRange.deleteContents(); wordRange.insertNode(replacementTextNode); var finalSelectionRange = document.createRange(); finalSelectionRange.setStart(replacementTextNode, 0); finalSelectionRange.setEnd(replacementTextNode, replacementString.length); selection.removeAllRanges(); selection.addRange(finalSelectionRange); event.handled = true; event.preventDefault(); if (finishHandler) finishHandler(originalValue, replacementString); return true; } return false; } WebInspector.startEditing = function(element, config) { if (!WebInspector.markBeingEdited(element, true)) return null; config = config || new WebInspector.EditingConfig(function() {}, function() {}); var committedCallback = config.commitHandler; var cancelledCallback = config.cancelHandler; var pasteCallback = config.pasteHandler; var context = config.context; var oldText = getContent(element); var moveDirection = ""; element.addStyleClass("editing"); var oldTabIndex = element.getAttribute("tabIndex"); if (typeof oldTabIndex !== "number" || oldTabIndex < 0) element.tabIndex = 0; function blurEventListener() { editingCommitted.call(element); } function getContent(element) { if (element.tagName === "INPUT" && element.type === "text") return element.value; else return element.textContent; } function cleanUpAfterEditing() { WebInspector.markBeingEdited(element, false); this.removeStyleClass("editing"); if (typeof oldTabIndex !== "number") element.removeAttribute("tabIndex"); else this.tabIndex = oldTabIndex; this.scrollTop = 0; this.scrollLeft = 0; element.removeEventListener("blur", blurEventListener, false); element.removeEventListener("keydown", keyDownEventListener, true); if (pasteCallback) element.removeEventListener("paste", pasteEventListener, true); WebInspector.restoreFocusFromElement(element); } function editingCancelled() { if (this.tagName === "INPUT" && this.type === "text") this.value = oldText; else this.textContent = oldText; cleanUpAfterEditing.call(this); cancelledCallback(this, context); } function editingCommitted() { cleanUpAfterEditing.call(this); committedCallback(this, getContent(this), oldText, context, moveDirection); } function defaultFinishHandler(event) { var isMetaOrCtrl = WebInspector.isMac() ? event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey : event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey; if (isEnterKey(event) && (event.isMetaOrCtrlForTest || !config.multiline || isMetaOrCtrl)) return "commit"; else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B") return "cancel"; else if (event.keyIdentifier === "U+0009") return "move-" + (event.shiftKey ? "backward" : "forward"); } function handleEditingResult(result, event) { if (result === "commit") { editingCommitted.call(element); event.consume(true); } else if (result === "cancel") { editingCancelled.call(element); event.consume(true); } else if (result && result.startsWith("move-")) { moveDirection = result.substring(5); if (event.keyIdentifier !== "U+0009") blurEventListener(); } } function pasteEventListener(event) { var result = pasteCallback(event); handleEditingResult(result, event); } function keyDownEventListener(event) { var handler = config.customFinishHandler || defaultFinishHandler; var result = handler(event); handleEditingResult(result, event); } element.addEventListener("blur", blurEventListener, false); element.addEventListener("keydown", keyDownEventListener, true); if (pasteCallback) element.addEventListener("paste", pasteEventListener, true); WebInspector.setCurrentFocusElement(element); return { cancel: editingCancelled.bind(element), commit: editingCommitted.bind(element) }; } Number.secondsToString = function(seconds, higherResolution) { if (!isFinite(seconds)) return "-"; if (seconds === 0) return "0"; var ms = seconds * 1000; if (higherResolution && ms < 1000) return WebInspector.UIString("%.3f\u2009ms", ms); else if (ms < 1000) return WebInspector.UIString("%.0f\u2009ms", ms); if (seconds < 60) return WebInspector.UIString("%.2f\u2009s", seconds); var minutes = seconds / 60; if (minutes < 60) return WebInspector.UIString("%.1f\u2009min", minutes); var hours = minutes / 60; if (hours < 24) return WebInspector.UIString("%.1f\u2009hrs", hours); var days = hours / 24; return WebInspector.UIString("%.1f\u2009days", days); } Number.bytesToString = function(bytes) { if (bytes < 1024) return WebInspector.UIString("%.0f\u2009B", bytes); var kilobytes = bytes / 1024; if (kilobytes < 100) return WebInspector.UIString("%.1f\u2009KB", kilobytes); if (kilobytes < 1024) return WebInspector.UIString("%.0f\u2009KB", kilobytes); var megabytes = kilobytes / 1024; if (megabytes < 100) return WebInspector.UIString("%.1f\u2009MB", megabytes); else return WebInspector.UIString("%.0f\u2009MB", megabytes); } Number.withThousandsSeparator = function(num) { var str = num + ""; var re = /(\d+)(\d{3})/; while (str.match(re)) str = str.replace(re, "$1\u2009$2"); return str; } WebInspector.useLowerCaseMenuTitles = function() { return WebInspector.platform() === "windows" && Preferences.useLowerCaseMenuTitlesOnWindows; } WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append) { return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append); } WebInspector.openLinkExternallyLabel = function() { return WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open link in new tab" : "Open Link in New Tab"); } WebInspector.copyLinkAddressLabel = function() { return WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy link address" : "Copy Link Address"); } WebInspector.platform = function() { if (!WebInspector._platform) WebInspector._platform = InspectorFrontendHost.platform(); return WebInspector._platform; } WebInspector.isMac = function() { if (typeof WebInspector._isMac === "undefined") WebInspector._isMac = WebInspector.platform() === "mac"; return WebInspector._isMac; } WebInspector.isWin = function() { if (typeof WebInspector._isWin === "undefined") WebInspector._isWin = WebInspector.platform() === "windows"; return WebInspector._isWin; } WebInspector.PlatformFlavor = { WindowsVista: "windows-vista", MacTiger: "mac-tiger", MacLeopard: "mac-leopard", MacSnowLeopard: "mac-snowleopard", MacLion: "mac-lion", MacMountainLion: "mac-mountain-lion" } WebInspector.platformFlavor = function() { function detectFlavor() { const userAgent = navigator.userAgent; if (WebInspector.platform() === "windows") { var match = userAgent.match(/Windows NT (\d+)\.(?:\d+)/); if (match && match[1] >= 6) return WebInspector.PlatformFlavor.WindowsVista; return null; } else if (WebInspector.platform() === "mac") { var match = userAgent.match(/Mac OS X\s*(?:(\d+)_(\d+))?/); if (!match || match[1] != 10) return WebInspector.PlatformFlavor.MacSnowLeopard; switch (Number(match[2])) { case 4: return WebInspector.PlatformFlavor.MacTiger; case 5: return WebInspector.PlatformFlavor.MacLeopard; case 6: return WebInspector.PlatformFlavor.MacSnowLeopard; case 7: return WebInspector.PlatformFlavor.MacLion; case 8: return WebInspector.PlatformFlavor.MacMountainLion; default: return ""; } } } if (!WebInspector._platformFlavor) WebInspector._platformFlavor = detectFlavor(); return WebInspector._platformFlavor; } WebInspector.port = function() { if (!WebInspector._port) WebInspector._port = InspectorFrontendHost.port(); return WebInspector._port; } WebInspector.installPortStyles = function() { var platform = WebInspector.platform(); document.body.addStyleClass("platform-" + platform); var flavor = WebInspector.platformFlavor(); if (flavor) document.body.addStyleClass("platform-" + flavor); var port = WebInspector.port(); document.body.addStyleClass("port-" + port); } WebInspector._windowFocused = function(event) { if (event.target.document.nodeType === Node.DOCUMENT_NODE) document.body.removeStyleClass("inactive"); } WebInspector._windowBlurred = function(event) { if (event.target.document.nodeType === Node.DOCUMENT_NODE) document.body.addStyleClass("inactive"); } WebInspector.previousFocusElement = function() { return WebInspector._previousFocusElement; } WebInspector.currentFocusElement = function() { return WebInspector._currentFocusElement; } WebInspector._focusChanged = function(event) { WebInspector.setCurrentFocusElement(event.target); } WebInspector._textInputTypes = ["text", "search", "tel", "url", "email", "password"].keySet(); WebInspector._isTextEditingElement = function(element) { if (element instanceof HTMLInputElement) return element.type in WebInspector._textInputTypes; if (element instanceof HTMLTextAreaElement) return true; return false; } WebInspector.setCurrentFocusElement = function(x) { if (WebInspector._currentFocusElement !== x) WebInspector._previousFocusElement = WebInspector._currentFocusElement; WebInspector._currentFocusElement = x; if (WebInspector._currentFocusElement) { WebInspector._currentFocusElement.focus(); var selection = window.getSelection(); if (!WebInspector._isTextEditingElement(WebInspector._currentFocusElement) && selection.isCollapsed && !WebInspector._currentFocusElement.isInsertionCaretInside()) { var selectionRange = WebInspector._currentFocusElement.ownerDocument.createRange(); selectionRange.setStart(WebInspector._currentFocusElement, 0); selectionRange.setEnd(WebInspector._currentFocusElement, 0); selection.removeAllRanges(); selection.addRange(selectionRange); } } else if (WebInspector._previousFocusElement) WebInspector._previousFocusElement.blur(); } WebInspector.restoreFocusFromElement = function(element) { if (element && element.isSelfOrAncestor(WebInspector.currentFocusElement())) WebInspector.setCurrentFocusElement(WebInspector.previousFocusElement()); } WebInspector.setToolbarColors = function(backgroundColor, color) { if (!WebInspector._themeStyleElement) { WebInspector._themeStyleElement = document.createElement("style"); document.head.appendChild(WebInspector._themeStyleElement); } WebInspector._themeStyleElement.textContent = "#toolbar {\ background-image: none !important;\ background-color: " + backgroundColor + " !important;\ }\ \ .toolbar-label {\ color: " + color + " !important;\ text-shadow: none;\ }"; } WebInspector.resetToolbarColors = function() { if (WebInspector._themeStyleElement) WebInspector._themeStyleElement.textContent = ""; } WebInspector.highlightSearchResult = function(element, offset, length, domChanges) { var result = WebInspector.highlightSearchResults(element, [{offset: offset, length: length }], domChanges); return result.length ? result[0] : null; } WebInspector.highlightSearchResults = function(element, resultRanges, changes) { return WebInspector.highlightRangesWithStyleClass(element, resultRanges, "webkit-search-result", changes); } WebInspector.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes) { changes = changes || []; var highlightNodes = []; var lineText = element.textContent; var ownerDocument = element.ownerDocument; var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var snapshotLength = textNodeSnapshot.snapshotLength; if (snapshotLength === 0) return highlightNodes; var nodeRanges = []; var rangeEndOffset = 0; for (var i = 0; i < snapshotLength; ++i) { var range = {}; range.offset = rangeEndOffset; range.length = textNodeSnapshot.snapshotItem(i).textContent.length; rangeEndOffset = range.offset + range.length; nodeRanges.push(range); } var startIndex = 0; for (var i = 0; i < resultRanges.length; ++i) { var startOffset = resultRanges[i].offset; var endOffset = startOffset + resultRanges[i].length; while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset) startIndex++; var endIndex = startIndex; while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset) endIndex++; if (endIndex === snapshotLength) break; var highlightNode = ownerDocument.createElement("span"); highlightNode.className = styleClass; highlightNode.textContent = lineText.substring(startOffset, endOffset); var lastTextNode = textNodeSnapshot.snapshotItem(endIndex); var lastText = lastTextNode.textContent; lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset); changes.push({ node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent }); if (startIndex === endIndex) { lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode); changes.push({ node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement }); highlightNodes.push(highlightNode); var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset)); lastTextNode.parentElement.insertBefore(prefixNode, highlightNode); changes.push({ node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement }); } else { var firstTextNode = textNodeSnapshot.snapshotItem(startIndex); var firstText = firstTextNode.textContent; var anchorElement = firstTextNode.nextSibling; firstTextNode.parentElement.insertBefore(highlightNode, anchorElement); changes.push({ node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement }); highlightNodes.push(highlightNode); firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset); changes.push({ node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent }); for (var j = startIndex + 1; j < endIndex; j++) { var textNode = textNodeSnapshot.snapshotItem(j); var text = textNode.textContent; textNode.textContent = ""; changes.push({ node: textNode, type: "changed", oldText: text, newText: textNode.textContent }); } } startIndex = endIndex; nodeRanges[startIndex].offset = endOffset; nodeRanges[startIndex].length = lastTextNode.textContent.length; } return highlightNodes; } WebInspector.applyDomChanges = function(domChanges) { for (var i = 0, size = domChanges.length; i < size; ++i) { var entry = domChanges[i]; switch (entry.type) { case "added": entry.parent.insertBefore(entry.node, entry.nextSibling); break; case "changed": entry.node.textContent = entry.newText; break; } } } WebInspector.revertDomChanges = function(domChanges) { for (var i = domChanges.length - 1; i >= 0; --i) { var entry = domChanges[i]; switch (entry.type) { case "added": if (entry.node.parentElement) entry.node.parentElement.removeChild(entry.node); break; case "changed": entry.node.textContent = entry.oldText; break; } } } WebInspector._coalescingLevel = 0; WebInspector.startBatchUpdate = function() { if (!WebInspector._coalescingLevel) WebInspector._postUpdateHandlers = new Map(); WebInspector._coalescingLevel++; } WebInspector.endBatchUpdate = function() { if (--WebInspector._coalescingLevel) return; var handlers = WebInspector._postUpdateHandlers; delete WebInspector._postUpdateHandlers; var keys = handlers.keys(); for (var i = 0; i < keys.length; ++i) { var object = keys[i]; var methods = handlers.get(object).keys(); for (var j = 0; j < methods.length; ++j) methods[j].call(object); } } WebInspector.invokeOnceAfterBatchUpdate = function(object, method) { if (!WebInspector._coalescingLevel) { method.call(object); return; } var methods = WebInspector._postUpdateHandlers.get(object); if (!methods) { methods = new Map(); WebInspector._postUpdateHandlers.put(object, methods); } methods.put(method); } ;(function() { function windowLoaded() { window.addEventListener("focus", WebInspector._windowFocused, false); window.addEventListener("blur", WebInspector._windowBlurred, false); document.addEventListener("focus", WebInspector._focusChanged.bind(this), true); window.removeEventListener("DOMContentLoaded", windowLoaded, false); } window.addEventListener("DOMContentLoaded", windowLoaded, false); })(); function InspectorBackendClass() { this._lastCallbackId = 1; this._pendingResponsesCount = 0; this._callbacks = {}; this._domainDispatchers = {}; this._eventArgs = {}; this._replyArgs = {}; this.dumpInspectorTimeStats = false; this.dumpInspectorProtocolMessages = false; this._initialized = false; } InspectorBackendClass.prototype = { _wrap: function(callback, method) { var callbackId = this._lastCallbackId++; if (!callback) callback = function() {}; this._callbacks[callbackId] = callback; callback.methodName = method; if (this.dumpInspectorTimeStats) callback.sendRequestTime = Date.now(); return callbackId; }, registerCommand: function(method, signature, replyArgs) { var domainAndMethod = method.split("."); var agentName = domainAndMethod[0] + "Agent"; if (!window[agentName]) window[agentName] = {}; window[agentName][domainAndMethod[1]] = this._sendMessageToBackend.bind(this, method, signature); window[agentName][domainAndMethod[1]]["invoke"] = this._invoke.bind(this, method, signature); this._replyArgs[method] = replyArgs; this._initialized = true; }, registerEvent: function(eventName, params) { this._eventArgs[eventName] = params; this._initialized = true; }, _invoke: function(method, signature, args, callback) { this._wrapCallbackAndSendMessageObject(method, args, callback); }, _sendMessageToBackend: function(method, signature, vararg) { var args = Array.prototype.slice.call(arguments, 2); var callback = (args.length && typeof args[args.length - 1] === "function") ? args.pop() : null; var params = {}; var hasParams = false; for (var i = 0; i < signature.length; ++i) { var param = signature[i]; var paramName = param["name"]; var typeName = param["type"]; var optionalFlag = param["optional"]; if (!args.length && !optionalFlag) { console.error("Protocol Error: Invalid number of arguments for method '" + method + "' call. It must have the following arguments '" + JSON.stringify(signature) + "'."); return; } var value = args.shift(); if (optionalFlag && typeof value === "undefined") { continue; } if (typeof value !== typeName) { console.error("Protocol Error: Invalid type of argument '" + paramName + "' for method '" + method + "' call. It must be '" + typeName + "' but it is '" + typeof value + "'."); return; } params[paramName] = value; hasParams = true; } if (args.length === 1 && !callback) { if (typeof args[0] !== "undefined") { console.error("Protocol Error: Optional callback argument for method '" + method + "' call must be a function but its type is '" + typeof args[0] + "'."); return; } } this._wrapCallbackAndSendMessageObject(method, hasParams ? params : null, callback); }, _wrapCallbackAndSendMessageObject: function(method, params, callback) { var messageObject = {}; messageObject.method = method; if (params) messageObject.params = params; messageObject.id = this._wrap(callback, method); if (this.dumpInspectorProtocolMessages) console.log("frontend: " + JSON.stringify(messageObject)); ++this._pendingResponsesCount; this.sendMessageObjectToBackend(messageObject); }, sendMessageObjectToBackend: function(messageObject) { var message = JSON.stringify(messageObject); InspectorFrontendHost.sendMessageToBackend(message); }, registerDomainDispatcher: function(domain, dispatcher) { this._domainDispatchers[domain] = dispatcher; }, dispatch: function(message) { if (this.dumpInspectorProtocolMessages) console.log("backend: " + ((typeof message === "string") ? message : JSON.stringify(message))); var messageObject = (typeof message === "string") ? JSON.parse(message) : message; if ("id" in messageObject) { if (messageObject.error) { if (messageObject.error.code !== -32000) this.reportProtocolError(messageObject); } var callback = this._callbacks[messageObject.id]; if (callback) { var argumentsArray = []; if (messageObject.result) { var paramNames = this._replyArgs[callback.methodName]; if (paramNames) { for (var i = 0; i < paramNames.length; ++i) argumentsArray.push(messageObject.result[paramNames[i]]); } } var processingStartTime; if (this.dumpInspectorTimeStats && callback.methodName) processingStartTime = Date.now(); argumentsArray.unshift(messageObject.error ? messageObject.error.message : null); callback.apply(null, argumentsArray); --this._pendingResponsesCount; delete this._callbacks[messageObject.id]; if (this.dumpInspectorTimeStats && callback.methodName) console.log("time-stats: " + callback.methodName + " = " + (processingStartTime - callback.sendRequestTime) + " + " + (Date.now() - processingStartTime)); } if (this._scripts && !this._pendingResponsesCount) this.runAfterPendingDispatches(); return; } else { var method = messageObject.method.split("."); var domainName = method[0]; var functionName = method[1]; if (!(domainName in this._domainDispatchers)) { console.error("Protocol Error: the message is for non-existing domain '" + domainName + "'"); return; } var dispatcher = this._domainDispatchers[domainName]; if (!(functionName in dispatcher)) { console.error("Protocol Error: Attempted to dispatch an unimplemented method '" + messageObject.method + "'"); return; } if (!this._eventArgs[messageObject.method]) { console.error("Protocol Error: Attempted to dispatch an unspecified method '" + messageObject.method + "'"); return; } var params = []; if (messageObject.params) { var paramNames = this._eventArgs[messageObject.method]; for (var i = 0; i < paramNames.length; ++i) params.push(messageObject.params[paramNames[i]]); } var processingStartTime; if (this.dumpInspectorTimeStats) processingStartTime = Date.now(); dispatcher[functionName].apply(dispatcher, params); if (this.dumpInspectorTimeStats) console.log("time-stats: " + messageObject.method + " = " + (Date.now() - processingStartTime)); } }, reportProtocolError: function(messageObject) { console.error("Request with id = " + messageObject.id + " failed. " + messageObject.error); }, runAfterPendingDispatches: function(script) { if (!this._scripts) this._scripts = []; if (script) this._scripts.push(script); if (!this._pendingResponsesCount) { var scripts = this._scripts; this._scripts = [] for (var id = 0; id < scripts.length; ++id) scripts[id].call(this); } }, loadFromJSONIfNeeded: function(jsonUrl) { if (this._initialized) return; var xhr = new XMLHttpRequest(); xhr.open("GET", jsonUrl, false); xhr.send(null); var schema = JSON.parse(xhr.responseText); var jsTypes = { integer: "number", array: "object" }; var rawTypes = {}; var domains = schema["domains"]; for (var i = 0; i < domains.length; ++i) { var domain = domains[i]; for (var j = 0; domain.types && j < domain.types.length; ++j) { var type = domain.types[j]; rawTypes[domain.domain + "." + type.id] = jsTypes[type.type] || type.type; } } var result = []; for (var i = 0; i < domains.length; ++i) { var domain = domains[i]; var commands = domain["commands"] || []; for (var j = 0; j < commands.length; ++j) { var command = commands[j]; var parameters = command["parameters"]; var paramsText = []; for (var k = 0; parameters && k < parameters.length; ++k) { var parameter = parameters[k]; var type; if (parameter.type) type = jsTypes[parameter.type] || parameter.type; else { var ref = parameter["$ref"]; if (ref.indexOf(".") !== -1) type = rawTypes[ref]; else type = rawTypes[domain.domain + "." + ref]; } var text = "{\"name\": \"" + parameter.name + "\", \"type\": \"" + type + "\", \"optional\": " + (parameter.optional ? "true" : "false") + "}"; paramsText.push(text); } var returnsText = []; var returns = command["returns"] || []; for (var k = 0; k < returns.length; ++k) { var parameter = returns[k]; returnsText.push("\"" + parameter.name + "\""); } result.push("InspectorBackend.registerCommand(\"" + domain.domain + "." + command.name + "\", [" + paramsText.join(", ") + "], [" + returnsText.join(", ") + "]);"); } for (var j = 0; domain.events && j < domain.events.length; ++j) { var event = domain.events[j]; var paramsText = []; for (var k = 0; event.parameters && k < event.parameters.length; ++k) { var parameter = event.parameters[k]; paramsText.push("\"" + parameter.name + "\""); } result.push("InspectorBackend.registerEvent(\"" + domain.domain + "." + event.name + "\", [" + paramsText.join(", ") + "]);"); } result.push("InspectorBackend.register" + domain.domain + "Dispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, \"" + domain.domain + "\");"); } eval(result.join("\n")); } } InspectorBackend = new InspectorBackendClass(); InspectorBackend.registerInspectorDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Inspector"); InspectorBackend.registerEvent("Inspector.evaluateForTestInFrontend", ["testCallId", "script"]); InspectorBackend.registerEvent("Inspector.inspect", ["object", "hints"]); InspectorBackend.registerEvent("Inspector.detached", ["reason"]); InspectorBackend.registerCommand("Inspector.enable", [], []); InspectorBackend.registerCommand("Inspector.disable", [], []); InspectorBackend.registerMemoryDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Memory"); InspectorBackend.registerCommand("Memory.getDOMNodeCount", [], ["domGroups", "strings"]); InspectorBackend.registerCommand("Memory.getProcessMemoryDistribution", [{"name": "reportGraph", "type": "boolean", "optional": true}], ["distribution", "graph"]); InspectorBackend.registerPageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Page"); InspectorBackend.registerEvent("Page.domContentEventFired", ["timestamp"]); InspectorBackend.registerEvent("Page.loadEventFired", ["timestamp"]); InspectorBackend.registerEvent("Page.frameNavigated", ["frame"]); InspectorBackend.registerEvent("Page.frameDetached", ["frameId"]); InspectorBackend.registerCommand("Page.enable", [], []); InspectorBackend.registerCommand("Page.disable", [], []); InspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad", [{"name": "scriptSource", "type": "string", "optional": false}], ["identifier"]); InspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad", [{"name": "identifier", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Page.reload", [{"name": "ignoreCache", "type": "boolean", "optional": true}, {"name": "scriptToEvaluateOnLoad", "type": "string", "optional": true}, {"name": "scriptPreprocessor", "type": "string", "optional": true}], []); InspectorBackend.registerCommand("Page.navigate", [{"name": "url", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Page.getCookies", [], ["cookies", "cookiesString"]); InspectorBackend.registerCommand("Page.deleteCookie", [{"name": "cookieName", "type": "string", "optional": false}, {"name": "domain", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Page.getResourceTree", [], ["frameTree"]); InspectorBackend.registerCommand("Page.getResourceContent", [{"name": "frameId", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}, {"name": "resourceId", "type": "string", "optional": true}], ["content", "base64Encoded"]); InspectorBackend.registerCommand("Page.searchInResource", [{"name": "frameId", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}, {"name": "query", "type": "string", "optional": false}, {"name": "caseSensitive", "type": "boolean", "optional": true}, {"name": "isRegex", "type": "boolean", "optional": true}], ["result"]); InspectorBackend.registerCommand("Page.searchInResources", [{"name": "text", "type": "string", "optional": false}, {"name": "caseSensitive", "type": "boolean", "optional": true}, {"name": "isRegex", "type": "boolean", "optional": true}], ["result"]); InspectorBackend.registerCommand("Page.setDocumentContent", [{"name": "frameId", "type": "string", "optional": false}, {"name": "html", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Page.canOverrideDeviceMetrics", [], ["result"]); InspectorBackend.registerCommand("Page.setDeviceMetricsOverride", [{"name": "width", "type": "number", "optional": false}, {"name": "height", "type": "number", "optional": false}, {"name": "fontScaleFactor", "type": "number", "optional": false}, {"name": "fitWindow", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Page.setShowPaintRects", [{"name": "result", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Page.canShowFPSCounter", [], ["show"]); InspectorBackend.registerCommand("Page.setShowFPSCounter", [{"name": "show", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Page.getScriptExecutionStatus", [], ["result"]); InspectorBackend.registerCommand("Page.setScriptExecutionDisabled", [{"name": "value", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Page.setGeolocationOverride", [{"name": "latitude", "type": "number", "optional": true}, {"name": "longitude", "type": "number", "optional": true}, {"name": "accuracy", "type": "number", "optional": true}], []); InspectorBackend.registerCommand("Page.clearGeolocationOverride", [], []); InspectorBackend.registerCommand("Page.canOverrideGeolocation", [], ["result"]); InspectorBackend.registerCommand("Page.setDeviceOrientationOverride", [{"name": "alpha", "type": "number", "optional": false}, {"name": "beta", "type": "number", "optional": false}, {"name": "gamma", "type": "number", "optional": false}], []); InspectorBackend.registerCommand("Page.clearDeviceOrientationOverride", [], []); InspectorBackend.registerCommand("Page.canOverrideDeviceOrientation", [], ["result"]); InspectorBackend.registerCommand("Page.setTouchEmulationEnabled", [{"name": "enabled", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Page.setEmulatedMedia", [{"name": "media", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Page.getCompositingBordersVisible", [], ["result"]); InspectorBackend.registerCommand("Page.setCompositingBordersVisible", [{"name": "visible", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Page.captureScreenshot", [], ["data"]); InspectorBackend.registerRuntimeDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Runtime"); InspectorBackend.registerEvent("Runtime.executionContextCreated", ["context"]); InspectorBackend.registerCommand("Runtime.evaluate", [{"name": "expression", "type": "string", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}, {"name": "includeCommandLineAPI", "type": "boolean", "optional": true}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}, {"name": "contextId", "type": "number", "optional": true}, {"name": "returnByValue", "type": "boolean", "optional": true}, {"name": "generatePreview", "type": "boolean", "optional": true}], ["result", "wasThrown"]); InspectorBackend.registerCommand("Runtime.callFunctionOn", [{"name": "objectId", "type": "string", "optional": false}, {"name": "functionDeclaration", "type": "string", "optional": false}, {"name": "arguments", "type": "object", "optional": true}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}, {"name": "returnByValue", "type": "boolean", "optional": true}, {"name": "generatePreview", "type": "boolean", "optional": true}], ["result", "wasThrown"]); InspectorBackend.registerCommand("Runtime.getProperties", [{"name": "objectId", "type": "string", "optional": false}, {"name": "ownProperties", "type": "boolean", "optional": true}], ["result", "internalProperties"]); InspectorBackend.registerCommand("Runtime.releaseObject", [{"name": "objectId", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Runtime.releaseObjectGroup", [{"name": "objectGroup", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Runtime.run", [], []); InspectorBackend.registerCommand("Runtime.enable", [], []); InspectorBackend.registerCommand("Runtime.disable", [], []); InspectorBackend.registerConsoleDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Console"); InspectorBackend.registerEvent("Console.messageAdded", ["message"]); InspectorBackend.registerEvent("Console.messageRepeatCountUpdated", ["count"]); InspectorBackend.registerEvent("Console.messagesCleared", []); InspectorBackend.registerCommand("Console.enable", [], []); InspectorBackend.registerCommand("Console.disable", [], []); InspectorBackend.registerCommand("Console.clearMessages", [], []); InspectorBackend.registerCommand("Console.setMonitoringXHREnabled", [{"name": "enabled", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Console.addInspectedNode", [{"name": "nodeId", "type": "number", "optional": false}], []); InspectorBackend.registerCommand("Console.addInspectedHeapObject", [{"name": "heapObjectId", "type": "number", "optional": false}], []); InspectorBackend.registerNetworkDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Network"); InspectorBackend.registerEvent("Network.requestWillBeSent", ["requestId", "frameId", "loaderId", "documentURL", "request", "timestamp", "initiator", "redirectResponse"]); InspectorBackend.registerEvent("Network.requestServedFromCache", ["requestId"]); InspectorBackend.registerEvent("Network.responseReceived", ["requestId", "frameId", "loaderId", "timestamp", "type", "response"]); InspectorBackend.registerEvent("Network.dataReceived", ["requestId", "timestamp", "dataLength", "encodedDataLength"]); InspectorBackend.registerEvent("Network.loadingFinished", ["requestId", "timestamp"]); InspectorBackend.registerEvent("Network.loadingFailed", ["requestId", "timestamp", "errorText", "canceled"]); InspectorBackend.registerEvent("Network.requestServedFromMemoryCache", ["requestId", "frameId", "loaderId", "documentURL", "timestamp", "initiator", "resource"]); InspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest", ["requestId", "timestamp", "request"]); InspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived", ["requestId", "timestamp", "response"]); InspectorBackend.registerEvent("Network.webSocketCreated", ["requestId", "url"]); InspectorBackend.registerEvent("Network.webSocketClosed", ["requestId", "timestamp"]); InspectorBackend.registerEvent("Network.webSocketFrameReceived", ["requestId", "timestamp", "response"]); InspectorBackend.registerEvent("Network.webSocketFrameError", ["requestId", "timestamp", "errorMessage"]); InspectorBackend.registerEvent("Network.webSocketFrameSent", ["requestId", "timestamp", "response"]); InspectorBackend.registerCommand("Network.enable", [], []); InspectorBackend.registerCommand("Network.disable", [], []); InspectorBackend.registerCommand("Network.setUserAgentOverride", [{"name": "userAgent", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Network.setExtraHTTPHeaders", [{"name": "headers", "type": "object", "optional": false}], []); InspectorBackend.registerCommand("Network.getResponseBody", [{"name": "requestId", "type": "string", "optional": false}], ["body", "base64Encoded"]); InspectorBackend.registerCommand("Network.replayXHR", [{"name": "requestId", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Network.canClearBrowserCache", [], ["result"]); InspectorBackend.registerCommand("Network.clearBrowserCache", [], []); InspectorBackend.registerCommand("Network.canClearBrowserCookies", [], ["result"]); InspectorBackend.registerCommand("Network.clearBrowserCookies", [], []); InspectorBackend.registerCommand("Network.setCacheDisabled", [{"name": "cacheDisabled", "type": "boolean", "optional": false}], []); InspectorBackend.registerDatabaseDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Database"); InspectorBackend.registerEvent("Database.addDatabase", ["database"]); InspectorBackend.registerCommand("Database.enable", [], []); InspectorBackend.registerCommand("Database.disable", [], []); InspectorBackend.registerCommand("Database.getDatabaseTableNames", [{"name": "databaseId", "type": "string", "optional": false}], ["tableNames"]); InspectorBackend.registerCommand("Database.executeSQL", [{"name": "databaseId", "type": "string", "optional": false}, {"name": "query", "type": "string", "optional": false}], ["columnNames", "values", "sqlError"]); InspectorBackend.registerIndexedDBDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "IndexedDB"); InspectorBackend.registerCommand("IndexedDB.enable", [], []); InspectorBackend.registerCommand("IndexedDB.disable", [], []); InspectorBackend.registerCommand("IndexedDB.requestDatabaseNamesForFrame", [{"name": "frameId", "type": "string", "optional": false}], ["securityOriginWithDatabaseNames"]); InspectorBackend.registerCommand("IndexedDB.requestDatabase", [{"name": "frameId", "type": "string", "optional": false}, {"name": "databaseName", "type": "string", "optional": false}], ["databaseWithObjectStores"]); InspectorBackend.registerCommand("IndexedDB.requestData", [{"name": "frameId", "type": "string", "optional": false}, {"name": "databaseName", "type": "string", "optional": false}, {"name": "objectStoreName", "type": "string", "optional": false}, {"name": "indexName", "type": "string", "optional": false}, {"name": "skipCount", "type": "number", "optional": false}, {"name": "pageSize", "type": "number", "optional": false}, {"name": "keyRange", "type": "object", "optional": true}], ["objectStoreDataEntries", "hasMore"]); InspectorBackend.registerDOMStorageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOMStorage"); InspectorBackend.registerEvent("DOMStorage.addDOMStorage", ["storage"]); InspectorBackend.registerEvent("DOMStorage.domStorageUpdated", ["storageId"]); InspectorBackend.registerCommand("DOMStorage.enable", [], []); InspectorBackend.registerCommand("DOMStorage.disable", [], []); InspectorBackend.registerCommand("DOMStorage.getDOMStorageEntries", [{"name": "storageId", "type": "string", "optional": false}], ["entries"]); InspectorBackend.registerCommand("DOMStorage.setDOMStorageItem", [{"name": "storageId", "type": "string", "optional": false}, {"name": "key", "type": "string", "optional": false}, {"name": "value", "type": "string", "optional": false}], ["success"]); InspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem", [{"name": "storageId", "type": "string", "optional": false}, {"name": "key", "type": "string", "optional": false}], ["success"]); InspectorBackend.registerApplicationCacheDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "ApplicationCache"); InspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated", ["frameId", "manifestURL", "status"]); InspectorBackend.registerEvent("ApplicationCache.networkStateUpdated", ["isNowOnline"]); InspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests", [], ["frameIds"]); InspectorBackend.registerCommand("ApplicationCache.enable", [], []); InspectorBackend.registerCommand("ApplicationCache.getManifestForFrame", [{"name": "frameId", "type": "string", "optional": false}], ["manifestURL"]); InspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame", [{"name": "frameId", "type": "string", "optional": false}], ["applicationCache"]); InspectorBackend.registerFileSystemDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "FileSystem"); InspectorBackend.registerCommand("FileSystem.enable", [], []); InspectorBackend.registerCommand("FileSystem.disable", [], []); InspectorBackend.registerCommand("FileSystem.requestFileSystemRoot", [{"name": "origin", "type": "string", "optional": false}, {"name": "type", "type": "string", "optional": false}], ["errorCode", "root"]); InspectorBackend.registerCommand("FileSystem.requestDirectoryContent", [{"name": "url", "type": "string", "optional": false}], ["errorCode", "entries"]); InspectorBackend.registerCommand("FileSystem.requestMetadata", [{"name": "url", "type": "string", "optional": false}], ["errorCode", "metadata"]); InspectorBackend.registerCommand("FileSystem.requestFileContent", [{"name": "url", "type": "string", "optional": false}, {"name": "readAsText", "type": "boolean", "optional": false}, {"name": "start", "type": "number", "optional": true}, {"name": "end", "type": "number", "optional": true}, {"name": "charset", "type": "string", "optional": true}], ["errorCode", "content", "charset"]); InspectorBackend.registerCommand("FileSystem.deleteEntry", [{"name": "url", "type": "string", "optional": false}], ["errorCode"]); InspectorBackend.registerDOMDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOM"); InspectorBackend.registerEvent("DOM.documentUpdated", []); InspectorBackend.registerEvent("DOM.setChildNodes", ["parentId", "nodes"]); InspectorBackend.registerEvent("DOM.attributeModified", ["nodeId", "name", "value"]); InspectorBackend.registerEvent("DOM.attributeRemoved", ["nodeId", "name"]); InspectorBackend.registerEvent("DOM.inlineStyleInvalidated", ["nodeIds"]); InspectorBackend.registerEvent("DOM.characterDataModified", ["nodeId", "characterData"]); InspectorBackend.registerEvent("DOM.childNodeCountUpdated", ["nodeId", "childNodeCount"]); InspectorBackend.registerEvent("DOM.childNodeInserted", ["parentNodeId", "previousNodeId", "node"]); InspectorBackend.registerEvent("DOM.childNodeRemoved", ["parentNodeId", "nodeId"]); InspectorBackend.registerEvent("DOM.shadowRootPushed", ["hostId", "root"]); InspectorBackend.registerEvent("DOM.shadowRootPopped", ["hostId", "rootId"]); InspectorBackend.registerCommand("DOM.getDocument", [], ["root"]); InspectorBackend.registerCommand("DOM.requestChildNodes", [{"name": "nodeId", "type": "number", "optional": false}], []); InspectorBackend.registerCommand("DOM.querySelector", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["nodeId"]); InspectorBackend.registerCommand("DOM.querySelectorAll", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["nodeIds"]); InspectorBackend.registerCommand("DOM.setNodeName", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}], ["nodeId"]); InspectorBackend.registerCommand("DOM.setNodeValue", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "value", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOM.removeNode", [{"name": "nodeId", "type": "number", "optional": false}], []); InspectorBackend.registerCommand("DOM.setAttributeValue", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}, {"name": "value", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOM.setAttributesAsText", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "text", "type": "string", "optional": false}, {"name": "name", "type": "string", "optional": true}], []); InspectorBackend.registerCommand("DOM.removeAttribute", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOM.getEventListenersForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["listeners"]); InspectorBackend.registerCommand("DOM.getOuterHTML", [{"name": "nodeId", "type": "number", "optional": false}], ["outerHTML"]); InspectorBackend.registerCommand("DOM.setOuterHTML", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "outerHTML", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOM.performSearch", [{"name": "query", "type": "string", "optional": false}], ["searchId", "resultCount"]); InspectorBackend.registerCommand("DOM.getSearchResults", [{"name": "searchId", "type": "string", "optional": false}, {"name": "fromIndex", "type": "number", "optional": false}, {"name": "toIndex", "type": "number", "optional": false}], ["nodeIds"]); InspectorBackend.registerCommand("DOM.discardSearchResults", [{"name": "searchId", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOM.requestNode", [{"name": "objectId", "type": "string", "optional": false}], ["nodeId"]); InspectorBackend.registerCommand("DOM.setInspectModeEnabled", [{"name": "enabled", "type": "boolean", "optional": false}, {"name": "highlightConfig", "type": "object", "optional": true}], []); InspectorBackend.registerCommand("DOM.highlightRect", [{"name": "x", "type": "number", "optional": false}, {"name": "y", "type": "number", "optional": false}, {"name": "width", "type": "number", "optional": false}, {"name": "height", "type": "number", "optional": false}, {"name": "color", "type": "object", "optional": true}, {"name": "outlineColor", "type": "object", "optional": true}], []); InspectorBackend.registerCommand("DOM.highlightNode", [{"name": "highlightConfig", "type": "object", "optional": false}, {"name": "nodeId", "type": "number", "optional": true}, {"name": "objectId", "type": "string", "optional": true}], []); InspectorBackend.registerCommand("DOM.hideHighlight", [], []); InspectorBackend.registerCommand("DOM.highlightFrame", [{"name": "frameId", "type": "string", "optional": false}, {"name": "contentColor", "type": "object", "optional": true}, {"name": "contentOutlineColor", "type": "object", "optional": true}], []); InspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend", [{"name": "path", "type": "string", "optional": false}], ["nodeId"]); InspectorBackend.registerCommand("DOM.resolveNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["object"]); InspectorBackend.registerCommand("DOM.getAttributes", [{"name": "nodeId", "type": "number", "optional": false}], ["attributes"]); InspectorBackend.registerCommand("DOM.moveTo", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "targetNodeId", "type": "number", "optional": false}, {"name": "insertBeforeNodeId", "type": "number", "optional": true}], ["nodeId"]); InspectorBackend.registerCommand("DOM.undo", [], []); InspectorBackend.registerCommand("DOM.redo", [], []); InspectorBackend.registerCommand("DOM.markUndoableState", [], []); InspectorBackend.registerCommand("DOM.focus", [{"name": "nodeId", "type": "number", "optional": false}], []); InspectorBackend.registerCSSDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "CSS"); InspectorBackend.registerEvent("CSS.mediaQueryResultChanged", []); InspectorBackend.registerEvent("CSS.styleSheetChanged", ["styleSheetId"]); InspectorBackend.registerEvent("CSS.namedFlowCreated", ["namedFlow"]); InspectorBackend.registerEvent("CSS.namedFlowRemoved", ["documentNodeId", "flowName"]); InspectorBackend.registerEvent("CSS.regionLayoutUpdated", ["namedFlow"]); InspectorBackend.registerCommand("CSS.enable", [], []); InspectorBackend.registerCommand("CSS.disable", [], []); InspectorBackend.registerCommand("CSS.getMatchedStylesForNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "includePseudo", "type": "boolean", "optional": true}, {"name": "includeInherited", "type": "boolean", "optional": true}], ["matchedCSSRules", "pseudoElements", "inherited"]); InspectorBackend.registerCommand("CSS.getInlineStylesForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["inlineStyle", "attributesStyle"]); InspectorBackend.registerCommand("CSS.getComputedStyleForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["computedStyle"]); InspectorBackend.registerCommand("CSS.getAllStyleSheets", [], ["headers"]); InspectorBackend.registerCommand("CSS.getStyleSheet", [{"name": "styleSheetId", "type": "string", "optional": false}], ["styleSheet"]); InspectorBackend.registerCommand("CSS.getStyleSheetText", [{"name": "styleSheetId", "type": "string", "optional": false}], ["text"]); InspectorBackend.registerCommand("CSS.setStyleSheetText", [{"name": "styleSheetId", "type": "string", "optional": false}, {"name": "text", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("CSS.setPropertyText", [{"name": "styleId", "type": "object", "optional": false}, {"name": "propertyIndex", "type": "number", "optional": false}, {"name": "text", "type": "string", "optional": false}, {"name": "overwrite", "type": "boolean", "optional": false}], ["style"]); InspectorBackend.registerCommand("CSS.toggleProperty", [{"name": "styleId", "type": "object", "optional": false}, {"name": "propertyIndex", "type": "number", "optional": false}, {"name": "disable", "type": "boolean", "optional": false}], ["style"]); InspectorBackend.registerCommand("CSS.setRuleSelector", [{"name": "ruleId", "type": "object", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["rule"]); InspectorBackend.registerCommand("CSS.addRule", [{"name": "contextNodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["rule"]); InspectorBackend.registerCommand("CSS.getSupportedCSSProperties", [], ["cssProperties"]); InspectorBackend.registerCommand("CSS.forcePseudoState", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "forcedPseudoClasses", "type": "object", "optional": false}], []); InspectorBackend.registerCommand("CSS.startSelectorProfiler", [], []); InspectorBackend.registerCommand("CSS.stopSelectorProfiler", [], ["profile"]); InspectorBackend.registerCommand("CSS.getNamedFlowCollection", [{"name": "documentNodeId", "type": "number", "optional": false}], ["namedFlows"]); InspectorBackend.registerTimelineDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Timeline"); InspectorBackend.registerEvent("Timeline.eventRecorded", ["record"]); InspectorBackend.registerCommand("Timeline.start", [{"name": "maxCallStackDepth", "type": "number", "optional": true}], []); InspectorBackend.registerCommand("Timeline.stop", [], []); InspectorBackend.registerCommand("Timeline.setIncludeMemoryDetails", [{"name": "enabled", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Timeline.supportsFrameInstrumentation", [], ["result"]); InspectorBackend.registerCommand("Timeline.canMonitorMainThread", [], ["result"]); InspectorBackend.registerDebuggerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Debugger"); InspectorBackend.registerEvent("Debugger.globalObjectCleared", []); InspectorBackend.registerEvent("Debugger.scriptParsed", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "isContentScript", "sourceMapURL", "hasSourceURL"]); InspectorBackend.registerEvent("Debugger.scriptFailedToParse", ["url", "scriptSource", "startLine", "errorLine", "errorMessage"]); InspectorBackend.registerEvent("Debugger.breakpointResolved", ["breakpointId", "location"]); InspectorBackend.registerEvent("Debugger.paused", ["callFrames", "reason", "data"]); InspectorBackend.registerEvent("Debugger.resumed", []); InspectorBackend.registerCommand("Debugger.causesRecompilation", [], ["result"]); InspectorBackend.registerCommand("Debugger.supportsSeparateScriptCompilationAndExecution", [], ["result"]); InspectorBackend.registerCommand("Debugger.enable", [], []); InspectorBackend.registerCommand("Debugger.disable", [], []); InspectorBackend.registerCommand("Debugger.setBreakpointsActive", [{"name": "active", "type": "boolean", "optional": false}], []); InspectorBackend.registerCommand("Debugger.setBreakpointByUrl", [{"name": "lineNumber", "type": "number", "optional": false}, {"name": "url", "type": "string", "optional": true}, {"name": "urlRegex", "type": "string", "optional": true}, {"name": "columnNumber", "type": "number", "optional": true}, {"name": "condition", "type": "string", "optional": true}], ["breakpointId", "locations"]); InspectorBackend.registerCommand("Debugger.setBreakpoint", [{"name": "location", "type": "object", "optional": false}, {"name": "condition", "type": "string", "optional": true}], ["breakpointId", "actualLocation"]); InspectorBackend.registerCommand("Debugger.removeBreakpoint", [{"name": "breakpointId", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Debugger.continueToLocation", [{"name": "location", "type": "object", "optional": false}], []); InspectorBackend.registerCommand("Debugger.stepOver", [], []); InspectorBackend.registerCommand("Debugger.stepInto", [], []); InspectorBackend.registerCommand("Debugger.stepOut", [], []); InspectorBackend.registerCommand("Debugger.pause", [], []); InspectorBackend.registerCommand("Debugger.resume", [], []); InspectorBackend.registerCommand("Debugger.searchInContent", [{"name": "scriptId", "type": "string", "optional": false}, {"name": "query", "type": "string", "optional": false}, {"name": "caseSensitive", "type": "boolean", "optional": true}, {"name": "isRegex", "type": "boolean", "optional": true}], ["result"]); InspectorBackend.registerCommand("Debugger.canSetScriptSource", [], ["result"]); InspectorBackend.registerCommand("Debugger.setScriptSource", [{"name": "scriptId", "type": "string", "optional": false}, {"name": "scriptSource", "type": "string", "optional": false}, {"name": "preview", "type": "boolean", "optional": true}], ["callFrames", "result"]); InspectorBackend.registerCommand("Debugger.restartFrame", [{"name": "callFrameId", "type": "string", "optional": false}], ["callFrames", "result"]); InspectorBackend.registerCommand("Debugger.getScriptSource", [{"name": "scriptId", "type": "string", "optional": false}], ["scriptSource"]); InspectorBackend.registerCommand("Debugger.getFunctionDetails", [{"name": "functionId", "type": "string", "optional": false}], ["details"]); InspectorBackend.registerCommand("Debugger.setPauseOnExceptions", [{"name": "state", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Debugger.evaluateOnCallFrame", [{"name": "callFrameId", "type": "string", "optional": false}, {"name": "expression", "type": "string", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}, {"name": "includeCommandLineAPI", "type": "boolean", "optional": true}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}, {"name": "returnByValue", "type": "boolean", "optional": true}, {"name": "generatePreview", "type": "boolean", "optional": true}], ["result", "wasThrown"]); InspectorBackend.registerCommand("Debugger.compileScript", [{"name": "expression", "type": "string", "optional": false}, {"name": "sourceURL", "type": "string", "optional": false}], ["scriptId", "syntaxErrorMessage"]); InspectorBackend.registerCommand("Debugger.runScript", [{"name": "scriptId", "type": "string", "optional": false}, {"name": "contextId", "type": "number", "optional": true}, {"name": "objectGroup", "type": "string", "optional": true}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}], ["result", "wasThrown"]); InspectorBackend.registerCommand("Debugger.setOverlayMessage", [{"name": "message", "type": "string", "optional": true}], []); InspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "type", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "type", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint", [{"name": "url", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint", [{"name": "url", "type": "string", "optional": false}], []); InspectorBackend.registerProfilerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Profiler"); InspectorBackend.registerEvent("Profiler.addProfileHeader", ["header"]); InspectorBackend.registerEvent("Profiler.addHeapSnapshotChunk", ["uid", "chunk"]); InspectorBackend.registerEvent("Profiler.finishHeapSnapshot", ["uid"]); InspectorBackend.registerEvent("Profiler.setRecordingProfile", ["isProfiling"]); InspectorBackend.registerEvent("Profiler.resetProfiles", []); InspectorBackend.registerEvent("Profiler.reportHeapSnapshotProgress", ["done", "total"]); InspectorBackend.registerCommand("Profiler.causesRecompilation", [], ["result"]); InspectorBackend.registerCommand("Profiler.isSampling", [], ["result"]); InspectorBackend.registerCommand("Profiler.hasHeapProfiler", [], ["result"]); InspectorBackend.registerCommand("Profiler.enable", [], []); InspectorBackend.registerCommand("Profiler.disable", [], []); InspectorBackend.registerCommand("Profiler.start", [], []); InspectorBackend.registerCommand("Profiler.stop", [], []); InspectorBackend.registerCommand("Profiler.getProfileHeaders", [], ["headers"]); InspectorBackend.registerCommand("Profiler.getProfile", [{"name": "type", "type": "string", "optional": false}, {"name": "uid", "type": "number", "optional": false}], ["profile"]); InspectorBackend.registerCommand("Profiler.removeProfile", [{"name": "type", "type": "string", "optional": false}, {"name": "uid", "type": "number", "optional": false}], []); InspectorBackend.registerCommand("Profiler.clearProfiles", [], []); InspectorBackend.registerCommand("Profiler.takeHeapSnapshot", [], []); InspectorBackend.registerCommand("Profiler.collectGarbage", [], []); InspectorBackend.registerCommand("Profiler.getObjectByHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["result"]); InspectorBackend.registerCommand("Profiler.getHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}], ["heapSnapshotObjectId"]); InspectorBackend.registerWorkerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Worker"); InspectorBackend.registerEvent("Worker.workerCreated", ["workerId", "url", "inspectorConnected"]); InspectorBackend.registerEvent("Worker.workerTerminated", ["workerId"]); InspectorBackend.registerEvent("Worker.dispatchMessageFromWorker", ["workerId", "message"]); InspectorBackend.registerEvent("Worker.disconnectedFromWorker", []); InspectorBackend.registerCommand("Worker.enable", [], []); InspectorBackend.registerCommand("Worker.disable", [], []); InspectorBackend.registerCommand("Worker.sendMessageToWorker", [{"name": "workerId", "type": "number", "optional": false}, {"name": "message", "type": "object", "optional": false}], []); InspectorBackend.registerCommand("Worker.connectToWorker", [{"name": "workerId", "type": "number", "optional": false}], []); InspectorBackend.registerCommand("Worker.disconnectFromWorker", [{"name": "workerId", "type": "number", "optional": false}], []); InspectorBackend.registerCommand("Worker.setAutoconnectToWorkers", [{"name": "value", "type": "boolean", "optional": false}], []); InspectorBackend.registerCanvasDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Canvas"); InspectorBackend.registerCommand("Canvas.enable", [], []); InspectorBackend.registerCommand("Canvas.disable", [], []); InspectorBackend.registerCommand("Canvas.dropTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Canvas.captureFrame", [], ["traceLogId"]); InspectorBackend.registerCommand("Canvas.startCapturing", [], ["traceLogId"]); InspectorBackend.registerCommand("Canvas.stopCapturing", [{"name": "traceLogId", "type": "string", "optional": false}], []); InspectorBackend.registerCommand("Canvas.getTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "startOffset", "type": "number", "optional": true}], ["traceLog"]); InspectorBackend.registerCommand("Canvas.replayTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "stepNo", "type": "number", "optional": false}], ["screenshotDataUrl"]); InspectorBackend.registerInputDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Input"); InspectorBackend.registerCommand("Input.dispatchKeyEvent", [{"name": "type", "type": "string", "optional": false}, {"name": "modifiers", "type": "number", "optional": true}, {"name": "timestamp", "type": "number", "optional": true}, {"name": "text", "type": "string", "optional": true}, {"name": "unmodifiedText", "type": "string", "optional": true}, {"name": "keyIdentifier", "type": "string", "optional": true}, {"name": "windowsVirtualKeyCode", "type": "number", "optional": true}, {"name": "nativeVirtualKeyCode", "type": "number", "optional": true}, {"name": "macCharCode", "type": "number", "optional": true}, {"name": "autoRepeat", "type": "boolean", "optional": true}, {"name": "isKeypad", "type": "boolean", "optional": true}, {"name": "isSystemKey", "type": "boolean", "optional": true}], []); InspectorBackend.registerCommand("Input.dispatchMouseEvent", [{"name": "type", "type": "string", "optional": false}, {"name": "x", "type": "number", "optional": false}, {"name": "y", "type": "number", "optional": false}, {"name": "modifiers", "type": "number", "optional": true}, {"name": "timestamp", "type": "number", "optional": true}, {"name": "button", "type": "string", "optional": true}, {"name": "clickCount", "type": "number", "optional": true}], []); InspectorBackend.registerLayerTreeDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "LayerTree"); InspectorBackend.registerEvent("LayerTree.layerTreeDidChange", []); InspectorBackend.registerCommand("LayerTree.enable", [], []); InspectorBackend.registerCommand("LayerTree.disable", [], []); InspectorBackend.registerCommand("LayerTree.getLayerTree", [], ["layerTree"]); InspectorBackend.registerCommand("LayerTree.nodeIdForLayerId", [{"name": "layerId", "type": "string", "optional": false}], ["nodeId"]); if (!window.InspectorExtensionRegistry) { WebInspector.InspectorExtensionRegistryStub = function() { } WebInspector.InspectorExtensionRegistryStub.prototype = { getExtensionsAsync: function() { } } var InspectorExtensionRegistry = new WebInspector.InspectorExtensionRegistryStub(); } var InspectorFrontendAPI = { _pendingCommands: [], isDebuggingEnabled: function() { return WebInspector.debuggerModel.debuggerEnabled(); }, setDebuggingEnabled: function(enabled) { if (enabled) { WebInspector.debuggerModel.enableDebugger(); WebInspector.showPanel("scripts"); } else WebInspector.debuggerModel.disableDebugger(); }, isTimelineProfilingEnabled: function() { return WebInspector.panels.timeline && WebInspector.panels.timeline.timelineProfilingEnabled; }, setTimelineProfilingEnabled: function(enabled) { WebInspector.showPanel("timeline").setTimelineProfilingEnabled(enabled); }, isProfilingJavaScript: function() { return WebInspector.panels.profiles && WebInspector.CPUProfileType.instance && WebInspector.CPUProfileType.instance.isRecordingProfile(); }, startProfilingJavaScript: function() { WebInspector.showPanel("profiles").enableProfiler(); if (WebInspector.CPUProfileType.instance) WebInspector.CPUProfileType.instance.startRecordingProfile(); }, stopProfilingJavaScript: function() { WebInspector.showPanel("profiles"); if (WebInspector.CPUProfileType.instance) WebInspector.CPUProfileType.instance.stopRecordingProfile(); }, setAttachedWindow: function(side) { }, setDockSide: function(side) { if (WebInspector.dockController) WebInspector.dockController.setDockSide(side); }, showConsole: function() { WebInspector.showPanel("console"); }, showMainResourceForFrame: function(frameId) { }, showResources: function() { WebInspector.showPanel("resources"); }, setDockingUnavailable: function(unavailable) { WebInspector.setDockingUnavailable(unavailable); }, enterInspectElementMode: function() { WebInspector.toggleSearchingForNode(); }, savedURL: function(url) { WebInspector.fileManager.savedURL(url); }, appendedToURL: function(url) { WebInspector.fileManager.appendedToURL(url); }, setToolbarColors: function(backgroundColor, color) { WebInspector.setToolbarColors(backgroundColor, color); }, evaluateForTest: function(callId, script) { WebInspector.evaluateForTestInFrontend(callId, script); }, dispatch: function(signature) { if (InspectorFrontendAPI._isLoaded) { var methodName = signature.shift(); return InspectorFrontendAPI[methodName].apply(InspectorFrontendAPI, signature); } InspectorFrontendAPI._pendingCommands.push(signature); }, dispatchQueryParameters: function() { if ("dispatch" in WebInspector.queryParamsObject) InspectorFrontendAPI.dispatch(JSON.parse(window.decodeURI(WebInspector.queryParamsObject["dispatch"]))); }, loadTimelineFromURL: function(url) { WebInspector.showPanel("timeline").loadFromURL(url); }, loadCompleted: function() { InspectorFrontendAPI._isLoaded = true; for (var i = 0; i < InspectorFrontendAPI._pendingCommands.length; ++i) InspectorFrontendAPI.dispatch(InspectorFrontendAPI._pendingCommands[i]); InspectorFrontendAPI._pendingCommands = []; if (window.opener) window.opener.postMessage(["loadCompleted"], "*"); }, contextMenuItemSelected: function(id) { WebInspector.contextMenuItemSelected(id); }, contextMenuCleared: function() { WebInspector.contextMenuCleared(); }, dispatchMessageAsync: function(messageObject) { WebInspector.dispatch(messageObject); }, dispatchMessage: function(messageObject) { InspectorBackend.dispatch(messageObject); } } if (window.opener) { function onMessageFromOpener(event) { if (event.source === window.opener) InspectorFrontendAPI.dispatch(event.data); } window.addEventListener("message", onMessageFromOpener, true); } WebInspector.Object = function() { } WebInspector.Object.prototype = { addEventListener: function(eventType, listener, thisObject) { console.assert(listener); if (!this._listeners) this._listeners = {}; if (!this._listeners[eventType]) this._listeners[eventType] = []; this._listeners[eventType].push({ thisObject: thisObject, listener: listener }); }, removeEventListener: function(eventType, listener, thisObject) { console.assert(listener); if (!this._listeners || !this._listeners[eventType]) return; var listeners = this._listeners[eventType]; for (var i = 0; i < listeners.length; ++i) { if (listener && listeners[i].listener === listener && listeners[i].thisObject === thisObject) listeners.splice(i, 1); else if (!listener && thisObject && listeners[i].thisObject === thisObject) listeners.splice(i, 1); } if (!listeners.length) delete this._listeners[eventType]; }, removeAllListeners: function() { delete this._listeners; }, hasEventListeners: function(eventType) { if (!this._listeners || !this._listeners[eventType]) return false; return true; }, dispatchEventToListeners: function(eventType, eventData) { if (!this._listeners || !this._listeners[eventType]) return false; var event = new WebInspector.Event(this, eventType, eventData); var listeners = this._listeners[eventType].slice(0); for (var i = 0; i < listeners.length; ++i) { listeners[i].listener.call(listeners[i].thisObject, event); if (event._stoppedPropagation) break; } return event.defaultPrevented; } } WebInspector.Event = function(target, type, data) { this.target = target; this.type = type; this.data = data; this.defaultPrevented = false; this._stoppedPropagation = false; } WebInspector.Event.prototype = { stopPropagation: function() { this._stoppedPropagation = true; }, preventDefault: function() { this.defaultPrevented = true; }, consume: function(preventDefault) { this.stopPropagation(); if (preventDefault) this.preventDefault(); } } WebInspector.notifications = new WebInspector.Object(); var Preferences = { maxInlineTextChildLength: 80, minConsoleHeight: 75, minSidebarWidth: 100, minElementsSidebarWidth: 200, minScriptsSidebarWidth: 200, styleRulesExpandedState: {}, showMissingLocalizedStrings: false, useLowerCaseMenuTitlesOnWindows: false, sharedWorkersDebugNote: undefined, localizeUI: true, exposeDisableCache: false, applicationTitle: "Web Inspector - %s", showDockToRight: false, exposeFileSystemInspection: false, experimentsEnabled: true } var Capabilities = { samplingCPUProfiler: false, debuggerCausesRecompilation: true, separateScriptCompilationAndExecutionEnabled: false, profilerCausesRecompilation: true, heapProfilerPresent: false, canOverrideDeviceMetrics: false, timelineSupportsFrameInstrumentation: false, timelineCanMonitorMainThread: false, canOverrideGeolocation: false, canOverrideDeviceOrientation: false, canShowFPSCounter: false } WebInspector.Settings = function() { this._eventSupport = new WebInspector.Object(); this.colorFormat = this.createSetting("colorFormat", "original"); this.consoleHistory = this.createSetting("consoleHistory", []); this.debuggerEnabled = this.createSetting("debuggerEnabled", false); this.domWordWrap = this.createSetting("domWordWrap", true); this.profilerEnabled = this.createSetting("profilerEnabled", false); this.eventListenersFilter = this.createSetting("eventListenersFilter", "all"); this.lastActivePanel = this.createSetting("lastActivePanel", "elements"); this.lastViewedScriptFile = this.createSetting("lastViewedScriptFile", "application"); this.monitoringXHREnabled = this.createSetting("monitoringXHREnabled", false); this.preserveConsoleLog = this.createSetting("preserveConsoleLog", false); this.resourcesLargeRows = this.createSetting("resourcesLargeRows", true); this.resourcesSortOptions = this.createSetting("resourcesSortOptions", {timeOption: "responseTime", sizeOption: "transferSize"}); this.resourceViewTab = this.createSetting("resourceViewTab", "preview"); this.showInheritedComputedStyleProperties = this.createSetting("showInheritedComputedStyleProperties", false); this.showUserAgentStyles = this.createSetting("showUserAgentStyles", true); this.watchExpressions = this.createSetting("watchExpressions", []); this.breakpoints = this.createSetting("breakpoints", []); this.eventListenerBreakpoints = this.createSetting("eventListenerBreakpoints", []); this.domBreakpoints = this.createSetting("domBreakpoints", []); this.xhrBreakpoints = this.createSetting("xhrBreakpoints", []); this.sourceMapsEnabled = this.createSetting("sourceMapsEnabled", false); this.cacheDisabled = this.createSetting("cacheDisabled", false); this.overrideUserAgent = this.createSetting("overrideUserAgent", ""); this.userAgent = this.createSetting("userAgent", ""); this.deviceMetrics = this.createSetting("deviceMetrics", ""); this.deviceFitWindow = this.createSetting("deviceFitWindow", false); this.showScriptFolders = this.createSetting("showScriptFolders", true); this.emulateTouchEvents = this.createSetting("emulateTouchEvents", false); this.showPaintRects = this.createSetting("showPaintRects", false); this.showFPSCounter = this.createSetting("showFPSCounter", false); this.showShadowDOM = this.createSetting("showShadowDOM", false); this.zoomLevel = this.createSetting("zoomLevel", 0); this.savedURLs = this.createSetting("savedURLs", {}); this.javaScriptDisabled = this.createSetting("javaScriptDisabled", false); this.geolocationOverride = this.createSetting("geolocationOverride", ""); this.deviceOrientationOverride = this.createSetting("deviceOrientationOverride", ""); this.showHeapSnapshotObjectsHiddenProperties = this.createSetting("showHeaSnapshotObjectsHiddenProperties", false); this.showNativeSnapshotUninstrumentedSize = this.createSetting("showNativeSnapshotUninstrumentedSize", false); this.searchInContentScripts = this.createSetting("searchInContentScripts", false); this.textEditorIndent = this.createSetting("textEditorIndent", " "); this.lastDockState = this.createSetting("lastDockState", ""); this.cssReloadEnabled = this.createSetting("cssReloadEnabled", false); this.cssReloadTimeout = this.createSetting("cssReloadTimeout", 1000); this.showCpuOnTimelineRuler = this.createSetting("showCpuOnTimelineRuler", false); this.showMetricsRulers = this.createSetting("showMetricsRulers", false); this.emulatedCSSMedia = this.createSetting("emulatedCSSMedia", "print"); this.showToolbarIcons = this.createSetting("showToolbarIcons", false); if (this.breakpoints.get().length > 500000) this.breakpoints.set([]); } WebInspector.Settings.prototype = { createSetting: function(key, defaultValue) { return new WebInspector.Setting(key, defaultValue, this._eventSupport); } } WebInspector.Setting = function(name, defaultValue, eventSupport) { this._name = name; this._defaultValue = defaultValue; this._eventSupport = eventSupport; } WebInspector.Setting.prototype = { addChangeListener: function(listener, thisObject) { this._eventSupport.addEventListener(this._name, listener, thisObject); }, removeChangeListener: function(listener, thisObject) { this._eventSupport.removeEventListener(this._name, listener, thisObject); }, get name() { return this._name; }, get: function() { if (typeof this._value !== "undefined") return this._value; this._value = this._defaultValue; if (window.localStorage != null && this._name in window.localStorage) { try { this._value = JSON.parse(window.localStorage[this._name]); } catch(e) { window.localStorage.removeItem(this._name); } } return this._value; }, set: function(value) { this._value = value; if (window.localStorage != null) { try { window.localStorage[this._name] = JSON.stringify(value); } catch(e) { console.error("Error saving setting with name:" + this._name); } } this._eventSupport.dispatchEventToListeners(this._name, value); } } WebInspector.ExperimentsSettings = function() { this._setting = WebInspector.settings.createSetting("experiments", {}); this._experiments = []; this._enabledForTest = {}; this.snippetsSupport = this._createExperiment("snippetsSupport", "Snippets support"); this.nativeMemorySnapshots = this._createExperiment("nativeMemorySnapshots", "Native memory profiling"); this.liveNativeMemoryChart = this._createExperiment("liveNativeMemoryChart", "Live native memory chart"); this.fileSystemInspection = this._createExperiment("fileSystemInspection", "FileSystem inspection"); this.canvasInspection = this._createExperiment("canvasInspection ", "Canvas inspection"); this.sass = this._createExperiment("sass", "Support for Sass"); this.codemirror = this._createExperiment("codemirror", "Use CodeMirror editor"); this.cssRegions = this._createExperiment("cssRegions", "CSS Regions Support"); this.showOverridesInDrawer = this._createExperiment("showOverridesInDrawer", "Show Overrides in drawer"); this._cleanUpSetting(); } WebInspector.ExperimentsSettings.prototype = { get experiments() { return this._experiments.slice(); }, get experimentsEnabled() { return Preferences.experimentsEnabled || ("experiments" in WebInspector.queryParamsObject); }, _createExperiment: function(experimentName, experimentTitle) { var experiment = new WebInspector.Experiment(this, experimentName, experimentTitle); this._experiments.push(experiment); return experiment; }, isEnabled: function(experimentName) { if (this._enabledForTest[experimentName]) return true; if (!this.experimentsEnabled) return false; var experimentsSetting = this._setting.get(); return experimentsSetting[experimentName]; }, setEnabled: function(experimentName, enabled) { var experimentsSetting = this._setting.get(); experimentsSetting[experimentName] = enabled; this._setting.set(experimentsSetting); }, _enableForTest: function(experimentName) { this._enabledForTest[experimentName] = true; }, _cleanUpSetting: function() { var experimentsSetting = this._setting.get(); var cleanedUpExperimentSetting = {}; for (var i = 0; i < this._experiments.length; ++i) { var experimentName = this._experiments[i].name; if (experimentsSetting[experimentName]) cleanedUpExperimentSetting[experimentName] = true; } this._setting.set(cleanedUpExperimentSetting); } } WebInspector.Experiment = function(experimentsSettings, name, title) { this._name = name; this._title = title; this._experimentsSettings = experimentsSettings; } WebInspector.Experiment.prototype = { get name() { return this._name; }, get title() { return this._title; }, isEnabled: function() { return this._experimentsSettings.isEnabled(this._name); }, setEnabled: function(enabled) { return this._experimentsSettings.setEnabled(this._name, enabled); }, enableForTest: function() { this._experimentsSettings._enableForTest(this._name); } } WebInspector.settings = new WebInspector.Settings(); WebInspector.experimentsSettings = new WebInspector.ExperimentsSettings(); WebInspector.View = function() { this.element = document.createElement("div"); this.element.__view = this; this._visible = true; this._isRoot = false; this._isShowing = false; this._children = []; this._hideOnDetach = false; this._cssFiles = []; this._notificationDepth = 0; } WebInspector.View._cssFileToVisibleViewCount = {}; WebInspector.View._cssFileToStyleElement = {}; WebInspector.View.prototype = { markAsRoot: function() { this._isRoot = true; }, isShowing: function() { return this._isShowing; }, setHideOnDetach: function() { this._hideOnDetach = true; }, _inNotification: function() { return !!this._notificationDepth || (this._parentView && this._parentView._inNotification()); }, _parentIsShowing: function() { if (this._isRoot) return true; return this._parentView && this._parentView.isShowing(); }, _callOnVisibleChildren: function(method) { var copy = this._children.slice(); for (var i = 0; i < copy.length; ++i) { if (copy[i]._parentView === this && copy[i]._visible) method.call(copy[i]); } }, _processWillShow: function() { this._loadCSSIfNeeded(); this._callOnVisibleChildren(this._processWillShow); }, _processWasShown: function() { if (this._inNotification()) return; this._isShowing = true; this.restoreScrollPositions(); this._notify(this.wasShown); this._notify(this.onResize); this._callOnVisibleChildren(this._processWasShown); }, _processWillHide: function() { if (this._inNotification()) return; this.storeScrollPositions(); this._callOnVisibleChildren(this._processWillHide); this._notify(this.willHide); this._isShowing = false; }, _processWasHidden: function() { this._disableCSSIfNeeded(); this._callOnVisibleChildren(this._processWasHidden); }, _processOnResize: function() { if (this._inNotification()) return; if (!this.isShowing()) return; this._notify(this.onResize); this._callOnVisibleChildren(this._processOnResize); }, _notify: function(notification) { ++this._notificationDepth; try { notification.call(this); } finally { --this._notificationDepth; } }, wasShown: function() { }, willHide: function() { }, onResize: function() { }, show: function(parentElement, insertBefore) { WebInspector.View._assert(parentElement, "Attempt to attach view with no parent element"); if (this.element.parentElement !== parentElement) { if (this.element.parentElement) this.detach(); var currentParent = parentElement; while (currentParent && !currentParent.__view) currentParent = currentParent.parentElement; if (currentParent) { this._parentView = currentParent.__view; this._parentView._children.push(this); this._isRoot = false; } else WebInspector.View._assert(this._isRoot, "Attempt to attach view to orphan node"); } else if (this._visible) return; this._visible = true; if (this._parentIsShowing()) this._processWillShow(); this.element.addStyleClass("visible"); if (this.element.parentElement !== parentElement) { WebInspector.View._incrementViewCounter(parentElement, this.element); if (insertBefore) WebInspector.View._originalInsertBefore.call(parentElement, this.element, insertBefore); else WebInspector.View._originalAppendChild.call(parentElement, this.element); } if (this._parentIsShowing()) this._processWasShown(); }, detach: function(overrideHideOnDetach) { var parentElement = this.element.parentElement; if (!parentElement) return; if (this._parentIsShowing()) this._processWillHide(); if (this._hideOnDetach && !overrideHideOnDetach) { this.element.removeStyleClass("visible"); this._visible = false; if (this._parentIsShowing()) this._processWasHidden(); return; } WebInspector.View._decrementViewCounter(parentElement, this.element); WebInspector.View._originalRemoveChild.call(parentElement, this.element); this._visible = false; if (this._parentIsShowing()) this._processWasHidden(); if (this._parentView) { var childIndex = this._parentView._children.indexOf(this); WebInspector.View._assert(childIndex >= 0, "Attempt to remove non-child view"); this._parentView._children.splice(childIndex, 1); this._parentView = null; } else WebInspector.View._assert(this._isRoot, "Removing non-root view from DOM"); }, detachChildViews: function() { var children = this._children.slice(); for (var i = 0; i < children.length; ++i) children[i].detach(); }, elementsToRestoreScrollPositionsFor: function() { return [this.element]; }, storeScrollPositions: function() { var elements = this.elementsToRestoreScrollPositionsFor(); for (var i = 0; i < elements.length; ++i) { var container = elements[i]; container._scrollTop = container.scrollTop; container._scrollLeft = container.scrollLeft; } }, restoreScrollPositions: function() { var elements = this.elementsToRestoreScrollPositionsFor(); for (var i = 0; i < elements.length; ++i) { var container = elements[i]; if (container._scrollTop) container.scrollTop = container._scrollTop; if (container._scrollLeft) container.scrollLeft = container._scrollLeft; } }, canHighlightLine: function() { return false; }, highlightLine: function(line) { }, doResize: function() { this._processOnResize(); }, registerRequiredCSS: function(cssFile) { this._cssFiles.push(cssFile); }, _loadCSSIfNeeded: function() { for (var i = 0; i < this._cssFiles.length; ++i) { var cssFile = this._cssFiles[i]; var viewsWithCSSFile = WebInspector.View._cssFileToVisibleViewCount[cssFile]; WebInspector.View._cssFileToVisibleViewCount[cssFile] = (viewsWithCSSFile || 0) + 1; if (!viewsWithCSSFile) this._doLoadCSS(cssFile); } }, _doLoadCSS: function(cssFile) { var styleElement = WebInspector.View._cssFileToStyleElement[cssFile]; if (styleElement) { styleElement.disabled = false; return; } if (window.debugCSS) { styleElement = document.createElement("link"); styleElement.rel = "stylesheet"; styleElement.type = "text/css"; styleElement.href = cssFile; } else { var xhr = new XMLHttpRequest(); xhr.open("GET", cssFile, false); xhr.send(null); styleElement = document.createElement("style"); styleElement.type = "text/css"; styleElement.textContent = xhr.responseText; } document.head.insertBefore(styleElement, document.head.firstChild); WebInspector.View._cssFileToStyleElement[cssFile] = styleElement; }, _disableCSSIfNeeded: function() { for (var i = 0; i < this._cssFiles.length; ++i) { var cssFile = this._cssFiles[i]; var viewsWithCSSFile = WebInspector.View._cssFileToVisibleViewCount[cssFile]; viewsWithCSSFile--; WebInspector.View._cssFileToVisibleViewCount[cssFile] = viewsWithCSSFile; if (!viewsWithCSSFile) this._doUnloadCSS(cssFile); } }, _doUnloadCSS: function(cssFile) { var styleElement = WebInspector.View._cssFileToStyleElement[cssFile]; styleElement.disabled = true; }, printViewHierarchy: function() { var lines = []; this._collectViewHierarchy("", lines); console.log(lines.join("\n")); }, _collectViewHierarchy: function(prefix, lines) { lines.push(prefix + "[" + this.element.className + "]" + (this._children.length ? " {" : "")); for (var i = 0; i < this._children.length; ++i) this._children[i]._collectViewHierarchy(prefix + " ", lines); if (this._children.length) lines.push(prefix + "}"); }, defaultFocusedElement: function() { return this._defaultFocusedElement || this.element; }, setDefaultFocusedElement: function(element) { this._defaultFocusedElement = element; }, focus: function() { var element = this.defaultFocusedElement(); if (!element || element.isAncestor(document.activeElement)) return; WebInspector.setCurrentFocusElement(element); }, measurePreferredSize: function() { this._loadCSSIfNeeded(); WebInspector.View._originalAppendChild.call(document.body, this.element); this.element.positionAt(0, 0); var result = new Size(this.element.offsetWidth, this.element.offsetHeight); this.element.positionAt(undefined, undefined); WebInspector.View._originalRemoveChild.call(document.body, this.element); this._disableCSSIfNeeded(); return result; }, __proto__: WebInspector.Object.prototype } WebInspector.View._originalAppendChild = Element.prototype.appendChild; WebInspector.View._originalInsertBefore = Element.prototype.insertBefore; WebInspector.View._originalRemoveChild = Element.prototype.removeChild; WebInspector.View._originalRemoveChildren = Element.prototype.removeChildren; WebInspector.View._incrementViewCounter = function(parentElement, childElement) { var count = (childElement.__viewCounter || 0) + (childElement.__view ? 1 : 0); if (!count) return; while (parentElement) { parentElement.__viewCounter = (parentElement.__viewCounter || 0) + count; parentElement = parentElement.parentElement; } } WebInspector.View._decrementViewCounter = function(parentElement, childElement) { var count = (childElement.__viewCounter || 0) + (childElement.__view ? 1 : 0); if (!count) return; while (parentElement) { parentElement.__viewCounter -= count; parentElement = parentElement.parentElement; } } WebInspector.View._assert = function(condition, message) { if (!condition) { console.trace(); throw new Error(message); } } Element.prototype.appendChild = function(child) { WebInspector.View._assert(!child.__view, "Attempt to add view via regular DOM operation."); return WebInspector.View._originalAppendChild.call(this, child); } Element.prototype.insertBefore = function(child, anchor) { WebInspector.View._assert(!child.__view, "Attempt to add view via regular DOM operation."); return WebInspector.View._originalInsertBefore.call(this, child, anchor); } Element.prototype.removeChild = function(child) { WebInspector.View._assert(!child.__viewCounter && !child.__view, "Attempt to remove element containing view via regular DOM operation"); return WebInspector.View._originalRemoveChild.call(this, child); } Element.prototype.removeChildren = function() { WebInspector.View._assert(!this.__viewCounter, "Attempt to remove element containing view via regular DOM operation"); WebInspector.View._originalRemoveChildren.call(this); } WebInspector.HelpScreen = function(title) { WebInspector.View.call(this); this.markAsRoot(); this.registerRequiredCSS("helpScreen.css"); this.element.className = "help-window-outer"; this.element.addEventListener("keydown", this._onKeyDown.bind(this), false); this.element.tabIndex = 0; this.element.addEventListener("focus", this._onBlur.bind(this), false); if (title) { var mainWindow = this.element.createChild("div", "help-window-main"); var captionWindow = mainWindow.createChild("div", "help-window-caption"); captionWindow.appendChild(this._createCloseButton()); this.contentElement = mainWindow.createChild("div", "help-content"); captionWindow.createChild("h1", "help-window-title").textContent = title; } } WebInspector.HelpScreen._visibleScreen = null; WebInspector.HelpScreen.prototype = { _createCloseButton: function() { var closeButton = document.createElement("button"); closeButton.className = "help-close-button"; closeButton.textContent = "\u2716"; closeButton.addEventListener("click", this.hide.bind(this), false); return closeButton; }, showModal: function() { var visibleHelpScreen = WebInspector.HelpScreen._visibleScreen; if (visibleHelpScreen === this) return; if (visibleHelpScreen) visibleHelpScreen.hide(); WebInspector.HelpScreen._visibleScreen = this; this.show(document.body); this.focus(); }, hide: function() { if (!this.isShowing()) return; WebInspector.HelpScreen._visibleScreen = null; WebInspector.restoreFocusFromElement(this.element); this.detach(); }, isClosingKey: function(keyCode) { return [ WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, WebInspector.KeyboardShortcut.Keys.Space.code, ].indexOf(keyCode) >= 0; }, _onKeyDown: function(event) { if (this.isShowing() && this.isClosingKey(event.keyCode)) { this.hide(); event.consume(); } }, _onBlur: function(event) { if (this.isShowing() && !this.element.isSelfOrAncestor(event.target)) WebInspector.setCurrentFocusElement(this.element); }, __proto__: WebInspector.View.prototype } if (!window.InspectorFrontendHost) { WebInspector.InspectorFrontendHostStub = function() { this._attachedWindowHeight = 0; this.isStub = true; this._fileBuffers = {}; WebInspector.documentCopyEventFired = this.documentCopy.bind(this); } WebInspector.InspectorFrontendHostStub.prototype = { platform: function() { var match = navigator.userAgent.match(/Windows NT/); if (match) return "windows"; match = navigator.userAgent.match(/Mac OS X/); if (match) return "mac"; return "linux"; }, port: function() { return "unknown"; }, bringToFront: function() { this._windowVisible = true; }, closeWindow: function() { this._windowVisible = false; }, requestSetDockSide: function(side) { InspectorFrontendAPI.setDockSide(side); }, setAttachedWindowHeight: function(height) { }, moveWindowBy: function(x, y) { }, setInjectedScriptForOrigin: function(origin, script) { }, loaded: function() { }, localizedStringsURL: function() { return undefined; }, hiddenPanels: function() { return WebInspector.queryParamsObject["hiddenPanels"] || ""; }, inspectedURLChanged: function(url) { document.title = WebInspector.UIString(Preferences.applicationTitle, url); }, documentCopy: function(event) { if (!this._textToCopy) return; event.clipboardData.setData("text", this._textToCopy); event.preventDefault(); delete this._textToCopy; }, copyText: function(text) { this._textToCopy = text; if (!document.execCommand("copy")) { var screen = new WebInspector.ClipboardAccessDeniedScreen(); screen.showModal(); } }, openInNewTab: function(url) { window.open(url, "_blank"); }, canSave: function() { return true; }, save: function(url, content, forceSaveAs) { if (this._fileBuffers[url]) throw new Error("Concurrent file modification denied."); this._fileBuffers[url] = [content]; setTimeout(WebInspector.fileManager.savedURL.bind(WebInspector.fileManager, url), 0); }, append: function(url, content) { var buffer = this._fileBuffers[url]; if (!buffer) throw new Error("File is not open for write yet."); buffer.push(content); setTimeout(WebInspector.fileManager.appendedToURL.bind(WebInspector.fileManager, url), 0); }, close: function(url) { var content = this._fileBuffers[url]; delete this._fileBuffers[url]; if (!content) return; var lastSlashIndex = url.lastIndexOf("/"); var fileNameSuffix = (lastSlashIndex === -1) ? url : url.substring(lastSlashIndex + 1); var blob = new Blob(content, { type: "application/octet-stream" }); var objectUrl = window.URL.createObjectURL(blob); window.location = objectUrl + "#" + fileNameSuffix; function cleanup() { window.URL.revokeObjectURL(objectUrl); } setTimeout(cleanup, 0); }, sendMessageToBackend: function(message) { }, recordActionTaken: function(actionCode) { }, recordPanelShown: function(panelCode) { }, recordSettingChanged: function(settingCode) { }, loadResourceSynchronously: function(url) { return loadXHR(url); }, setZoomFactor: function(zoom) { }, canInspectWorkers: function() { return true; } } InspectorFrontendHost = new WebInspector.InspectorFrontendHostStub(); Preferences.localizeUI = false; WebInspector.clipboardAccessDeniedMessage = function() { return ""; } WebInspector.ClipboardAccessDeniedScreen = function() { WebInspector.HelpScreen.call(this, WebInspector.UIString("Clipboard access is denied")); var platformMessage = WebInspector.clipboardAccessDeniedMessage(); if (platformMessage) { var p = this.contentElement.createChild("p"); p.addStyleClass("help-section"); p.textContent = platformMessage; } } WebInspector.ClipboardAccessDeniedScreen.prototype = { __proto__: WebInspector.HelpScreen.prototype } } WebInspector.RemoteDebuggingTerminatedScreen = function(reason) { WebInspector.HelpScreen.call(this, WebInspector.UIString("Detached from the target")); var p = this.contentElement.createChild("p"); p.addStyleClass("help-section"); p.createChild("span").textContent = "Remote debugging has been terminated with reason: "; p.createChild("span", "error-message").textContent = reason; p.createChild("br"); p.createChild("span").textContent = "Please re-attach to the new target."; } WebInspector.RemoteDebuggingTerminatedScreen.prototype = { __proto__: WebInspector.HelpScreen.prototype } WebInspector.FileManager = function() { } WebInspector.FileManager.EventTypes = { SavedURL: "SavedURL", AppendedToURL: "AppendedToURL" } WebInspector.FileManager.prototype = { canSave: function() { return InspectorFrontendHost.canSave(); }, save: function(url, content, forceSaveAs) { var savedURLs = WebInspector.settings.savedURLs.get(); delete savedURLs[url]; WebInspector.settings.savedURLs.set(savedURLs); InspectorFrontendHost.save(url, content, forceSaveAs); }, savedURL: function(url) { var savedURLs = WebInspector.settings.savedURLs.get(); savedURLs[url] = true; WebInspector.settings.savedURLs.set(savedURLs); this.dispatchEventToListeners(WebInspector.FileManager.EventTypes.SavedURL, url); }, isURLSaved: function(url) { var savedURLs = WebInspector.settings.savedURLs.get(); return savedURLs[url]; }, append: function(url, content) { InspectorFrontendHost.append(url, content); }, close: function(url) { InspectorFrontendHost.close(url); }, appendedToURL: function(url) { this.dispatchEventToListeners(WebInspector.FileManager.EventTypes.AppendedToURL, url); }, __proto__: WebInspector.Object.prototype } WebInspector.fileManager = new WebInspector.FileManager(); WebInspector.Checkbox = function(label, className, tooltip) { this.element = document.createElement('label'); this._inputElement = document.createElement('input'); this._inputElement.type = "checkbox"; this.element.className = className; this.element.appendChild(this._inputElement); this.element.appendChild(document.createTextNode(label)); if (tooltip) this.element.title = tooltip; } WebInspector.Checkbox.prototype = { set checked(checked) { this._inputElement.checked = checked; }, get checked() { return this._inputElement.checked; }, addEventListener: function(listener) { function listenerWrapper(event) { if (listener) listener(event); event.consume(); return true; } this._inputElement.addEventListener("click", listenerWrapper, false); this.element.addEventListener("click", listenerWrapper, false); } } WebInspector.ContextMenuItem = function(topLevelMenu, type, label, disabled, checked) { this._type = type; this._label = label; this._disabled = disabled; this._checked = checked; this._contextMenu = topLevelMenu; if (type === "item" || type === "checkbox") this._id = topLevelMenu.nextId(); } WebInspector.ContextMenuItem.prototype = { id: function() { return this._id; }, type: function() { return this._type; }, _buildDescriptor: function() { switch (this._type) { case "item": return { type: "item", id: this._id, label: this._label, enabled: !this._disabled }; case "separator": return { type: "separator" }; case "checkbox": return { type: "checkbox", id: this._id, label: this._label, checked: !!this._checked, enabled: !this._disabled }; } } } WebInspector.ContextSubMenuItem = function(topLevelMenu, label, disabled) { WebInspector.ContextMenuItem.call(this, topLevelMenu, "subMenu", label, disabled); this._items = []; } WebInspector.ContextSubMenuItem.prototype = { appendItem: function(label, handler, disabled) { var item = new WebInspector.ContextMenuItem(this._contextMenu, "item", label, disabled); this._pushItem(item); this._contextMenu._setHandler(item.id(), handler); return item; }, appendSubMenuItem: function(label, disabled) { var item = new WebInspector.ContextSubMenuItem(this._contextMenu, label, disabled); this._pushItem(item); return item; }, appendCheckboxItem: function(label, handler, checked, disabled) { var item = new WebInspector.ContextMenuItem(this._contextMenu, "checkbox", label, disabled, checked); this._pushItem(item); this._contextMenu._setHandler(item.id(), handler); return item; }, appendSeparator: function() { if (this._items.length) this._pendingSeparator = true; }, _pushItem: function(item) { if (this._pendingSeparator) { this._items.push(new WebInspector.ContextMenuItem(this._contextMenu, "separator")); delete this._pendingSeparator; } this._items.push(item); }, isEmpty: function() { return !this._items.length; }, _buildDescriptor: function() { var result = { type: "subMenu", label: this._label, enabled: !this._disabled, subItems: [] }; for (var i = 0; i < this._items.length; ++i) result.subItems.push(this._items[i]._buildDescriptor()); return result; }, __proto__: WebInspector.ContextMenuItem.prototype } WebInspector.ContextMenu = function(event) { WebInspector.ContextSubMenuItem.call(this, this, ""); this._event = event; this._handlers = {}; this._id = 0; } WebInspector.ContextMenu.prototype = { nextId: function() { return this._id++; }, show: function() { var menuObject = this._buildDescriptor(); if (menuObject.length) { WebInspector._contextMenu = this; InspectorFrontendHost.showContextMenu(this._event, menuObject); } this._event.consume(); }, showSoftMenu: function() { var menuObject = this._buildDescriptor(); if (menuObject.length) { WebInspector._contextMenu = this; var softMenu = new WebInspector.SoftContextMenu(menuObject); softMenu.show(this._event, true); } this._event.consume(); }, _setHandler: function(id, handler) { if (handler) this._handlers[id] = handler; }, _buildDescriptor: function() { var result = []; for (var i = 0; i < this._items.length; ++i) result.push(this._items[i]._buildDescriptor()); return result; }, _itemSelected: function(id) { if (this._handlers[id]) this._handlers[id].call(this); }, appendApplicableItems: function(target) { for (var i = 0; i < WebInspector.ContextMenu._providers.length; ++i) { var provider = WebInspector.ContextMenu._providers[i]; this.appendSeparator(); provider.appendApplicableItems(this._event, this, target); this.appendSeparator(); } }, __proto__: WebInspector.ContextSubMenuItem.prototype } WebInspector.ContextMenu.Provider = function() { } WebInspector.ContextMenu.Provider.prototype = { appendApplicableItems: function(event, contextMenu, target) { } } WebInspector.ContextMenu.registerProvider = function(provider) { WebInspector.ContextMenu._providers.push(provider); } WebInspector.ContextMenu._providers = []; WebInspector.contextMenuItemSelected = function(id) { if (WebInspector._contextMenu) WebInspector._contextMenu._itemSelected(id); } WebInspector.contextMenuCleared = function() { } WebInspector.SoftContextMenu = function(items, parentMenu) { this._items = items; this._parentMenu = parentMenu; } WebInspector.SoftContextMenu.prototype = { show: function(event, alignToCurrentTarget) { this._x = event.x; this._y = event.y; this._time = new Date().getTime(); var absoluteX = event.pageX; var absoluteY = event.pageY; var targetElement = event.target; while (targetElement && window !== targetElement.ownerDocument.defaultView) { var frameElement = targetElement.ownerDocument.defaultView.frameElement; absoluteY += frameElement.totalOffsetTop(); absoluteX += frameElement.totalOffsetLeft(); targetElement = frameElement; } var targetRect; this._contextMenuElement = document.createElement("div"); this._contextMenuElement.className = "soft-context-menu"; this._contextMenuElement.tabIndex = 0; if (alignToCurrentTarget) { targetRect = event.currentTarget.getBoundingClientRect(); absoluteX = targetRect.left; absoluteY = targetRect.bottom; } this._contextMenuElement.style.top = absoluteY + "px"; this._contextMenuElement.style.left = absoluteX + "px"; this._contextMenuElement.addEventListener("mouseup", consumeEvent, false); this._contextMenuElement.addEventListener("keydown", this._menuKeyDown.bind(this), false); for (var i = 0; i < this._items.length; ++i) this._contextMenuElement.appendChild(this._createMenuItem(this._items[i])); if (!this._parentMenu) { this._glassPaneElement = document.createElement("div"); this._glassPaneElement.className = "soft-context-menu-glass-pane"; this._glassPaneElement.tabIndex = 0; this._glassPaneElement.addEventListener("mouseup", this._glassPaneMouseUp.bind(this), false); this._glassPaneElement.appendChild(this._contextMenuElement); document.body.appendChild(this._glassPaneElement); this._focus(); } else this._parentMenu._parentGlassPaneElement().appendChild(this._contextMenuElement); if (document.body.offsetWidth < this._contextMenuElement.offsetLeft + this._contextMenuElement.offsetWidth) { if (alignToCurrentTarget) this._contextMenuElement.style.left = Math.max(0, targetRect.right - this._contextMenuElement.offsetWidth) + "px"; else this._contextMenuElement.style.left = (absoluteX - this._contextMenuElement.offsetWidth) + "px"; } if (document.body.offsetHeight < this._contextMenuElement.offsetTop + this._contextMenuElement.offsetHeight) { if (alignToCurrentTarget) this._contextMenuElement.style.top = Math.max(0, targetRect.top - this._contextMenuElement.offsetHeight) + "px"; else this._contextMenuElement.style.top = (document.body.offsetHeight - this._contextMenuElement.offsetHeight) + "px"; } event.consume(true); }, _parentGlassPaneElement: function() { if (this._glassPaneElement) return this._glassPaneElement; if (this._parentMenu) return this._parentMenu._parentGlassPaneElement(); return null; }, _createMenuItem: function(item) { if (item.type === "separator") return this._createSeparator(); if (item.type === "subMenu") return this._createSubMenu(item); var menuItemElement = document.createElement("div"); menuItemElement.className = "soft-context-menu-item"; var checkMarkElement = document.createElement("span"); checkMarkElement.textContent = "\u2713 "; checkMarkElement.className = "soft-context-menu-item-checkmark"; if (!item.checked) checkMarkElement.style.opacity = "0"; menuItemElement.appendChild(checkMarkElement); menuItemElement.appendChild(document.createTextNode(item.label)); menuItemElement.addEventListener("mousedown", this._menuItemMouseDown.bind(this), false); menuItemElement.addEventListener("mouseup", this._menuItemMouseUp.bind(this), false); menuItemElement.addEventListener("mouseover", this._menuItemMouseOver.bind(this), false); menuItemElement.addEventListener("mouseout", this._menuItemMouseOut.bind(this), false); menuItemElement._actionId = item.id; return menuItemElement; }, _createSubMenu: function(item) { var menuItemElement = document.createElement("div"); menuItemElement.className = "soft-context-menu-item"; menuItemElement._subItems = item.subItems; var checkMarkElement = document.createElement("span"); checkMarkElement.textContent = "\u2713 "; checkMarkElement.className = "soft-context-menu-item-checkmark"; checkMarkElement.style.opacity = "0"; menuItemElement.appendChild(checkMarkElement); var subMenuArrowElement = document.createElement("span"); subMenuArrowElement.textContent = "\u25B6"; subMenuArrowElement.className = "soft-context-menu-item-submenu-arrow"; menuItemElement.appendChild(document.createTextNode(item.label)); menuItemElement.appendChild(subMenuArrowElement); menuItemElement.addEventListener("mousedown", this._menuItemMouseDown.bind(this), false); menuItemElement.addEventListener("mouseup", this._menuItemMouseUp.bind(this), false); menuItemElement.addEventListener("mouseover", this._menuItemMouseOver.bind(this), false); menuItemElement.addEventListener("mouseout", this._menuItemMouseOut.bind(this), false); return menuItemElement; }, _createSeparator: function() { var separatorElement = document.createElement("div"); separatorElement.className = "soft-context-menu-separator"; separatorElement._isSeparator = true; separatorElement.addEventListener("mouseover", this._hideSubMenu.bind(this), false); separatorElement.createChild("div", "separator-line"); return separatorElement; }, _menuItemMouseDown: function(event) { event.consume(true); }, _menuItemMouseUp: function(event) { this._triggerAction(event.target, event); event.consume(); }, _focus: function() { this._contextMenuElement.focus(); }, _triggerAction: function(menuItemElement, event) { if (!menuItemElement._subItems) { this._discardMenu(true, event); if (typeof menuItemElement._actionId !== "undefined") { WebInspector.contextMenuItemSelected(menuItemElement._actionId); delete menuItemElement._actionId; } return; } this._showSubMenu(menuItemElement, event); event.consume(); }, _showSubMenu: function(menuItemElement, event) { if (menuItemElement._subMenuTimer) { clearTimeout(menuItemElement._subMenuTimer); delete menuItemElement._subMenuTimer; } if (this._subMenu) return; this._subMenu = new WebInspector.SoftContextMenu(menuItemElement._subItems, this); this._subMenu.show(this._buildMouseEventForSubMenu(menuItemElement)); }, _buildMouseEventForSubMenu: function(subMenuItemElement) { var subMenuOffset = { x: subMenuItemElement.offsetWidth - 3, y: subMenuItemElement.offsetTop - 1 }; var targetX = this._x + subMenuOffset.x; var targetY = this._y + subMenuOffset.y; var targetPageX = parseInt(this._contextMenuElement.style.left, 10) + subMenuOffset.x; var targetPageY = parseInt(this._contextMenuElement.style.top, 10) + subMenuOffset.y; return { x: targetX, y: targetY, pageX: targetPageX, pageY: targetPageY, consume: function() {} }; }, _hideSubMenu: function() { if (!this._subMenu) return; this._subMenu._discardSubMenus(); this._focus(); }, _menuItemMouseOver: function(event) { this._highlightMenuItem(event.target); }, _menuItemMouseOut: function(event) { if (!this._subMenu || !event.relatedTarget) { this._highlightMenuItem(null); return; } var relatedTarget = event.relatedTarget; if (this._contextMenuElement.isSelfOrAncestor(relatedTarget) || relatedTarget.hasStyleClass("soft-context-menu-glass-pane")) this._highlightMenuItem(null); }, _highlightMenuItem: function(menuItemElement) { if (this._highlightedMenuItemElement === menuItemElement) return; this._hideSubMenu(); if (this._highlightedMenuItemElement) { this._highlightedMenuItemElement.removeStyleClass("soft-context-menu-item-mouse-over"); if (this._highlightedMenuItemElement._subItems && this._highlightedMenuItemElement._subMenuTimer) { clearTimeout(this._highlightedMenuItemElement._subMenuTimer); delete this._highlightedMenuItemElement._subMenuTimer; } } this._highlightedMenuItemElement = menuItemElement; if (this._highlightedMenuItemElement) { this._highlightedMenuItemElement.addStyleClass("soft-context-menu-item-mouse-over"); this._contextMenuElement.focus(); if (this._highlightedMenuItemElement._subItems && !this._highlightedMenuItemElement._subMenuTimer) this._highlightedMenuItemElement._subMenuTimer = setTimeout(this._showSubMenu.bind(this, this._highlightedMenuItemElement, this._buildMouseEventForSubMenu(this._highlightedMenuItemElement)), 150); } }, _highlightPrevious: function() { var menuItemElement = this._highlightedMenuItemElement ? this._highlightedMenuItemElement.previousSibling : this._contextMenuElement.lastChild; while (menuItemElement && menuItemElement._isSeparator) menuItemElement = menuItemElement.previousSibling; if (menuItemElement) this._highlightMenuItem(menuItemElement); }, _highlightNext: function() { var menuItemElement = this._highlightedMenuItemElement ? this._highlightedMenuItemElement.nextSibling : this._contextMenuElement.firstChild; while (menuItemElement && menuItemElement._isSeparator) menuItemElement = menuItemElement.nextSibling; if (menuItemElement) this._highlightMenuItem(menuItemElement); }, _menuKeyDown: function(event) { switch (event.keyIdentifier) { case "Up": this._highlightPrevious(); break; case "Down": this._highlightNext(); break; case "Left": if (this._parentMenu) { this._highlightMenuItem(null); this._parentMenu._focus(); } break; case "Right": if (!this._highlightedMenuItemElement) break; if (this._highlightedMenuItemElement._subItems) { this._showSubMenu(this._highlightedMenuItemElement, this._buildMouseEventForSubMenu(this._highlightedMenuItemElement)); this._subMenu._focus(); this._subMenu._highlightNext(); } break; case "U+001B": this._discardMenu(true, event); break; case "Enter": if (!isEnterKey(event)) break; case "U+0020": if (this._highlightedMenuItemElement) this._triggerAction(this._highlightedMenuItemElement, event); break; } event.consume(true); }, _glassPaneMouseUp: function(event) { if (event.x === this._x && event.y === this._y && new Date().getTime() - this._time < 300) return; this._discardMenu(true, event); event.consume(); }, _discardMenu: function(closeParentMenus, event) { if (this._subMenu && !closeParentMenus) return; if (this._glassPaneElement) { var glassPane = this._glassPaneElement; delete this._glassPaneElement; document.body.removeChild(glassPane); if (this._parentMenu) { delete this._parentMenu._subMenu; if (closeParentMenus) this._parentMenu._discardMenu(closeParentMenus, event); } if (event) event.consume(true); } else if (this._parentMenu && this._contextMenuElement.parentElement) { this._discardSubMenus(); if (closeParentMenus) this._parentMenu._discardMenu(closeParentMenus, event); if (event) event.consume(true); } }, _discardSubMenus: function() { if (this._subMenu) this._subMenu._discardSubMenus(); if (this._contextMenuElement.parentElement) this._contextMenuElement.parentElement.removeChild(this._contextMenuElement); if (this._parentMenu) delete this._parentMenu._subMenu; } } if (!InspectorFrontendHost.showContextMenu) { InspectorFrontendHost.showContextMenu = function(event, items) { new WebInspector.SoftContextMenu(items).show(event); } } WebInspector.KeyboardShortcut = function() { } WebInspector.KeyboardShortcut.Modifiers = { None: 0, Shift: 1, Ctrl: 2, Alt: 4, Meta: 8, get CtrlOrMeta() { return WebInspector.isMac() ? this.Meta : this.Ctrl; } }; WebInspector.KeyboardShortcut.Key; WebInspector.KeyboardShortcut.Keys = { Backspace: { code: 8, name: "\u21a4" }, Tab: { code: 9, name: { mac: "\u21e5", other: "<Tab>" } }, Enter: { code: 13, name: { mac: "\u21a9", other: "<Enter>" } }, Esc: { code: 27, name: { mac: "\u238b", other: "<Esc>" } }, Space: { code: 32, name: "<Space>" }, PageUp: { code: 33, name: { mac: "\u21de", other: "<PageUp>" } }, PageDown: { code: 34, name: { mac: "\u21df", other: "<PageDown>" } }, End: { code: 35, name: { mac: "\u2197", other: "<End>" } }, Home: { code: 36, name: { mac: "\u2196", other: "<Home>" } }, Left: { code: 37, name: "<Left>" }, Up: { code: 38, name: "<Up>" }, Right: { code: 39, name: "<Right>" }, Down: { code: 40, name: "<Down>" }, Delete: { code: 46, name: "<Del>" }, Zero: { code: 48, name: "0" }, F1: { code: 112, name: "F1" }, F2: { code: 113, name: "F2" }, F3: { code: 114, name: "F3" }, F4: { code: 115, name: "F4" }, F5: { code: 116, name: "F5" }, F6: { code: 117, name: "F6" }, F7: { code: 118, name: "F7" }, F8: { code: 119, name: "F8" }, F9: { code: 120, name: "F9" }, F10: { code: 121, name: "F10" }, F11: { code: 122, name: "F11" }, F12: { code: 123, name: "F12" }, Semicolon: { code: 186, name: ";" }, Plus: { code: 187, name: "+" }, Comma: { code: 188, name: "," }, Minus: { code: 189, name: "-" }, Period: { code: 190, name: "." }, Slash: { code: 191, name: "/" }, Apostrophe: { code: 192, name: "`" }, SingleQuote: { code: 222, name: "\'" }, H: { code: 72, name: "H" } }; WebInspector.KeyboardShortcut.makeKey = function(keyCode, modifiers) { if (typeof keyCode === "string") keyCode = keyCode.charCodeAt(0) - 32; modifiers = modifiers || WebInspector.KeyboardShortcut.Modifiers.None; return WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode, modifiers); } WebInspector.KeyboardShortcut.makeKeyFromEvent = function(keyboardEvent) { var modifiers = WebInspector.KeyboardShortcut.Modifiers.None; if (keyboardEvent.shiftKey) modifiers |= WebInspector.KeyboardShortcut.Modifiers.Shift; if (keyboardEvent.ctrlKey) modifiers |= WebInspector.KeyboardShortcut.Modifiers.Ctrl; if (keyboardEvent.altKey) modifiers |= WebInspector.KeyboardShortcut.Modifiers.Alt; if (keyboardEvent.metaKey) modifiers |= WebInspector.KeyboardShortcut.Modifiers.Meta; return WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyboardEvent.keyCode, modifiers); } WebInspector.KeyboardShortcut.eventHasCtrlOrMeta = function(event) { return WebInspector.isMac() ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey; } WebInspector.KeyboardShortcut.hasNoModifiers = function(event) { return !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey; } WebInspector.KeyboardShortcut.Descriptor; WebInspector.KeyboardShortcut.makeDescriptor = function(key, modifiers) { return { key: WebInspector.KeyboardShortcut.makeKey(typeof key === "string" ? key : key.code, modifiers), name: WebInspector.KeyboardShortcut.shortcutToString(key, modifiers) }; } WebInspector.KeyboardShortcut.shortcutToString = function(key, modifiers) { return WebInspector.KeyboardShortcut._modifiersToString(modifiers) + WebInspector.KeyboardShortcut._keyName(key); } WebInspector.KeyboardShortcut._keyName = function(key) { if (typeof key === "string") return key.toUpperCase(); if (typeof key.name === "string") return key.name; return key.name[WebInspector.platform()] || key.name.other || ''; } WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers = function(keyCode, modifiers) { return (keyCode & 255) | (modifiers << 8); }; WebInspector.KeyboardShortcut._modifiersToString = function(modifiers) { const cmdKey = "\u2318"; const optKey = "\u2325"; const shiftKey = "\u21e7"; const ctrlKey = "\u2303"; var isMac = WebInspector.isMac(); var res = ""; if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Ctrl) res += isMac ? ctrlKey : "<Ctrl> + "; if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Alt) res += isMac ? optKey : "<Alt> + "; if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Shift) res += isMac ? shiftKey : "<Shift> + "; if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Meta) res += isMac ? cmdKey : "<Win> + "; return res; }; WebInspector.KeyboardShortcut.SelectAll = WebInspector.KeyboardShortcut.makeKey("a", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta); WebInspector.TextPrompt = function(completions, stopCharacters) { this._proxyElement; this._proxyElementDisplay = "inline-block"; this._loadCompletions = completions; this._completionStopCharacters = stopCharacters || " =:[({;,!+-*/&|^<>."; this._suggestForceable = true; } WebInspector.TextPrompt.Events = { ItemApplied: "text-prompt-item-applied", ItemAccepted: "text-prompt-item-accepted" }; WebInspector.TextPrompt.prototype = { get proxyElement() { return this._proxyElement; }, setSuggestForceable: function(x) { this._suggestForceable = x; }, setSuggestBoxEnabled: function(className) { this._suggestBoxClassName = className; }, renderAsBlock: function() { this._proxyElementDisplay = "block"; }, attach: function(element) { return this._attachInternal(element); }, attachAndStartEditing: function(element, blurListener) { this._attachInternal(element); this._startEditing(blurListener); return this.proxyElement; }, _attachInternal: function(element) { if (this.proxyElement) throw "Cannot attach an attached TextPrompt"; this._element = element; this._boundOnKeyDown = this.onKeyDown.bind(this); this._boundOnMouseWheel = this.onMouseWheel.bind(this); this._boundSelectStart = this._selectStart.bind(this); this._proxyElement = element.ownerDocument.createElement("span"); this._proxyElement.style.display = this._proxyElementDisplay; element.parentElement.insertBefore(this.proxyElement, element); this.proxyElement.appendChild(element); this._element.addStyleClass("text-prompt"); this._element.addEventListener("keydown", this._boundOnKeyDown, false); this._element.addEventListener("mousewheel", this._boundOnMouseWheel, false); this._element.addEventListener("selectstart", this._boundSelectStart, false); if (typeof this._suggestBoxClassName === "string") this._suggestBox = new WebInspector.TextPrompt.SuggestBox(this, this._element, this._suggestBoxClassName); return this.proxyElement; }, detach: function() { this._removeFromElement(); this.proxyElement.parentElement.insertBefore(this._element, this.proxyElement); this.proxyElement.parentElement.removeChild(this.proxyElement); this._element.removeStyleClass("text-prompt"); this._element.removeEventListener("keydown", this._boundOnKeyDown, false); this._element.removeEventListener("mousewheel", this._boundOnMouseWheel, false); this._element.removeEventListener("selectstart", this._boundSelectStart, false); delete this._proxyElement; WebInspector.restoreFocusFromElement(this._element); }, get text() { return this._element.textContent; }, set text(x) { this._removeSuggestionAids(); if (!x) { this._element.removeChildren(); this._element.appendChild(document.createElement("br")); } else this._element.textContent = x; this.moveCaretToEndOfPrompt(); this._element.scrollIntoView(); }, _removeFromElement: function() { this.clearAutoComplete(true); this._element.removeEventListener("keydown", this._boundOnKeyDown, false); this._element.removeEventListener("selectstart", this._boundSelectStart, false); if (this._isEditing) this._stopEditing(); if (this._suggestBox) this._suggestBox.removeFromElement(); }, _startEditing: function(blurListener) { this._isEditing = true; this._element.addStyleClass("editing"); if (blurListener) { this._blurListener = blurListener; this._element.addEventListener("blur", this._blurListener, false); } this._oldTabIndex = this._element.tabIndex; if (this._element.tabIndex < 0) this._element.tabIndex = 0; WebInspector.setCurrentFocusElement(this._element); }, _stopEditing: function() { this._element.tabIndex = this._oldTabIndex; if (this._blurListener) this._element.removeEventListener("blur", this._blurListener, false); this._element.removeStyleClass("editing"); delete this._isEditing; }, _removeSuggestionAids: function() { this.clearAutoComplete(); this.hideSuggestBox(); }, _selectStart: function(event) { if (this._selectionTimeout) clearTimeout(this._selectionTimeout); this._removeSuggestionAids(); function moveBackIfOutside() { delete this._selectionTimeout; if (!this.isCaretInsidePrompt() && window.getSelection().isCollapsed) { this.moveCaretToEndOfPrompt(); this.autoCompleteSoon(); } } this._selectionTimeout = setTimeout(moveBackIfOutside.bind(this), 100); }, defaultKeyHandler: function(event, force) { this.clearAutoComplete(); this.autoCompleteSoon(force); return false; }, onMouseWheel: function(event) { }, onKeyDown: function(event) { var handled = false; var invokeDefault = true; switch (event.keyIdentifier) { case "Up": handled = this.upKeyPressed(event); break; case "Down": handled = this.downKeyPressed(event); break; case "PageUp": handled = this.pageUpKeyPressed(event); break; case "PageDown": handled = this.pageDownKeyPressed(event); break; case "U+0009": handled = this.tabKeyPressed(event); break; case "Enter": handled = this.enterKeyPressed(event); break; case "Left": case "Home": this._removeSuggestionAids(); invokeDefault = false; break; case "Right": case "End": if (this.isCaretAtEndOfPrompt()) handled = this.acceptAutoComplete(); else this._removeSuggestionAids(); invokeDefault = false; break; case "U+001B": if (this.isSuggestBoxVisible()) { this._suggestBox.hide(); handled = true; } break; case "U+0020": if (this._suggestForceable && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) { this.defaultKeyHandler(event, true); handled = true; } break; case "Alt": case "Meta": case "Shift": case "Control": invokeDefault = false; break; } if (!handled && invokeDefault) handled = this.defaultKeyHandler(event); if (handled) event.consume(true); return handled; }, acceptAutoComplete: function() { var result = false; if (this.isSuggestBoxVisible()) result = this._suggestBox.acceptSuggestion(); if (!result) result = this.acceptSuggestion(); return result; }, clearAutoComplete: function(includeTimeout) { if (includeTimeout && this._completeTimeout) { clearTimeout(this._completeTimeout); delete this._completeTimeout; } delete this._waitingForCompletions; if (!this.autoCompleteElement) return; if (this.autoCompleteElement.parentNode) this.autoCompleteElement.parentNode.removeChild(this.autoCompleteElement); delete this.autoCompleteElement; if (!this._userEnteredRange || !this._userEnteredText) return; this._userEnteredRange.deleteContents(); this._element.normalize(); var userTextNode = document.createTextNode(this._userEnteredText); this._userEnteredRange.insertNode(userTextNode); var selectionRange = document.createRange(); selectionRange.setStart(userTextNode, this._userEnteredText.length); selectionRange.setEnd(userTextNode, this._userEnteredText.length); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(selectionRange); delete this._userEnteredRange; delete this._userEnteredText; }, autoCompleteSoon: function(force) { var immediately = this.isSuggestBoxVisible() || force; if (!this._completeTimeout) this._completeTimeout = setTimeout(this.complete.bind(this, true, force), immediately ? 0 : 250); }, complete: function(auto, force, reverse) { this.clearAutoComplete(true); var selection = window.getSelection(); if (!selection.rangeCount) return; var selectionRange = selection.getRangeAt(0); var isEmptyInput = selectionRange.commonAncestorContainer === this._element; var shouldExit; if (auto && isEmptyInput && !force) shouldExit = true; else if (!auto && !isEmptyInput && !selectionRange.commonAncestorContainer.isDescendant(this._element)) shouldExit = true; else if (auto && !force && !this.isCaretAtEndOfPrompt() && !this.isSuggestBoxVisible()) shouldExit = true; else if (!selection.isCollapsed) shouldExit = true; else if (!force) { var wordSuffixRange = selectionRange.startContainer.rangeOfWord(selectionRange.endOffset, this._completionStopCharacters, this._element, "forward"); if (wordSuffixRange.toString().length) shouldExit = true; } if (shouldExit) { this.hideSuggestBox(); return; } var wordPrefixRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, this._completionStopCharacters, this._element, "backward"); this._waitingForCompletions = true; this._loadCompletions(this.proxyElement, wordPrefixRange, force, this._completionsReady.bind(this, selection, auto, wordPrefixRange, !!reverse)); }, _boxForAnchorAtStart: function(selection, textRange) { var rangeCopy = selection.getRangeAt(0).cloneRange(); var anchorElement = document.createElement("span"); anchorElement.textContent = "\u200B"; textRange.insertNode(anchorElement); var box = anchorElement.boxInWindow(window); anchorElement.parentElement.removeChild(anchorElement); selection.removeAllRanges(); selection.addRange(rangeCopy); return box; }, _buildCommonPrefix: function(completions, wordPrefixLength) { var commonPrefix = completions[0]; for (var i = 0; i < completions.length; ++i) { var completion = completions[i]; var lastIndex = Math.min(commonPrefix.length, completion.length); for (var j = wordPrefixLength; j < lastIndex; ++j) { if (commonPrefix[j] !== completion[j]) { commonPrefix = commonPrefix.substr(0, j); break; } } } return commonPrefix; }, _completionsReady: function(selection, auto, originalWordPrefixRange, reverse, completions, selectedIndex) { if (!this._waitingForCompletions || !completions || !completions.length) { this.hideSuggestBox(); return; } delete this._waitingForCompletions; var selectionRange = selection.getRangeAt(0); var fullWordRange = document.createRange(); fullWordRange.setStart(originalWordPrefixRange.startContainer, originalWordPrefixRange.startOffset); fullWordRange.setEnd(selectionRange.endContainer, selectionRange.endOffset); if (originalWordPrefixRange.toString() + selectionRange.toString() != fullWordRange.toString()) return; selectedIndex = selectedIndex || 0; this._userEnteredRange = fullWordRange; this._userEnteredText = fullWordRange.toString(); if (this._suggestBox) this._suggestBox.updateSuggestions(this._boxForAnchorAtStart(selection, fullWordRange), completions, selectedIndex, !this.isCaretAtEndOfPrompt()); var wordPrefixLength = originalWordPrefixRange.toString().length; if (auto) { var completionText = completions[selectedIndex]; var commonPrefix = this._buildCommonPrefix(completions, wordPrefixLength); this._commonPrefix = commonPrefix; } else { if (completions.length === 1) { var completionText = completions[selectedIndex]; wordPrefixLength = completionText.length; } else { var commonPrefix = this._buildCommonPrefix(completions, wordPrefixLength); wordPrefixLength = commonPrefix.length; if (selection.isCollapsed) var completionText = completions[selectedIndex]; else { var currentText = fullWordRange.toString(); var foundIndex = null; for (var i = 0; i < completions.length; ++i) { if (completions[i] === currentText) foundIndex = i; } var nextIndex = foundIndex + (reverse ? -1 : 1); if (foundIndex === null || nextIndex >= completions.length) var completionText = completions[selectedIndex]; else if (nextIndex < 0) var completionText = completions[completions.length - 1]; else var completionText = completions[nextIndex]; } } } if (auto) { if (this.isCaretAtEndOfPrompt()) { this._userEnteredRange.deleteContents(); this._element.normalize(); var finalSelectionRange = document.createRange(); var prefixText = completionText.substring(0, wordPrefixLength); var suffixText = completionText.substring(wordPrefixLength); var prefixTextNode = document.createTextNode(prefixText); fullWordRange.insertNode(prefixTextNode); this.autoCompleteElement = document.createElement("span"); this.autoCompleteElement.className = "auto-complete-text"; this.autoCompleteElement.textContent = suffixText; prefixTextNode.parentNode.insertBefore(this.autoCompleteElement, prefixTextNode.nextSibling); finalSelectionRange.setStart(prefixTextNode, wordPrefixLength); finalSelectionRange.setEnd(prefixTextNode, wordPrefixLength); selection.removeAllRanges(); selection.addRange(finalSelectionRange); } } else this.applySuggestion(completionText, completions.length > 1, originalWordPrefixRange); }, _completeCommonPrefix: function() { if (!this.autoCompleteElement || !this._commonPrefix || !this._userEnteredText || !this._commonPrefix.startsWith(this._userEnteredText)) return; if (!this.isSuggestBoxVisible()) { this.acceptAutoComplete(); return; } this.autoCompleteElement.textContent = this._commonPrefix.substring(this._userEnteredText.length); this.acceptSuggestion(true) }, applySuggestion: function(completionText, isIntermediateSuggestion, originalPrefixRange) { var wordPrefixLength; if (originalPrefixRange) wordPrefixLength = originalPrefixRange.toString().length; else wordPrefixLength = this._userEnteredText ? this._userEnteredText.length : 0; this._userEnteredRange.deleteContents(); this._element.normalize(); var finalSelectionRange = document.createRange(); var completionTextNode = document.createTextNode(completionText); this._userEnteredRange.insertNode(completionTextNode); if (this.autoCompleteElement && this.autoCompleteElement.parentNode) { this.autoCompleteElement.parentNode.removeChild(this.autoCompleteElement); delete this.autoCompleteElement; } if (isIntermediateSuggestion) finalSelectionRange.setStart(completionTextNode, wordPrefixLength); else finalSelectionRange.setStart(completionTextNode, completionText.length); finalSelectionRange.setEnd(completionTextNode, completionText.length); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(finalSelectionRange); if (isIntermediateSuggestion) this.dispatchEventToListeners(WebInspector.TextPrompt.Events.ItemApplied, { itemText: completionText }); }, acceptSuggestion: function(prefixAccepted) { if (this._isAcceptingSuggestion) return false; if (!this.autoCompleteElement || !this.autoCompleteElement.parentNode) return false; var text = this.autoCompleteElement.textContent; var textNode = document.createTextNode(text); this.autoCompleteElement.parentNode.replaceChild(textNode, this.autoCompleteElement); delete this.autoCompleteElement; var finalSelectionRange = document.createRange(); finalSelectionRange.setStart(textNode, text.length); finalSelectionRange.setEnd(textNode, text.length); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(finalSelectionRange); if (!prefixAccepted) { this.hideSuggestBox(); this.dispatchEventToListeners(WebInspector.TextPrompt.Events.ItemAccepted); } else this.autoCompleteSoon(true); return true; }, hideSuggestBox: function() { if (this.isSuggestBoxVisible()) this._suggestBox.hide(); }, isSuggestBoxVisible: function() { return this._suggestBox && this._suggestBox.visible; }, isCaretInsidePrompt: function() { return this._element.isInsertionCaretInside(); }, isCaretAtEndOfPrompt: function() { var selection = window.getSelection(); if (!selection.rangeCount || !selection.isCollapsed) return false; var selectionRange = selection.getRangeAt(0); var node = selectionRange.startContainer; if (!node.isSelfOrDescendant(this._element)) return false; if (node.nodeType === Node.TEXT_NODE && selectionRange.startOffset < node.nodeValue.length) return false; var foundNextText = false; while (node) { if (node.nodeType === Node.TEXT_NODE && node.nodeValue.length) { if (foundNextText && (!this.autoCompleteElement || !this.autoCompleteElement.isAncestor(node))) return false; foundNextText = true; } node = node.traverseNextNode(this._element); } return true; }, isCaretOnFirstLine: function() { var selection = window.getSelection(); var focusNode = selection.focusNode; if (!focusNode || focusNode.nodeType !== Node.TEXT_NODE || focusNode.parentNode !== this._element) return true; if (focusNode.textContent.substring(0, selection.focusOffset).indexOf("\n") !== -1) return false; focusNode = focusNode.previousSibling; while (focusNode) { if (focusNode.nodeType !== Node.TEXT_NODE) return true; if (focusNode.textContent.indexOf("\n") !== -1) return false; focusNode = focusNode.previousSibling; } return true; }, isCaretOnLastLine: function() { var selection = window.getSelection(); var focusNode = selection.focusNode; if (!focusNode || focusNode.nodeType !== Node.TEXT_NODE || focusNode.parentNode !== this._element) return true; if (focusNode.textContent.substring(selection.focusOffset).indexOf("\n") !== -1) return false; focusNode = focusNode.nextSibling; while (focusNode) { if (focusNode.nodeType !== Node.TEXT_NODE) return true; if (focusNode.textContent.indexOf("\n") !== -1) return false; focusNode = focusNode.nextSibling; } return true; }, moveCaretToEndOfPrompt: function() { var selection = window.getSelection(); var selectionRange = document.createRange(); var offset = this._element.childNodes.length; selectionRange.setStart(this._element, offset); selectionRange.setEnd(this._element, offset); selection.removeAllRanges(); selection.addRange(selectionRange); }, tabKeyPressed: function(event) { this._completeCommonPrefix(); return true; }, enterKeyPressed: function(event) { if (this.isSuggestBoxVisible()) return this._suggestBox.enterKeyPressed(event); return false; }, upKeyPressed: function(event) { if (this.isSuggestBoxVisible()) return this._suggestBox.upKeyPressed(event); return false; }, downKeyPressed: function(event) { if (this.isSuggestBoxVisible()) return this._suggestBox.downKeyPressed(event); return false; }, pageUpKeyPressed: function(event) { if (this.isSuggestBoxVisible()) return this._suggestBox.pageUpKeyPressed(event); return false; }, pageDownKeyPressed: function(event) { if (this.isSuggestBoxVisible()) return this._suggestBox.pageDownKeyPressed(event); return false; }, __proto__: WebInspector.Object.prototype } WebInspector.TextPromptWithHistory = function(completions, stopCharacters) { WebInspector.TextPrompt.call(this, completions, stopCharacters); this._data = []; this._historyOffset = 1; this._coalesceHistoryDupes = true; } WebInspector.TextPromptWithHistory.prototype = { get historyData() { return this._data; }, setCoalesceHistoryDupes: function(x) { this._coalesceHistoryDupes = x; }, setHistoryData: function(data) { this._data = [].concat(data); this._historyOffset = 1; }, pushHistoryItem: function(text) { if (this._uncommittedIsTop) { this._data.pop(); delete this._uncommittedIsTop; } this._historyOffset = 1; if (this._coalesceHistoryDupes && text === this._currentHistoryItem()) return; this._data.push(text); }, _pushCurrentText: function() { if (this._uncommittedIsTop) this._data.pop(); this._uncommittedIsTop = true; this.clearAutoComplete(true); this._data.push(this.text); }, _previous: function() { if (this._historyOffset > this._data.length) return undefined; if (this._historyOffset === 1) this._pushCurrentText(); ++this._historyOffset; return this._currentHistoryItem(); }, _next: function() { if (this._historyOffset === 1) return undefined; --this._historyOffset; return this._currentHistoryItem(); }, _currentHistoryItem: function() { return this._data[this._data.length - this._historyOffset]; }, defaultKeyHandler: function(event, force) { var newText; var isPrevious; switch (event.keyIdentifier) { case "Up": if (!this.isCaretOnFirstLine()) break; newText = this._previous(); isPrevious = true; break; case "Down": if (!this.isCaretOnLastLine()) break; newText = this._next(); break; case "U+0050": if (WebInspector.isMac() && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) { newText = this._previous(); isPrevious = true; } break; case "U+004E": if (WebInspector.isMac() && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) newText = this._next(); break; } if (newText !== undefined) { event.consume(true); this.text = newText; if (isPrevious) { var firstNewlineIndex = this.text.indexOf("\n"); if (firstNewlineIndex === -1) this.moveCaretToEndOfPrompt(); else { var selection = window.getSelection(); var selectionRange = document.createRange(); selectionRange.setStart(this._element.firstChild, firstNewlineIndex); selectionRange.setEnd(this._element.firstChild, firstNewlineIndex); selection.removeAllRanges(); selection.addRange(selectionRange); } } return true; } return WebInspector.TextPrompt.prototype.defaultKeyHandler.apply(this, arguments); }, __proto__: WebInspector.TextPrompt.prototype } WebInspector.TextPrompt.SuggestBox = function(textPrompt, inputElement, className) { this._textPrompt = textPrompt; this._inputElement = inputElement; this._length = 0; this._selectedIndex = -1; this._selectedElement = null; this._boundOnScroll = this._onscrollresize.bind(this, true); this._boundOnResize = this._onscrollresize.bind(this, false); window.addEventListener("scroll", this._boundOnScroll, true); window.addEventListener("resize", this._boundOnResize, true); this._bodyElement = inputElement.ownerDocument.body; this._element = inputElement.ownerDocument.createElement("div"); this._element.className = "suggest-box " + (className || ""); this._element.addEventListener("mousedown", this._onboxmousedown.bind(this), true); this.containerElement = this._element.createChild("div", "container"); this.contentElement = this.containerElement.createChild("div", "content"); } WebInspector.TextPrompt.SuggestBox.prototype = { get visible() { return !!this._element.parentElement; }, get hasSelection() { return !!this._selectedElement; }, _onscrollresize: function(isScroll, event) { if (isScroll && this._element.isAncestor(event.target) || !this.visible) return; this._updateBoxPositionWithExistingAnchor(); }, _updateBoxPositionWithExistingAnchor: function() { this._updateBoxPosition(this._anchorBox); }, _updateBoxPosition: function(anchorBox) { this.contentElement.style.display = "inline-block"; document.body.appendChild(this.contentElement); this.contentElement.positionAt(0, 0); var contentWidth = this.contentElement.offsetWidth; var contentHeight = this.contentElement.offsetHeight; this.contentElement.style.display = "block"; this.containerElement.appendChild(this.contentElement); this._anchorBox = anchorBox; const spacer = 6; const suggestBoxPaddingX = 21; var maxWidth = document.body.offsetWidth - anchorBox.x - spacer; var width = Math.min(contentWidth, maxWidth - suggestBoxPaddingX) + suggestBoxPaddingX; var paddedWidth = contentWidth + suggestBoxPaddingX; var boxX = anchorBox.x; if (width < paddedWidth) { maxWidth = document.body.offsetWidth - spacer; width = Math.min(contentWidth, maxWidth - suggestBoxPaddingX) + suggestBoxPaddingX; boxX = document.body.offsetWidth - width; } const suggestBoxPaddingY = 2; var boxY; var aboveHeight = anchorBox.y; var underHeight = document.body.offsetHeight - anchorBox.y - anchorBox.height; var maxHeight = Math.max(underHeight, aboveHeight) - spacer; var height = Math.min(contentHeight, maxHeight - suggestBoxPaddingY) + suggestBoxPaddingY; if (underHeight >= aboveHeight) { boxY = anchorBox.y + anchorBox.height; this._element.removeStyleClass("above-anchor"); this._element.addStyleClass("under-anchor"); } else { boxY = anchorBox.y - height; this._element.removeStyleClass("under-anchor"); this._element.addStyleClass("above-anchor"); } this._element.positionAt(boxX, boxY); this._element.style.width = width + "px"; this._element.style.height = height + "px"; }, _onboxmousedown: function(event) { event.preventDefault(); }, hide: function() { if (!this.visible) return; this._element.parentElement.removeChild(this._element); delete this._selectedElement; }, removeFromElement: function() { window.removeEventListener("scroll", this._boundOnScroll, true); window.removeEventListener("resize", this._boundOnResize, true); this.hide(); }, _applySuggestion: function(text, isIntermediateSuggestion) { if (!this.visible || !(text || this._selectedElement)) return false; var suggestion = text || this._selectedElement.textContent; if (!suggestion) return false; this._textPrompt.applySuggestion(suggestion, isIntermediateSuggestion); return true; }, acceptSuggestion: function(text) { var result = this._applySuggestion(text, false); this.hide(); if (!result) return false; this._textPrompt.acceptSuggestion(); return true; }, _selectClosest: function(shift, isCircular) { if (!this._length) return false; var index = this._selectedIndex + shift; if (isCircular) index = (this._length + index) % this._length; else index = Number.constrain(index, 0, this._length - 1); this._selectItem(index); this._applySuggestion(undefined, true); return true; }, updateSuggestions: function(anchorBox, completions, selectedIndex, canShowForSingleItem) { if (this._suggestTimeout) { clearTimeout(this._suggestTimeout); delete this._suggestTimeout; } this._completionsReady(anchorBox, completions, selectedIndex, canShowForSingleItem); }, _onItemMouseDown: function(text, event) { this.acceptSuggestion(text); event.consume(true); }, _createItemElement: function(prefix, text) { var element = document.createElement("div"); element.className = "suggest-box-content-item source-code"; element.tabIndex = -1; if (prefix && prefix.length && !text.indexOf(prefix)) { var prefixElement = element.createChild("span", "prefix"); prefixElement.textContent = prefix; var suffixElement = element.createChild("span", "suffix"); suffixElement.textContent = text.substring(prefix.length); } else { var suffixElement = element.createChild("span", "suffix"); suffixElement.textContent = text; } element.addEventListener("mousedown", this._onItemMouseDown.bind(this, text), false); return element; }, _updateItems: function(items, selectedIndex) { this._length = items.length; this.contentElement.removeChildren(); var userEnteredText = this._textPrompt._userEnteredText; for (var i = 0; i < items.length; ++i) { var item = items[i]; var currentItemElement = this._createItemElement(userEnteredText, item); this.contentElement.appendChild(currentItemElement); } this._selectedElement = null; if (typeof selectedIndex === "number") this._selectItem(selectedIndex); }, _selectItem: function(index) { if (this._selectedElement) this._selectedElement.classList.remove("selected"); this._selectedIndex = index; this._selectedElement = this.contentElement.children[index]; this._selectedElement.classList.add("selected"); this._selectedElement.scrollIntoViewIfNeeded(false); }, _canShowBox: function(completions, canShowForSingleItem) { if (!completions || !completions.length) return false; if (completions.length > 1) return true; return canShowForSingleItem && completions[0] !== this._textPrompt._userEnteredText; }, _rememberRowCountPerViewport: function() { if (!this.contentElement.firstChild) return; this._rowCountPerViewport = Math.floor(this.containerElement.offsetHeight / this.contentElement.firstChild.offsetHeight); }, _completionsReady: function(anchorBox, completions, selectedIndex, canShowForSingleItem) { if (this._canShowBox(completions, canShowForSingleItem)) { this._updateItems(completions, selectedIndex); this._updateBoxPosition(anchorBox); if (!this.visible) this._bodyElement.appendChild(this._element); this._rememberRowCountPerViewport(); } else this.hide(); }, upKeyPressed: function(event) { return this._selectClosest(-1, true); }, downKeyPressed: function(event) { return this._selectClosest(1, true); }, pageUpKeyPressed: function(event) { return this._selectClosest(-this._rowCountPerViewport, false); }, pageDownKeyPressed: function(event) { return this._selectClosest(this._rowCountPerViewport, false); }, enterKeyPressed: function(event) { var hasSelectedItem = !!this._selectedElement; this.acceptSuggestion(); return hasSelectedItem; }, tabKeyPressed: function(event) { return this.enterKeyPressed(event); } } WebInspector.Popover = function(popoverHelper) { WebInspector.View.call(this); this.markAsRoot(); this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll"; this._popupArrowElement = document.createElement("div"); this._popupArrowElement.className = "arrow"; this.element.appendChild(this._popupArrowElement); this._contentDiv = document.createElement("div"); this._contentDiv.className = "content"; this.element.appendChild(this._contentDiv); this._popoverHelper = popoverHelper; } WebInspector.Popover.prototype = { show: function(element, anchor, preferredWidth, preferredHeight) { this._innerShow(null, element, anchor, preferredWidth, preferredHeight); }, showView: function(view, anchor, preferredWidth, preferredHeight) { this._innerShow(view, view.element, anchor, preferredWidth, preferredHeight); }, _innerShow: function(view, contentElement, anchor, preferredWidth, preferredHeight) { if (this._disposed) return; this.contentElement = contentElement; if (WebInspector.Popover._popover) WebInspector.Popover._popover.detach(); WebInspector.Popover._popover = this; var preferredSize = view ? view.measurePreferredSize() : this.contentElement.measurePreferredSize(); preferredWidth = preferredWidth || preferredSize.width; preferredHeight = preferredHeight || preferredSize.height; WebInspector.View.prototype.show.call(this, document.body); if (view) view.show(this._contentDiv); else this._contentDiv.appendChild(this.contentElement); this._positionElement(anchor, preferredWidth, preferredHeight); if (this._popoverHelper) { this.element.addEventListener("mousemove", this._popoverHelper._killHidePopoverTimer.bind(this._popoverHelper), true); this.element.addEventListener("mouseout", this._popoverHelper._popoverMouseOut.bind(this._popoverHelper), true); } }, hide: function() { this.detach(); delete WebInspector.Popover._popover; }, get disposed() { return this._disposed; }, dispose: function() { if (this.isShowing()) this.hide(); this._disposed = true; }, setCanShrink: function(canShrink) { this._hasFixedHeight = !canShrink; this._contentDiv.addStyleClass("fixed-height"); }, _positionElement: function(anchorElement, preferredWidth, preferredHeight) { const borderWidth = 25; const scrollerWidth = this._hasFixedHeight ? 0 : 11; const arrowHeight = 15; const arrowOffset = 10; const borderRadius = 10; preferredWidth = Math.max(preferredWidth, 50); const totalWidth = window.innerWidth; const totalHeight = window.innerHeight; var anchorBox = anchorElement.boxInWindow(window); var newElementPosition = { x: 0, y: 0, width: preferredWidth + scrollerWidth, height: preferredHeight }; var verticalAlignment; var roomAbove = anchorBox.y; var roomBelow = totalHeight - anchorBox.y - anchorBox.height; if (roomAbove > roomBelow) { if (anchorBox.y > newElementPosition.height + arrowHeight + borderRadius) newElementPosition.y = anchorBox.y - newElementPosition.height - arrowHeight; else { newElementPosition.y = borderRadius; newElementPosition.height = anchorBox.y - borderRadius * 2 - arrowHeight; if (this._hasFixedHeight && newElementPosition.height < preferredHeight) { newElementPosition.y = borderRadius; newElementPosition.height = preferredHeight; } } verticalAlignment = "bottom"; } else { newElementPosition.y = anchorBox.y + anchorBox.height + arrowHeight; if (newElementPosition.y + newElementPosition.height + arrowHeight - borderWidth >= totalHeight) { newElementPosition.height = totalHeight - anchorBox.y - anchorBox.height - borderRadius * 2 - arrowHeight; if (this._hasFixedHeight && newElementPosition.height < preferredHeight) { newElementPosition.y = totalHeight - preferredHeight - borderRadius; newElementPosition.height = preferredHeight; } } verticalAlignment = "top"; } var horizontalAlignment; if (anchorBox.x + newElementPosition.width < totalWidth) { newElementPosition.x = Math.max(borderRadius, anchorBox.x - borderRadius - arrowOffset); horizontalAlignment = "left"; } else if (newElementPosition.width + borderRadius * 2 < totalWidth) { newElementPosition.x = totalWidth - newElementPosition.width - borderRadius; horizontalAlignment = "right"; var arrowRightPosition = Math.max(0, totalWidth - anchorBox.x - anchorBox.width - borderRadius - arrowOffset); arrowRightPosition += anchorBox.width / 2; arrowRightPosition = Math.min(arrowRightPosition, newElementPosition.width - borderRadius - arrowOffset); this._popupArrowElement.style.right = arrowRightPosition + "px"; } else { newElementPosition.x = borderRadius; newElementPosition.width = totalWidth - borderRadius * 2; newElementPosition.height += scrollerWidth; horizontalAlignment = "left"; if (verticalAlignment === "bottom") newElementPosition.y -= scrollerWidth; this._popupArrowElement.style.left = Math.max(0, anchorBox.x - borderRadius * 2 - arrowOffset) + "px"; this._popupArrowElement.style.left += anchorBox.width / 2; } this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll " + verticalAlignment + "-" + horizontalAlignment + "-arrow"; this.element.positionAt(newElementPosition.x - borderWidth, newElementPosition.y - borderWidth); this.element.style.width = newElementPosition.width + borderWidth * 2 + "px"; this.element.style.height = newElementPosition.height + borderWidth * 2 + "px"; }, __proto__: WebInspector.View.prototype } WebInspector.PopoverHelper = function(panelElement, getAnchor, showPopover, onHide, disableOnClick) { this._panelElement = panelElement; this._getAnchor = getAnchor; this._showPopover = showPopover; this._onHide = onHide; this._disableOnClick = !!disableOnClick; panelElement.addEventListener("mousedown", this._mouseDown.bind(this), false); panelElement.addEventListener("mousemove", this._mouseMove.bind(this), false); panelElement.addEventListener("mouseout", this._mouseOut.bind(this), false); this.setTimeout(1000); } WebInspector.PopoverHelper.prototype = { setTimeout: function(timeout) { this._timeout = timeout; }, _mouseDown: function(event) { if (this._disableOnClick || !event.target.isSelfOrDescendant(this._hoverElement)) this.hidePopover(); else { this._killHidePopoverTimer(); this._handleMouseAction(event, true); } }, _mouseMove: function(event) { if (event.target.isSelfOrDescendant(this._hoverElement)) return; this._startHidePopoverTimer(); this._handleMouseAction(event, false); }, _popoverMouseOut: function(event) { if (!this.isPopoverVisible()) return; if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this._popover._contentDiv)) this._startHidePopoverTimer(); }, _mouseOut: function(event) { if (!this.isPopoverVisible()) return; if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this._hoverElement)) this._startHidePopoverTimer(); }, _startHidePopoverTimer: function() { if (!this._popover || this._hidePopoverTimer) return; function doHide() { this._hidePopover(); delete this._hidePopoverTimer; } this._hidePopoverTimer = setTimeout(doHide.bind(this), this._timeout / 2); }, _handleMouseAction: function(event, isMouseDown) { this._resetHoverTimer(); if (event.which && this._disableOnClick) return; this._hoverElement = this._getAnchor(event.target, event); if (!this._hoverElement) return; const toolTipDelay = isMouseDown ? 0 : (this._popup ? this._timeout * 0.6 : this._timeout); this._hoverTimer = setTimeout(this._mouseHover.bind(this, this._hoverElement), toolTipDelay); }, _resetHoverTimer: function() { if (this._hoverTimer) { clearTimeout(this._hoverTimer); delete this._hoverTimer; } }, isPopoverVisible: function() { return !!this._popover; }, hidePopover: function() { this._resetHoverTimer(); this._hidePopover(); }, _hidePopover: function() { if (!this._popover) return; if (this._onHide) this._onHide(); this._popover.dispose(); delete this._popover; this._hoverElement = null; }, _mouseHover: function(element) { delete this._hoverTimer; this._hidePopover(); this._popover = new WebInspector.Popover(this); this._showPopover(element, this._popover); }, _killHidePopoverTimer: function() { if (this._hidePopoverTimer) { clearTimeout(this._hidePopoverTimer); delete this._hidePopoverTimer; this._resetHoverTimer(); } } } WebInspector.Placard = function(title, subtitle) { this.element = document.createElement("div"); this.element.className = "placard"; this.element.placard = this; this.titleElement = document.createElement("div"); this.titleElement.className = "title"; this.subtitleElement = document.createElement("div"); this.subtitleElement.className = "subtitle"; this.element.appendChild(this.subtitleElement); this.element.appendChild(this.titleElement); this.title = title; this.subtitle = subtitle; this.selected = false; } WebInspector.Placard.prototype = { get title() { return this._title; }, set title(x) { if (this._title === x) return; this._title = x; this.titleElement.textContent = x; }, get subtitle() { return this._subtitle; }, set subtitle(x) { if (this._subtitle === x) return; this._subtitle = x; this.subtitleElement.textContent = x; }, get selected() { return this._selected; }, set selected(x) { if (x) this.select(); else this.deselect(); }, select: function() { if (this._selected) return; this._selected = true; this.element.addStyleClass("selected"); }, deselect: function() { if (!this._selected) return; this._selected = false; this.element.removeStyleClass("selected"); }, toggleSelected: function() { this.selected = !this.selected; }, discard: function() { } } WebInspector.TabbedPane = function() { WebInspector.View.call(this); this.registerRequiredCSS("tabbedPane.css"); this.element.addStyleClass("tabbed-pane"); this._headerElement = this.element.createChild("div", "tabbed-pane-header"); this._headerContentsElement = this._headerElement.createChild("div", "tabbed-pane-header-contents"); this._tabsElement = this._headerContentsElement.createChild("div", "tabbed-pane-header-tabs"); this._contentElement = this.element.createChild("div", "tabbed-pane-content"); this._tabs = []; this._tabsHistory = []; this._tabsById = {}; this.element.addEventListener("click", this.focus.bind(this), false); this.element.addEventListener("mouseup", this.onMouseUp.bind(this), false); this._dropDownButton = this._createDropDownButton(); } WebInspector.TabbedPane.EventTypes = { TabSelected: "TabSelected", TabClosed: "TabClosed" } WebInspector.TabbedPane.prototype = { get visibleView() { return this._currentTab ? this._currentTab.view : null; }, get selectedTabId() { return this._currentTab ? this._currentTab.id : null; }, set shrinkableTabs(shrinkableTabs) { this._shrinkableTabs = shrinkableTabs; }, set verticalTabLayout(verticalTabLayout) { this._verticalTabLayout = verticalTabLayout; }, set closeableTabs(closeableTabs) { this._closeableTabs = closeableTabs; }, defaultFocusedElement: function() { return this.visibleView ? this.visibleView.defaultFocusedElement() : null; }, onMouseUp: function(event) { if (event.button === 1) event.consume(true); }, appendTab: function(id, tabTitle, view, tabTooltip, userGesture) { var tab = new WebInspector.TabbedPaneTab(this, id, tabTitle, this._closeableTabs, view, tabTooltip); this._tabsById[id] = tab; this._tabs.push(tab); this._tabsHistory.push(tab); if (this._tabsHistory[0] === tab) this.selectTab(tab.id, userGesture); this._updateTabElements(); }, closeTab: function(id, userGesture) { this.closeTabs([id], userGesture); }, closeTabs: function(ids, userGesture) { for (var i = 0; i < ids.length; ++i) this._innerCloseTab(ids[i], userGesture); this._updateTabElements(); if (this._tabsHistory.length) this.selectTab(this._tabsHistory[0].id, userGesture); }, _innerCloseTab: function(id, userGesture) { if (this._currentTab && this._currentTab.id === id) this._hideCurrentTab(); var tab = this._tabsById[id]; delete this._tabsById[id]; this._tabsHistory.splice(this._tabsHistory.indexOf(tab), 1); this._tabs.splice(this._tabs.indexOf(tab), 1); if (tab._shown) this._hideTabElement(tab); var eventData = { tabId: id, view: tab.view, isUserGesture: userGesture }; this.dispatchEventToListeners(WebInspector.TabbedPane.EventTypes.TabClosed, eventData); return true; }, closeAllTabs: function(userGesture) { var tabs = this._tabs.slice(); for (var i = 0; i < tabs.length; ++i) this._innerCloseTab(tabs[i].id, userGesture); this._updateTabElements(); }, closeOtherTabs: function(id) { var tabs = this._tabs.slice(); for (var i = 0; i < tabs.length; ++i) { if (tabs[i].id !== id) this._innerCloseTab(tabs[i].id, true); } this._updateTabElements(); this.selectTab(id, true); }, selectTab: function(id, userGesture) { var tab = this._tabsById[id]; if (!tab) return; if (this._currentTab && this._currentTab.id === id) return; this._hideCurrentTab(); this._showTab(tab); this._currentTab = tab; this._tabsHistory.splice(this._tabsHistory.indexOf(tab), 1); this._tabsHistory.splice(0, 0, tab); this._updateTabElements(); var eventData = { tabId: id, view: tab.view, isUserGesture: userGesture }; this.dispatchEventToListeners(WebInspector.TabbedPane.EventTypes.TabSelected, eventData); return true; }, lastOpenedTabIds: function(tabsCount) { function tabToTabId(tab) { return tab.id; } return this._tabsHistory.slice(0, tabsCount).map(tabToTabId); }, changeTabTitle: function(id, tabTitle) { var tab = this._tabsById[id]; tab.title = tabTitle; this._updateTabElements(); }, changeTabView: function(id, view) { var tab = this._tabsById[id]; if (this._currentTab && this._currentTab.id === tab.id) { this._hideTab(tab); tab.view = view; this._showTab(tab); } else tab.view = view; }, changeTabTooltip: function(id, tabTooltip) { var tab = this._tabsById[id]; tab.tooltip = tabTooltip; }, onResize: function() { this._updateTabElements(); }, _updateTabElements: function() { WebInspector.invokeOnceAfterBatchUpdate(this, this._innerUpdateTabElements); }, _innerUpdateTabElements: function() { if (!this.isShowing()) return; if (!this._tabs.length) this._contentElement.addStyleClass("has-no-tabs"); else this._contentElement.removeStyleClass("has-no-tabs"); if (!this._measuredDropDownButtonWidth) this._measureDropDownButton(); this._updateWidths(); this._updateTabsDropDown(); }, _showTabElement: function(index, tab) { if (index >= this._tabsElement.children.length) this._tabsElement.appendChild(tab.tabElement); else this._tabsElement.insertBefore(tab.tabElement, this._tabsElement.children[index]); tab._shown = true; }, _hideTabElement: function(tab) { this._tabsElement.removeChild(tab.tabElement); tab._shown = false; }, _createDropDownButton: function() { var dropDownContainer = document.createElement("div"); dropDownContainer.addStyleClass("tabbed-pane-header-tabs-drop-down-container"); var dropDownButton = dropDownContainer.createChild("div", "tabbed-pane-header-tabs-drop-down"); dropDownButton.appendChild(document.createTextNode("\u00bb")); this._tabsSelect = dropDownButton.createChild("select", "tabbed-pane-header-tabs-drop-down-select"); this._tabsSelect.addEventListener("change", this._tabsSelectChanged.bind(this), false); return dropDownContainer; }, _totalWidth: function() { return this._headerContentsElement.getBoundingClientRect().width; }, _updateTabsDropDown: function() { var tabsToShowIndexes = this._tabsToShowIndexes(this._tabs, this._tabsHistory, this._totalWidth(), this._measuredDropDownButtonWidth); for (var i = 0; i < this._tabs.length; ++i) { if (this._tabs[i]._shown && tabsToShowIndexes.indexOf(i) === -1) this._hideTabElement(this._tabs[i]); } for (var i = 0; i < tabsToShowIndexes.length; ++i) { var tab = this._tabs[tabsToShowIndexes[i]]; if (!tab._shown) this._showTabElement(i, tab); } this._populateDropDownFromIndex(); }, _populateDropDownFromIndex: function() { if (this._dropDownButton.parentElement) this._headerContentsElement.removeChild(this._dropDownButton); this._tabsSelect.removeChildren(); var tabsToShow = []; for (var i = 0; i < this._tabs.length; ++i) { if (!this._tabs[i]._shown) tabsToShow.push(this._tabs[i]); continue; } function compareFunction(tab1, tab2) { return tab1.title.localeCompare(tab2.title); } tabsToShow.sort(compareFunction); for (var i = 0; i < tabsToShow.length; ++i) { var option = new Option(tabsToShow[i].title); option.tab = tabsToShow[i]; this._tabsSelect.appendChild(option); } if (this._tabsSelect.options.length) { this._headerContentsElement.appendChild(this._dropDownButton); this._tabsSelect.selectedIndex = -1; } }, _tabsSelectChanged: function() { var options = this._tabsSelect.options; var selectedOption = options[this._tabsSelect.selectedIndex]; this.selectTab(selectedOption.tab.id, true); }, _measureDropDownButton: function() { this._dropDownButton.addStyleClass("measuring"); this._headerContentsElement.appendChild(this._dropDownButton); this._measuredDropDownButtonWidth = this._dropDownButton.getBoundingClientRect().width; this._headerContentsElement.removeChild(this._dropDownButton); this._dropDownButton.removeStyleClass("measuring"); }, _updateWidths: function() { var measuredWidths = this._measureWidths(); var maxWidth = this._shrinkableTabs ? this._calculateMaxWidth(measuredWidths.slice(), this._totalWidth()) : Number.MAX_VALUE; var i = 0; for (var tabId in this._tabs) { var tab = this._tabs[tabId]; tab.setWidth(this._verticalTabLayout ? -1 : Math.min(maxWidth, measuredWidths[i++])); } }, _measureWidths: function() { var measuringTabElements = []; for (var tabId in this._tabs) { var tab = this._tabs[tabId]; if (typeof tab._measuredWidth === "number") continue; var measuringTabElement = tab._createTabElement(true); measuringTabElement.__tab = tab; measuringTabElements.push(measuringTabElement); this._tabsElement.appendChild(measuringTabElement); } for (var i = 0; i < measuringTabElements.length; ++i) measuringTabElements[i].__tab._measuredWidth = measuringTabElements[i].getBoundingClientRect().width; for (var i = 0; i < measuringTabElements.length; ++i) measuringTabElements[i].parentElement.removeChild(measuringTabElements[i]); var measuredWidths = []; for (var tabId in this._tabs) measuredWidths.push(this._tabs[tabId]._measuredWidth); return measuredWidths; }, _calculateMaxWidth: function(measuredWidths, totalWidth) { if (!measuredWidths.length) return 0; measuredWidths.sort(function(x, y) { return x - y }); var totalMeasuredWidth = 0; for (var i = 0; i < measuredWidths.length; ++i) totalMeasuredWidth += measuredWidths[i]; if (totalWidth >= totalMeasuredWidth) return measuredWidths[measuredWidths.length - 1]; var totalExtraWidth = 0; for (var i = measuredWidths.length - 1; i > 0; --i) { var extraWidth = measuredWidths[i] - measuredWidths[i - 1]; totalExtraWidth += (measuredWidths.length - i) * extraWidth; if (totalWidth + totalExtraWidth >= totalMeasuredWidth) return measuredWidths[i - 1] + (totalWidth + totalExtraWidth - totalMeasuredWidth) / (measuredWidths.length - i); } return totalWidth / measuredWidths.length; }, _tabsToShowIndexes: function(tabsOrdered, tabsHistory, totalWidth, measuredDropDownButtonWidth) { var tabsToShowIndexes = []; var totalTabsWidth = 0; for (var i = 0; i < tabsHistory.length; ++i) { totalTabsWidth += tabsHistory[i].width(); var minimalRequiredWidth = totalTabsWidth; if (i !== tabsHistory.length - 1) minimalRequiredWidth += measuredDropDownButtonWidth; if (!this._verticalTabLayout && minimalRequiredWidth > totalWidth) break; tabsToShowIndexes.push(tabsOrdered.indexOf(tabsHistory[i])); } tabsToShowIndexes.sort(function(x, y) { return x - y }); return tabsToShowIndexes; }, _hideCurrentTab: function() { if (!this._currentTab) return; this._hideTab(this._currentTab); delete this._currentTab; }, _showTab: function(tab) { tab.tabElement.addStyleClass("selected"); tab.view.show(this._contentElement); }, _hideTab: function(tab) { tab.tabElement.removeStyleClass("selected"); tab.view.detach(); }, canHighlightLine: function() { return this._currentTab && this._currentTab.view && this._currentTab.view.canHighlightLine(); }, highlightLine: function(line) { if (this.canHighlightLine()) this._currentTab.view.highlightLine(line); }, elementsToRestoreScrollPositionsFor: function() { return [ this._contentElement ]; }, _insertBefore: function(tab, index) { this._tabsElement.insertBefore(tab._tabElement, this._tabsElement.childNodes[index]); var oldIndex = this._tabs.indexOf(tab); this._tabs.splice(oldIndex, 1); if (oldIndex < index) --index; this._tabs.splice(index, 0, tab); }, __proto__: WebInspector.View.prototype } WebInspector.TabbedPaneTab = function(tabbedPane, id, title, closeable, view, tooltip) { this._closeable = closeable; this._tabbedPane = tabbedPane; this._id = id; this._title = title; this._tooltip = tooltip; this._view = view; this._shown = false; this._measuredWidth; this._tabElement; } WebInspector.TabbedPaneTab.prototype = { get id() { return this._id; }, get title() { return this._title; }, set title(title) { if (title === this._title) return; this._title = title; if (this._titleElement) this._titleElement.textContent = title; delete this._measuredWidth; }, get view() { return this._view; }, set view(view) { this._view = view; }, get tooltip() { return this._tooltip; }, set tooltip(tooltip) { this._tooltip = tooltip; if (this._titleElement) this._titleElement.title = tooltip || ""; }, get tabElement() { if (typeof(this._tabElement) !== "undefined") return this._tabElement; this._createTabElement(false); return this._tabElement; }, width: function() { return this._width; }, setWidth: function(width) { this.tabElement.style.width = width === -1 ? "" : (width + "px"); this._width = width; }, _createTabElement: function(measuring) { var tabElement = document.createElement("div"); tabElement.addStyleClass("tabbed-pane-header-tab"); tabElement.id = "tab-" + this._id; tabElement.tabIndex = -1; var titleElement = tabElement.createChild("span", "tabbed-pane-header-tab-title"); titleElement.textContent = this.title; titleElement.title = this.tooltip || ""; if (!measuring) this._titleElement = titleElement; if (this._closeable) { var closeButtonSpan = tabElement.createChild("span", "tabbed-pane-header-tab-close-button"); closeButtonSpan.textContent = "\u00D7"; } if (measuring) tabElement.addStyleClass("measuring"); else { this._tabElement = tabElement; tabElement.addEventListener("click", this._tabClicked.bind(this), false); tabElement.addEventListener("mousedown", this._tabMouseDown.bind(this), false); if (this._closeable) { tabElement.addEventListener("contextmenu", this._tabContextMenu.bind(this), false); WebInspector.installDragHandle(tabElement, this._startTabDragging.bind(this), this._tabDragging.bind(this), this._endTabDragging.bind(this), "pointer"); } } return tabElement; }, _tabClicked: function(event) { if (this._closeable && (event.button === 1 || event.target.hasStyleClass("tabbed-pane-header-tab-close-button"))) this._tabbedPane.closeTab(this.id, true); }, _tabMouseDown: function(event) { if (event.target.hasStyleClass("tabbed-pane-header-tab-close-button") || event.button === 1) return; this._tabbedPane.selectTab(this.id, true); }, _tabContextMenu: function(event) { function close() { this._tabbedPane.closeTab(this.id, true); } function closeOthers() { this._tabbedPane.closeOtherTabs(this.id); } function closeAll() { this._tabbedPane.closeAllTabs(true); } var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Close"), close.bind(this)); contextMenu.appendItem(WebInspector.UIString("Close Others"), closeOthers.bind(this)); contextMenu.appendItem(WebInspector.UIString("Close All"), closeAll.bind(this)); contextMenu.show(); }, _startTabDragging: function(event) { if (event.target.hasStyleClass("tabbed-pane-header-tab-close-button")) return false; this._dragStartX = event.pageX; return true; }, _tabDragging: function(event) { var tabElements = this._tabbedPane._tabsElement.childNodes; for (var i = 0; i < tabElements.length; ++i) { var tabElement = tabElements[i]; if (tabElement === this._tabElement) continue; var intersects = tabElement.offsetLeft + tabElement.clientWidth > this._tabElement.offsetLeft && this._tabElement.offsetLeft + this._tabElement.clientWidth > tabElement.offsetLeft; if (!intersects) continue; if (Math.abs(event.pageX - this._dragStartX) < tabElement.clientWidth / 2 + 5) break; if (event.pageX - this._dragStartX > 0) { tabElement = tabElement.nextSibling; ++i; } var oldOffsetLeft = this._tabElement.offsetLeft; this._tabbedPane._insertBefore(this, i); this._dragStartX += this._tabElement.offsetLeft - oldOffsetLeft; break; } if (!this._tabElement.previousSibling && event.pageX - this._dragStartX < 0) { this._tabElement.style.setProperty("left", "0px"); return; } if (!this._tabElement.nextSibling && event.pageX - this._dragStartX > 0) { this._tabElement.style.setProperty("left", "0px"); return; } this._tabElement.style.setProperty("position", "relative"); this._tabElement.style.setProperty("left", (event.pageX - this._dragStartX) + "px"); }, _endTabDragging: function(event) { this._tabElement.style.removeProperty("position"); this._tabElement.style.removeProperty("left"); delete this._dragStartX; } } WebInspector.Drawer = function() { this.element = document.getElementById("drawer"); this._savedHeight = 200; this._mainElement = document.getElementById("main"); this._toolbarElement = document.getElementById("toolbar"); this._floatingStatusBarContainer = document.getElementById("floating-status-bar-container"); WebInspector.installDragHandle(this._floatingStatusBarContainer, this._startStatusBarDragging.bind(this), this._statusBarDragging.bind(this), this._endStatusBarDragging.bind(this), "row-resize"); this._drawerContentsElement = document.createElement("div"); this._drawerContentsElement.id = "drawer-contents"; this._drawerContentsElement.className = "drawer-contents"; this.element.appendChild(this._drawerContentsElement); this._viewStatusBar = document.createElement("div"); this._bottomStatusBar = document.getElementById("bottom-status-bar-container"); } WebInspector.Drawer.AnimationType = { Immediately: 0, Normal: 1, Slow: 2 } WebInspector.Drawer.prototype = { get visible() { return !!this._view; }, _constrainHeight: function(height) { return Number.constrain(height, Preferences.minConsoleHeight, window.innerHeight - this._mainElement.totalOffsetTop() - Preferences.minConsoleHeight); }, show: function(view, animationType) { this.immediatelyFinishAnimation(); var drawerWasVisible = this.visible; if (this._view) { this._view.detach(); this._drawerContentsElement.removeChildren(); } this._view = view; var statusBarItems = this._view.statusBarItems || []; this._viewStatusBar.removeChildren(); for (var i = 0; i < statusBarItems.length; ++i) this._viewStatusBar.appendChild(statusBarItems[i]); document.body.addStyleClass("drawer-visible"); this._floatingStatusBarContainer.insertBefore(document.getElementById("panel-status-bar"), this._floatingStatusBarContainer.firstElementChild); this._bottomStatusBar.appendChild(this._viewStatusBar); this._view.markAsRoot(); this._view.show(this._drawerContentsElement); if (drawerWasVisible) return; var height = this._constrainHeight(this._savedHeight || this.element.offsetHeight); var animations = [ {element: this.element, end: {height: height}}, {element: this._mainElement, end: {bottom: height}}, {element: this._floatingStatusBarContainer, start: {"padding-left": this._bottomStatusBar.offsetLeft}, end: {"padding-left": 0}}, {element: this._viewStatusBar, start: {opacity: 0}, end: {opacity: 1}} ]; function animationFinished() { WebInspector.inspectorView.currentPanel().doResize(); if (this._view && this._view.afterShow) this._view.afterShow(); delete this._currentAnimation; } this._currentAnimation = WebInspector.animateStyle(animations, this._animationDuration(animationType), animationFinished.bind(this)); if (animationType === WebInspector.Drawer.AnimationType.Immediately) this._currentAnimation.forceComplete(); }, hide: function(animationType) { this.immediatelyFinishAnimation(); if (!this.visible) return; this._savedHeight = this.element.offsetHeight; WebInspector.restoreFocusFromElement(this.element); document.body.removeStyleClass("drawer-visible"); WebInspector.inspectorView.currentPanel().statusBarResized(); document.body.addStyleClass("drawer-visible"); var animations = [ {element: this._mainElement, end: {bottom: 0}}, {element: this.element, end: {height: 0}}, {element: this._floatingStatusBarContainer, start: {"padding-left": 0}, end: {"padding-left": this._bottomStatusBar.offsetLeft} }, {element: this._viewStatusBar, start: {opacity: 1}, end: {opacity: 0}} ]; function animationFinished() { WebInspector.inspectorView.currentPanel().doResize(); this._view.detach(); delete this._view; this._bottomStatusBar.removeChildren(); this._bottomStatusBar.appendChild(document.getElementById("panel-status-bar")); this._drawerContentsElement.removeChildren(); document.body.removeStyleClass("drawer-visible"); delete this._currentAnimation; } this._currentAnimation = WebInspector.animateStyle(animations, this._animationDuration(animationType), animationFinished.bind(this)); if (animationType === WebInspector.Drawer.AnimationType.Immediately) this._currentAnimation.forceComplete(); }, resize: function() { if (!this.visible) return; this._view.storeScrollPositions(); var height = this._constrainHeight(parseInt(this.element.style.height, 10)); this._mainElement.style.bottom = height + "px"; this.element.style.height = height + "px"; this._view.doResize(); }, immediatelyFinishAnimation: function() { if (this._currentAnimation) this._currentAnimation.forceComplete(); }, _animationDuration: function(animationType) { switch (animationType) { case WebInspector.Drawer.AnimationType.Slow: return 2000; case WebInspector.Drawer.AnimationType.Normal: return 250; default: return 0; } }, _startStatusBarDragging: function(event) { if (!this.visible || event.target !== this._floatingStatusBarContainer) return false; this._view.storeScrollPositions(); this._statusBarDragOffset = event.pageY - this.element.totalOffsetTop(); return true; }, _statusBarDragging: function(event) { var height = window.innerHeight - event.pageY + this._statusBarDragOffset; height = Number.constrain(height, Preferences.minConsoleHeight, window.innerHeight - this._mainElement.totalOffsetTop() - Preferences.minConsoleHeight); this._mainElement.style.bottom = height + "px"; this.element.style.height = height + "px"; if (WebInspector.inspectorView.currentPanel()) WebInspector.inspectorView.currentPanel().doResize(); this._view.doResize(); event.consume(true); }, _endStatusBarDragging: function(event) { this._savedHeight = this.element.offsetHeight; delete this._statusBarDragOffset; event.consume(); } } WebInspector.drawer = null; WebInspector.ConsoleModel = function() { this.messages = []; this.warnings = 0; this.errors = 0; this._interruptRepeatCount = false; InspectorBackend.registerConsoleDispatcher(new WebInspector.ConsoleDispatcher(this)); } WebInspector.ConsoleModel.Events = { ConsoleCleared: "console-cleared", MessageAdded: "console-message-added", RepeatCountUpdated: "repeat-count-updated" } WebInspector.ConsoleModel.prototype = { enableAgent: function() { if (WebInspector.settings.monitoringXHREnabled.get()) ConsoleAgent.setMonitoringXHREnabled(true); this._enablingConsole = true; function callback() { delete this._enablingConsole; } ConsoleAgent.enable(callback.bind(this)); }, enablingConsole: function() { return !!this._enablingConsole; }, addMessage: function(msg) { this.messages.push(msg); this._previousMessage = msg; this._incrementErrorWarningCount(msg); this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.MessageAdded, msg); this._interruptRepeatCount = false; }, _incrementErrorWarningCount: function(msg) { switch (msg.level) { case WebInspector.ConsoleMessage.MessageLevel.Warning: this.warnings += msg.repeatDelta; break; case WebInspector.ConsoleMessage.MessageLevel.Error: this.errors += msg.repeatDelta; break; } }, requestClearMessages: function() { ConsoleAgent.clearMessages(); this.clearMessages(); }, clearMessages: function() { this.messages = []; this.errors = 0; this.warnings = 0; this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.ConsoleCleared); }, interruptRepeatCount: function() { this._interruptRepeatCount = true; }, _messageRepeatCountUpdated: function(count) { var msg = this._previousMessage; if (!msg) return; var prevRepeatCount = msg.totalRepeatCount; if (!this._interruptRepeatCount) { msg.repeatDelta = count - prevRepeatCount; msg.repeatCount = msg.repeatCount + msg.repeatDelta; msg.totalRepeatCount = count; msg.updateRepeatCount(); this._incrementErrorWarningCount(msg); this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.RepeatCountUpdated, msg); } else { var msgCopy = msg.clone(); msgCopy.totalRepeatCount = count; msgCopy.repeatCount = (count - prevRepeatCount) || 1; msgCopy.repeatDelta = msgCopy.repeatCount; this.addMessage(msgCopy); } }, __proto__: WebInspector.Object.prototype } WebInspector.ConsoleMessage = function(source, level, url, line, repeatCount) { this.source = source; this.level = level; this.url = url || null; this.line = line || 0; this.message = ""; repeatCount = repeatCount || 1; this.repeatCount = repeatCount; this.repeatDelta = repeatCount; this.totalRepeatCount = repeatCount; } WebInspector.ConsoleMessage.prototype = { isErrorOrWarning: function() { return (this.level === WebInspector.ConsoleMessage.MessageLevel.Warning || this.level === WebInspector.ConsoleMessage.MessageLevel.Error); }, updateRepeatCount: function() { }, clone: function() { }, location: function() { } } WebInspector.ConsoleMessage.create = function(source, level, message, type, url, line, repeatCount, parameters, stackTrace, requestId, isOutdated) { } WebInspector.ConsoleMessage.MessageSource = { HTML: "html", XML: "xml", JS: "javascript", Network: "network", ConsoleAPI: "console-api", Other: "other" } WebInspector.ConsoleMessage.MessageType = { Log: "log", Dir: "dir", DirXML: "dirxml", Trace: "trace", Clear: "clear", StartGroup: "startGroup", StartGroupCollapsed: "startGroupCollapsed", EndGroup: "endGroup", Assert: "assert", Result: "result" } WebInspector.ConsoleMessage.MessageLevel = { Tip: "tip", Log: "log", Warning: "warning", Error: "error", Debug: "debug" } WebInspector.ConsoleDispatcher = function(console) { this._console = console; } WebInspector.ConsoleDispatcher.prototype = { messageAdded: function(payload) { var consoleMessage = WebInspector.ConsoleMessage.create( payload.source, payload.level, payload.text, payload.type, payload.url, payload.line, payload.repeatCount, payload.parameters, payload.stackTrace, payload.networkRequestId, this._console._enablingConsole); this._console.addMessage(consoleMessage); }, messageRepeatCountUpdated: function(count) { this._console._messageRepeatCountUpdated(count); }, messagesCleared: function() { if (!WebInspector.settings.preserveConsoleLog.get()) this._console.clearMessages(); } } WebInspector.console = null; WebInspector.ConsoleMessageImpl = function(source, level, message, linkifier, type, url, line, repeatCount, parameters, stackTrace, requestId, isOutdated) { WebInspector.ConsoleMessage.call(this, source, level, url, line, repeatCount); this._linkifier = linkifier; this.type = type || WebInspector.ConsoleMessage.MessageType.Log; this._messageText = message; this._parameters = parameters; this._stackTrace = stackTrace; this._request = requestId ? WebInspector.networkLog.requestForId(requestId) : null; this._isOutdated = isOutdated; this._customFormatters = { "object": this._formatParameterAsObject, "array": this._formatParameterAsArray, "node": this._formatParameterAsNode, "string": this._formatParameterAsString }; } WebInspector.ConsoleMessageImpl.prototype = { _formatMessage: function() { this._formattedMessage = document.createElement("span"); this._formattedMessage.className = "console-message-text source-code"; if (this.source === WebInspector.ConsoleMessage.MessageSource.ConsoleAPI) { switch (this.type) { case WebInspector.ConsoleMessage.MessageType.Trace: this._messageElement = document.createTextNode("console.trace()"); break; case WebInspector.ConsoleMessage.MessageType.Clear: this._messageElement = document.createTextNode(WebInspector.UIString("Console was cleared")); this._formattedMessage.addStyleClass("console-info"); break; case WebInspector.ConsoleMessage.MessageType.Assert: var args = [WebInspector.UIString("Assertion failed:")]; if (this._parameters) args = args.concat(this._parameters); this._messageElement = this._format(args); break; case WebInspector.ConsoleMessage.MessageType.Dir: var obj = this._parameters ? this._parameters[0] : undefined; var args = ["%O", obj]; this._messageElement = this._format(args); break; default: var args = this._parameters || [this._messageText]; this._messageElement = this._format(args); } } else if (this.source === WebInspector.ConsoleMessage.MessageSource.Network) { if (this._request) { this._stackTrace = this._request.initiator.stackTrace; if (this._request.initiator && this._request.initiator.url) { this.url = this._request.initiator.url; this.line = this._request.initiator.lineNumber; } this._messageElement = document.createElement("span"); if (this.level === WebInspector.ConsoleMessage.MessageLevel.Error) { this._messageElement.appendChild(document.createTextNode(this._request.requestMethod + " ")); this._messageElement.appendChild(WebInspector.linkifyRequestAsNode(this._request)); if (this._request.failed) this._messageElement.appendChild(document.createTextNode(" " + this._request.localizedFailDescription)); else this._messageElement.appendChild(document.createTextNode(" " + this._request.statusCode + " (" + this._request.statusText + ")")); } else { var fragment = WebInspector.linkifyStringAsFragmentWithCustomLinkifier(this._messageText, WebInspector.linkifyRequestAsNode.bind(null, this._request, "")); this._messageElement.appendChild(fragment); } } else { if (this.url) { var isExternal = !WebInspector.resourceForURL(this.url); this._anchorElement = WebInspector.linkifyURLAsNode(this.url, this.url, "console-message-url", isExternal); } this._messageElement = this._format([this._messageText]); } } else { var args = this._parameters || [this._messageText]; this._messageElement = this._format(args); } if (this.source !== WebInspector.ConsoleMessage.MessageSource.Network || this._request) { if (this._stackTrace && this._stackTrace.length && this._stackTrace[0].url) { this._anchorElement = this._linkifyCallFrame(this._stackTrace[0]); } else if (this.url && this.url !== "undefined") { this._anchorElement = this._linkifyLocation(this.url, this.line, 0); } } this._formattedMessage.appendChild(this._messageElement); if (this._anchorElement) { this._formattedMessage.appendChild(document.createTextNode(" ")); this._formattedMessage.appendChild(this._anchorElement); } var dumpStackTrace = !!this._stackTrace && this._stackTrace.length && (this.source === WebInspector.ConsoleMessage.MessageSource.Network || this.level === WebInspector.ConsoleMessage.MessageLevel.Error || this.type === WebInspector.ConsoleMessage.MessageType.Trace); if (dumpStackTrace) { var ol = document.createElement("ol"); ol.className = "outline-disclosure"; var treeOutline = new TreeOutline(ol); var content = this._formattedMessage; var root = new TreeElement(content, null, true); content.treeElementForTest = root; treeOutline.appendChild(root); if (this.type === WebInspector.ConsoleMessage.MessageType.Trace) root.expand(); this._populateStackTraceTreeElement(root); this._formattedMessage = ol; } this._message = this._messageElement.textContent; }, get message() { var formattedMessage = this.formattedMessage; return this._message; }, get formattedMessage() { if (!this._formattedMessage) this._formatMessage(); return this._formattedMessage; }, _linkifyLocation: function(url, lineNumber, columnNumber) { lineNumber = lineNumber ? lineNumber - 1 : 0; columnNumber = columnNumber ? columnNumber - 1 : 0; return this._linkifier.linkifyLocation(url, lineNumber, columnNumber, "console-message-url"); }, _linkifyCallFrame: function(callFrame) { return this._linkifyLocation(callFrame.url, callFrame.lineNumber, callFrame.columnNumber); }, isErrorOrWarning: function() { return (this.level === WebInspector.ConsoleMessage.MessageLevel.Warning || this.level === WebInspector.ConsoleMessage.MessageLevel.Error); }, _format: function(parameters) { var formattedResult = document.createElement("span"); if (!parameters.length) return formattedResult; for (var i = 0; i < parameters.length; ++i) { if (parameters[i] instanceof WebInspector.RemoteObject) continue; if (typeof parameters[i] === "object") parameters[i] = WebInspector.RemoteObject.fromPayload(parameters[i]); else parameters[i] = WebInspector.RemoteObject.fromPrimitiveValue(parameters[i]); } var shouldFormatMessage = WebInspector.RemoteObject.type(parameters[0]) === "string" && this.type !== WebInspector.ConsoleMessage.MessageType.Result; if (shouldFormatMessage) { var result = this._formatWithSubstitutionString(parameters, formattedResult); parameters = result.unusedSubstitutions; if (parameters.length) formattedResult.appendChild(document.createTextNode(" ")); } for (var i = 0; i < parameters.length; ++i) { if (shouldFormatMessage && parameters[i].type === "string") formattedResult.appendChild(document.createTextNode(parameters[i].description)); else formattedResult.appendChild(this._formatParameter(parameters[i], false, true)); if (i < parameters.length - 1) formattedResult.appendChild(document.createTextNode(" ")); } return formattedResult; }, _formatParameter: function(output, forceObjectFormat, includePreview) { var type; if (forceObjectFormat) type = "object"; else if (output instanceof WebInspector.RemoteObject) type = output.subtype || output.type; else type = typeof output; var formatter = this._customFormatters[type]; if (!formatter) { formatter = this._formatParameterAsValue; output = output.description; } var span = document.createElement("span"); span.className = "console-formatted-" + type + " source-code"; formatter.call(this, output, span, includePreview); return span; }, _formatParameterAsValue: function(val, elem) { elem.appendChild(document.createTextNode(val)); }, _formatParameterAsObject: function(obj, elem, includePreview) { this._formatParameterAsArrayOrObject(obj, obj.description, elem, includePreview); }, _formatParameterAsArrayOrObject: function(obj, description, elem, includePreview) { var titleElement = document.createElement("span"); if (description) titleElement.createTextChild(description); if (includePreview && obj.preview) { titleElement.addStyleClass("console-object-preview"); var lossless = this._appendObjectPreview(obj, description, titleElement); if (lossless) { elem.appendChild(titleElement); return; } } var section = new WebInspector.ObjectPropertiesSection(obj, titleElement); section.enableContextMenu(); elem.appendChild(section.element); }, _appendObjectPreview: function(obj, description, titleElement) { var preview = obj.preview; var isArray = obj.subtype === "array"; if (description) titleElement.createTextChild(" "); titleElement.createTextChild(isArray ? "[" : "{"); for (var i = 0; i < preview.properties.length; ++i) { if (i > 0) titleElement.createTextChild(", "); var property = preview.properties[i]; if (!isArray || property.name != i) { titleElement.createChild("span", "name").textContent = property.name; titleElement.createTextChild(": "); } this._appendPropertyPreview(titleElement, property); } if (preview.overflow) titleElement.createChild("span").textContent = "\u2026"; titleElement.createTextChild(isArray ? "]" : "}"); return preview.lossless; }, _appendPropertyPreview: function(titleElement, property) { var span = titleElement.createChild("span", "console-formatted-" + property.type); if (property.type === "function") { span.textContent = "function"; return; } if (property.type === "object" && property.subtype === "regexp") { span.addStyleClass("console-formatted-string"); span.textContent = property.value; return; } if (property.type === "object" && property.subtype === "node" && property.value) { span.addStyleClass("console-formatted-preview-node"); WebInspector.DOMPresentationUtils.createSpansForNodeTitle(span, property.value); return; } span.textContent = property.value; }, _formatParameterAsNode: function(object, elem) { function printNode(nodeId) { if (!nodeId) { this._formatParameterAsObject(object, elem, false); return; } var treeOutline = new WebInspector.ElementsTreeOutline(false, false, true); treeOutline.setVisible(true); treeOutline.rootDOMNode = WebInspector.domAgent.nodeForId(nodeId); treeOutline.element.addStyleClass("outline-disclosure"); if (!treeOutline.children[0].hasChildren) treeOutline.element.addStyleClass("single-node"); elem.appendChild(treeOutline.element); treeOutline.element.treeElementForTest = treeOutline.children[0]; } object.pushNodeToFrontend(printNode.bind(this)); }, useArrayPreviewInFormatter: function(array) { return this.type !== WebInspector.ConsoleMessage.MessageType.DirXML && !!array.preview; }, _formatParameterAsArray: function(array, elem) { if (this.useArrayPreviewInFormatter(array)) { this._formatParameterAsArrayOrObject(array, "", elem, true); return; } const maxFlatArrayLength = 100; if (this._isOutdated || array.arrayLength() > maxFlatArrayLength) this._formatParameterAsObject(array, elem, false); else array.getOwnProperties(this._printArray.bind(this, array, elem)); }, _formatParameterAsString: function(output, elem) { var span = document.createElement("span"); span.className = "console-formatted-string source-code"; span.appendChild(WebInspector.linkifyStringAsFragment(output.description)); elem.removeStyleClass("console-formatted-string"); elem.appendChild(document.createTextNode("\"")); elem.appendChild(span); elem.appendChild(document.createTextNode("\"")); }, _printArray: function(array, elem, properties) { if (!properties) return; var elements = []; for (var i = 0; i < properties.length; ++i) { var property = properties[i]; var name = property.name; if (!isNaN(name)) elements[name] = this._formatAsArrayEntry(property.value); } elem.appendChild(document.createTextNode("[")); var lastNonEmptyIndex = -1; function appendUndefined(elem, index) { if (index - lastNonEmptyIndex <= 1) return; var span = elem.createChild(span, "console-formatted-undefined"); span.textContent = WebInspector.UIString("undefined × %d", index - lastNonEmptyIndex - 1); } var length = array.arrayLength(); for (var i = 0; i < length; ++i) { var element = elements[i]; if (!element) continue; if (i - lastNonEmptyIndex > 1) { appendUndefined(elem, i); elem.appendChild(document.createTextNode(", ")); } elem.appendChild(element); lastNonEmptyIndex = i; if (i < length - 1) elem.appendChild(document.createTextNode(", ")); } appendUndefined(elem, length); elem.appendChild(document.createTextNode("]")); }, _formatAsArrayEntry: function(output) { return this._formatParameter(output, output.subtype && output.subtype === "array", false); }, _formatWithSubstitutionString: function(parameters, formattedResult) { var formatters = {} function parameterFormatter(force, obj) { return this._formatParameter(obj, force, false); } function stringFormatter(obj) { return obj.description; } function floatFormatter(obj) { if (typeof obj.value !== "number") return "NaN"; return obj.value; } function integerFormatter(obj) { if (typeof obj.value !== "number") return "NaN"; return Math.floor(obj.value); } var currentStyle = null; function styleFormatter(obj) { currentStyle = {}; var buffer = document.createElement("span"); buffer.setAttribute("style", obj.description); for (var i = 0; i < buffer.style.length; i++) { var property = buffer.style[i]; if (isWhitelistedProperty(property)) currentStyle[property] = buffer.style[property]; } } function isWhitelistedProperty(property) { var prefixes = ["background", "border", "color", "font", "line", "margin", "padding", "text", "-webkit-background", "-webkit-border", "-webkit-font", "-webkit-margin", "-webkit-padding", "-webkit-text"]; for (var i = 0; i < prefixes.length; i++) { if (property.startsWith(prefixes[i])) return true; } return false; } formatters.o = parameterFormatter.bind(this, false); formatters.s = stringFormatter; formatters.f = floatFormatter; formatters.i = integerFormatter; formatters.d = integerFormatter; formatters.c = styleFormatter; formatters.O = parameterFormatter.bind(this, true); function append(a, b) { if (b instanceof Node) a.appendChild(b); else if (b) { var toAppend = WebInspector.linkifyStringAsFragment(b.toString()); if (currentStyle) { var wrapper = document.createElement('span'); for (var key in currentStyle) wrapper.style[key] = currentStyle[key]; wrapper.appendChild(toAppend); toAppend = wrapper; } a.appendChild(toAppend); } return a; } return String.format(parameters[0].description, parameters.slice(1), formatters, formattedResult, append); }, clearHighlight: function() { if (!this._formattedMessage) return; var highlightedMessage = this._formattedMessage; delete this._formattedMessage; delete this._anchorElement; delete this._messageElement; this._formatMessage(); this._element.replaceChild(this._formattedMessage, highlightedMessage); }, highlightSearchResults: function(regexObject) { if (!this._formattedMessage) return; this._highlightSearchResultsInElement(regexObject, this._messageElement); if (this._anchorElement) this._highlightSearchResultsInElement(regexObject, this._anchorElement); this._element.scrollIntoViewIfNeeded(); }, _highlightSearchResultsInElement: function(regexObject, element) { regexObject.lastIndex = 0; var text = element.textContent; var match = regexObject.exec(text); var offset = 0; var matchRanges = []; while (match) { matchRanges.push({ offset: match.index, length: match[0].length }); match = regexObject.exec(text); } WebInspector.highlightSearchResults(element, matchRanges); }, matchesRegex: function(regexObject) { return regexObject.test(this._message) || (this._anchorElement && regexObject.test(this._anchorElement.textContent)); }, toMessageElement: function() { if (this._element) return this._element; var element = document.createElement("div"); element.message = this; element.className = "console-message"; this._element = element; switch (this.level) { case WebInspector.ConsoleMessage.MessageLevel.Tip: element.addStyleClass("console-tip-level"); break; case WebInspector.ConsoleMessage.MessageLevel.Log: element.addStyleClass("console-log-level"); break; case WebInspector.ConsoleMessage.MessageLevel.Debug: element.addStyleClass("console-debug-level"); break; case WebInspector.ConsoleMessage.MessageLevel.Warning: element.addStyleClass("console-warning-level"); break; case WebInspector.ConsoleMessage.MessageLevel.Error: element.addStyleClass("console-error-level"); break; } if (this.type === WebInspector.ConsoleMessage.MessageType.StartGroup || this.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) element.addStyleClass("console-group-title"); element.appendChild(this.formattedMessage); if (this.repeatCount > 1) this.updateRepeatCount(); return element; }, _populateStackTraceTreeElement: function(parentTreeElement) { for (var i = 0; i < this._stackTrace.length; i++) { var frame = this._stackTrace[i]; var content = document.createElement("div"); var messageTextElement = document.createElement("span"); messageTextElement.className = "console-message-text source-code"; var functionName = frame.functionName || WebInspector.UIString("(anonymous function)"); messageTextElement.appendChild(document.createTextNode(functionName)); content.appendChild(messageTextElement); if (frame.url) { content.appendChild(document.createTextNode(" ")); var urlElement = this._linkifyCallFrame(frame); content.appendChild(urlElement); } var treeElement = new TreeElement(content); parentTreeElement.appendChild(treeElement); } }, updateRepeatCount: function() { if (!this.repeatCountElement) { this.repeatCountElement = document.createElement("span"); this.repeatCountElement.className = "bubble"; this._element.insertBefore(this.repeatCountElement, this._element.firstChild); this._element.addStyleClass("repeated-message"); } this.repeatCountElement.textContent = this.repeatCount; }, toString: function() { var sourceString; switch (this.source) { case WebInspector.ConsoleMessage.MessageSource.HTML: sourceString = "HTML"; break; case WebInspector.ConsoleMessage.MessageSource.XML: sourceString = "XML"; break; case WebInspector.ConsoleMessage.MessageSource.JS: sourceString = "JS"; break; case WebInspector.ConsoleMessage.MessageSource.Network: sourceString = "Network"; break; case WebInspector.ConsoleMessage.MessageSource.ConsoleAPI: sourceString = "ConsoleAPI"; break; case WebInspector.ConsoleMessage.MessageSource.Other: sourceString = "Other"; break; } var typeString; switch (this.type) { case WebInspector.ConsoleMessage.MessageType.Log: typeString = "Log"; break; case WebInspector.ConsoleMessage.MessageType.Dir: typeString = "Dir"; break; case WebInspector.ConsoleMessage.MessageType.DirXML: typeString = "Dir XML"; break; case WebInspector.ConsoleMessage.MessageType.Trace: typeString = "Trace"; break; case WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed: case WebInspector.ConsoleMessage.MessageType.StartGroup: typeString = "Start Group"; break; case WebInspector.ConsoleMessage.MessageType.EndGroup: typeString = "End Group"; break; case WebInspector.ConsoleMessage.MessageType.Assert: typeString = "Assert"; break; case WebInspector.ConsoleMessage.MessageType.Result: typeString = "Result"; break; } var levelString; switch (this.level) { case WebInspector.ConsoleMessage.MessageLevel.Tip: levelString = "Tip"; break; case WebInspector.ConsoleMessage.MessageLevel.Log: levelString = "Log"; break; case WebInspector.ConsoleMessage.MessageLevel.Warning: levelString = "Warning"; break; case WebInspector.ConsoleMessage.MessageLevel.Debug: levelString = "Debug"; break; case WebInspector.ConsoleMessage.MessageLevel.Error: levelString = "Error"; break; } return sourceString + " " + typeString + " " + levelString + ": " + this.formattedMessage.textContent + "\n" + this.url + " line " + this.line; }, get text() { return this._messageText; }, location: function() { var lineNumber = this.stackTrace ? this.stackTrace[0].lineNumber - 1 : this.line - 1; var columnNumber = this.stackTrace && this.stackTrace[0].columnNumber ? this.stackTrace[0].columnNumber - 1 : 0; return WebInspector.debuggerModel.createRawLocationByURL(this.url, lineNumber, columnNumber); }, isEqual: function(msg) { if (!msg) return false; if (this._stackTrace) { if (!msg._stackTrace) return false; var l = this._stackTrace; var r = msg._stackTrace; if (l.length !== r.length) return false; for (var i = 0; i < l.length; i++) { if (l[i].url !== r[i].url || l[i].functionName !== r[i].functionName || l[i].lineNumber !== r[i].lineNumber || l[i].columnNumber !== r[i].columnNumber) return false; } } return (this.source === msg.source) && (this.type === msg.type) && (this.level === msg.level) && (this.line === msg.line) && (this.url === msg.url) && (this.message === msg.message) && (this._request === msg._request); }, get stackTrace() { return this._stackTrace; }, clone: function() { return WebInspector.ConsoleMessage.create(this.source, this.level, this._messageText, this.type, this.url, this.line, this.repeatCount, this._parameters, this._stackTrace, this._request ? this._request.requestId : undefined, this._isOutdated); }, __proto__: WebInspector.ConsoleMessage.prototype } WebInspector.ConsoleView = function(hideContextSelector) { WebInspector.View.call(this); this.element.id = "console-view"; this.messages = []; this._clearConsoleButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear console log."), "clear-status-bar-item"); this._clearConsoleButton.addEventListener("click", this._requestClearMessages, this); this._frameSelector = new WebInspector.StatusBarComboBox(this._frameChanged.bind(this), "console-context"); this._contextSelector = new WebInspector.StatusBarComboBox(this._contextChanged.bind(this), "console-context"); if (hideContextSelector) { this._frameSelector.element.addStyleClass("hidden"); this._contextSelector.element.addStyleClass("hidden"); } this.messagesElement = document.createElement("div"); this.messagesElement.id = "console-messages"; this.messagesElement.className = "monospace"; this.messagesElement.addEventListener("click", this._messagesClicked.bind(this), true); this.element.appendChild(this.messagesElement); this._scrolledToBottom = true; this.promptElement = document.createElement("div"); this.promptElement.id = "console-prompt"; this.promptElement.className = "source-code"; this.promptElement.spellcheck = false; this.messagesElement.appendChild(this.promptElement); this.messagesElement.appendChild(document.createElement("br")); this.topGroup = new WebInspector.ConsoleGroup(null); this.messagesElement.insertBefore(this.topGroup.element, this.promptElement); this.currentGroup = this.topGroup; this._filterBarElement = document.createElement("div"); this._filterBarElement.className = "scope-bar status-bar-item"; function createDividerElement() { var dividerElement = document.createElement("div"); dividerElement.addStyleClass("scope-bar-divider"); this._filterBarElement.appendChild(dividerElement); } var updateFilterHandler = this._updateFilter.bind(this); function createFilterElement(category, label) { var categoryElement = document.createElement("li"); categoryElement.category = category; categoryElement.className = category; categoryElement.addEventListener("click", updateFilterHandler, false); categoryElement.textContent = label; this._filterBarElement.appendChild(categoryElement); return categoryElement; } this.allElement = createFilterElement.call(this, "all", WebInspector.UIString("All")); createDividerElement.call(this); this.errorElement = createFilterElement.call(this, "errors", WebInspector.UIString("Errors")); this.warningElement = createFilterElement.call(this, "warnings", WebInspector.UIString("Warnings")); this.logElement = createFilterElement.call(this, "logs", WebInspector.UIString("Logs")); this.debugElement = createFilterElement.call(this, "debug", WebInspector.UIString("Debug")); this.filter(this.allElement, false); this._registerShortcuts(); this.registerRequiredCSS("textPrompt.css"); this.messagesElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), false); WebInspector.settings.monitoringXHREnabled.addChangeListener(this._monitoringXHREnabledSettingChanged.bind(this)); WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._consoleMessageAdded, this); WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); this._linkifier = new WebInspector.Linkifier(); this.prompt = new WebInspector.TextPromptWithHistory(WebInspector.runtimeModel.completionsForTextPrompt.bind(WebInspector.runtimeModel)); this.prompt.setSuggestBoxEnabled("generic-suggest"); this.prompt.renderAsBlock(); this.prompt.attach(this.promptElement); this.prompt.proxyElement.addEventListener("keydown", this._promptKeyDown.bind(this), false); this.prompt.setHistoryData(WebInspector.settings.consoleHistory.get()); WebInspector.runtimeModel.contextLists().forEach(this._addFrame, this); WebInspector.runtimeModel.addEventListener(WebInspector.RuntimeModel.Events.FrameExecutionContextListAdded, this._frameAdded, this); WebInspector.runtimeModel.addEventListener(WebInspector.RuntimeModel.Events.FrameExecutionContextListRemoved, this._frameRemoved, this); } WebInspector.ConsoleView.Events = { ConsoleCleared: "console-cleared", EntryAdded: "console-entry-added", } WebInspector.ConsoleView.prototype = { get statusBarItems() { return [this._clearConsoleButton.element, this._frameSelector.element, this._contextSelector.element, this._filterBarElement]; }, _frameAdded: function(event) { var contextList = (event.data); this._addFrame(contextList); }, _addFrame: function(contextList) { var option = document.createElement("option"); option.text = contextList.displayName; option.title = contextList.url; option._contextList = contextList; contextList._consoleOption = option; this._frameSelector.addOption(option); contextList.addEventListener(WebInspector.FrameExecutionContextList.EventTypes.ContextsUpdated, this._frameUpdated, this); contextList.addEventListener(WebInspector.FrameExecutionContextList.EventTypes.ContextAdded, this._contextAdded, this); this._frameChanged(); }, _frameRemoved: function(event) { var contextList = (event.data); this._frameSelector.removeOption(contextList._consoleOption); this._frameChanged(); }, _frameChanged: function() { var context = this._currentFrame(); if (!context) { WebInspector.runtimeModel.setCurrentExecutionContext(null); this._contextSelector.element.addStyleClass("hidden"); return; } var executionContexts = context.executionContexts(); if (executionContexts.length) WebInspector.runtimeModel.setCurrentExecutionContext(executionContexts[0]); if (executionContexts.length === 1) { this._contextSelector.element.addStyleClass("hidden"); return; } this._contextSelector.element.removeStyleClass("hidden"); this._contextSelector.removeOptions(); for (var i = 0; i < executionContexts.length; i++) this._appendContextOption(executionContexts[i]); }, _appendContextOption: function(executionContext) { if (!WebInspector.runtimeModel.currentExecutionContext()) WebInspector.runtimeModel.setCurrentExecutionContext(executionContext); var option = document.createElement("option"); option.text = executionContext.name; option.title = executionContext.id; option._executionContext = executionContext; this._contextSelector.addOption(option); }, _contextChanged: function(event) { var option = this._contextSelector.selectedOption(); WebInspector.runtimeModel.setCurrentExecutionContext(option ? option._executionContext : null); }, _frameUpdated: function(event) { var contextList = event.data; var option = contextList._consoleOption; option.text = contextList.displayName; option.title = contextList.url; }, _contextAdded: function(event) { var contextList = event.data; if (contextList === this._currentFrame()) this._frameChanged(); }, _currentFrame: function() { var option = this._frameSelector.selectedOption(); return option ? option._contextList : undefined; }, _updateFilter: function(e) { var isMac = WebInspector.isMac(); var selectMultiple = false; if (isMac && e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey) selectMultiple = true; if (!isMac && e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey) selectMultiple = true; this.filter(e.target, selectMultiple); }, filter: function(target, selectMultiple) { function unselectAll() { this.allElement.removeStyleClass("selected"); this.errorElement.removeStyleClass("selected"); this.warningElement.removeStyleClass("selected"); this.logElement.removeStyleClass("selected"); this.debugElement.removeStyleClass("selected"); this.messagesElement.classList.remove("filter-all", "filter-errors", "filter-warnings", "filter-logs", "filter-debug"); } var targetFilterClass = "filter-" + target.category; if (target.category === "all") { if (target.hasStyleClass("selected")) { return; } unselectAll.call(this); } else { if (this.allElement.hasStyleClass("selected")) { this.allElement.removeStyleClass("selected"); this.messagesElement.removeStyleClass("filter-all"); } } if (!selectMultiple) { unselectAll.call(this); target.addStyleClass("selected"); this.messagesElement.addStyleClass(targetFilterClass); return; } if (target.hasStyleClass("selected")) { target.removeStyleClass("selected"); this.messagesElement.removeStyleClass(targetFilterClass); } else { target.addStyleClass("selected"); this.messagesElement.addStyleClass(targetFilterClass); } }, willHide: function() { this.prompt.hideSuggestBox(); this.prompt.clearAutoComplete(true); }, wasShown: function() { if (!this.prompt.isCaretInsidePrompt()) this.prompt.moveCaretToEndOfPrompt(); }, afterShow: function() { WebInspector.setCurrentFocusElement(this.promptElement); }, storeScrollPositions: function() { WebInspector.View.prototype.storeScrollPositions.call(this); this._scrolledToBottom = this.messagesElement.isScrolledToBottom(); }, restoreScrollPositions: function() { if (this._scrolledToBottom) this._immediatelyScrollIntoView(); else WebInspector.View.prototype.restoreScrollPositions.call(this); }, onResize: function() { this.restoreScrollPositions(); }, _isScrollIntoViewScheduled: function() { return !!this._scrollIntoViewTimer; }, _scheduleScrollIntoView: function() { if (this._scrollIntoViewTimer) return; function scrollIntoView() { delete this._scrollIntoViewTimer; this.promptElement.scrollIntoView(true); } this._scrollIntoViewTimer = setTimeout(scrollIntoView.bind(this), 20); }, _immediatelyScrollIntoView: function() { this.promptElement.scrollIntoView(true); this._cancelScheduledScrollIntoView(); }, _cancelScheduledScrollIntoView: function() { if (!this._isScrollIntoViewScheduled()) return; clearTimeout(this._scrollIntoViewTimer); delete this._scrollIntoViewTimer; }, _consoleMessageAdded: function(event) { this._appendConsoleMessage(event.data); }, _appendConsoleMessage: function(msg) { if (!this._isScrollIntoViewScheduled() && ((msg instanceof WebInspector.ConsoleCommandResult) || this.messagesElement.isScrolledToBottom())) this._scheduleScrollIntoView(); this.messages.push(msg); if (msg.type === WebInspector.ConsoleMessage.MessageType.EndGroup) { var parentGroup = this.currentGroup.parentGroup if (parentGroup) this.currentGroup = parentGroup; } else { if (msg.type === WebInspector.ConsoleMessage.MessageType.StartGroup || msg.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) { var group = new WebInspector.ConsoleGroup(this.currentGroup); this.currentGroup.messagesElement.appendChild(group.element); this.currentGroup = group; } this.currentGroup.addMessage(msg); } this.dispatchEventToListeners(WebInspector.ConsoleView.Events.EntryAdded, msg); }, _consoleCleared: function() { this._scrolledToBottom = true; this.messages = []; this.currentGroup = this.topGroup; this.topGroup.messagesElement.removeChildren(); this.dispatchEventToListeners(WebInspector.ConsoleView.Events.ConsoleCleared); this._linkifier.reset(); }, _handleContextMenuEvent: function(event) { if (!window.getSelection().isCollapsed) { return; } if (event.target.enclosingNodeOrSelfWithNodeName("a")) return; var contextMenu = new WebInspector.ContextMenu(event); function monitoringXHRItemAction() { WebInspector.settings.monitoringXHREnabled.set(!WebInspector.settings.monitoringXHREnabled.get()); } contextMenu.appendCheckboxItem(WebInspector.UIString("Log XMLHttpRequests"), monitoringXHRItemAction.bind(this), WebInspector.settings.monitoringXHREnabled.get()); function preserveLogItemAction() { WebInspector.settings.preserveConsoleLog.set(!WebInspector.settings.preserveConsoleLog.get()); } contextMenu.appendCheckboxItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Preserve log upon navigation" : "Preserve Log upon Navigation"), preserveLogItemAction.bind(this), WebInspector.settings.preserveConsoleLog.get()); contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear console" : "Clear Console"), this._requestClearMessages.bind(this)); contextMenu.show(); }, _monitoringXHREnabledSettingChanged: function(event) { ConsoleAgent.setMonitoringXHREnabled(event.data); }, _messagesClicked: function(event) { if (!this.prompt.isCaretInsidePrompt() && window.getSelection().isCollapsed) this.prompt.moveCaretToEndOfPrompt(); }, _registerShortcuts: function() { this._shortcuts = {}; var shortcut = WebInspector.KeyboardShortcut; var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Console")); var shortcutL = shortcut.makeDescriptor("l", WebInspector.KeyboardShortcut.Modifiers.Ctrl); this._shortcuts[shortcutL.key] = this._requestClearMessages.bind(this); var keys = [shortcutL]; if (WebInspector.isMac()) { var shortcutK = shortcut.makeDescriptor("k", WebInspector.KeyboardShortcut.Modifiers.Meta); this._shortcuts[shortcutK.key] = this._requestClearMessages.bind(this); keys.unshift(shortcutK); } section.addAlternateKeys(keys, WebInspector.UIString("Clear console")); section.addKey(shortcut.makeDescriptor(shortcut.Keys.Tab), WebInspector.UIString("Autocomplete common prefix")); section.addKey(shortcut.makeDescriptor(shortcut.Keys.Right), WebInspector.UIString("Accept suggestion")); keys = [ shortcut.makeDescriptor(shortcut.Keys.Down), shortcut.makeDescriptor(shortcut.Keys.Up) ]; section.addRelatedKeys(keys, WebInspector.UIString("Next/previous line")); if (WebInspector.isMac()) { keys = [ shortcut.makeDescriptor("N", shortcut.Modifiers.Alt), shortcut.makeDescriptor("P", shortcut.Modifiers.Alt) ]; section.addRelatedKeys(keys, WebInspector.UIString("Next/previous command")); } section.addKey(shortcut.makeDescriptor(shortcut.Keys.Enter), WebInspector.UIString("Execute command")); }, _requestClearMessages: function() { WebInspector.console.requestClearMessages(); }, _promptKeyDown: function(event) { if (isEnterKey(event)) { this._enterKeyPressed(event); return; } var shortcut = WebInspector.KeyboardShortcut.makeKeyFromEvent(event); var handler = this._shortcuts[shortcut]; if (handler) { handler(); event.preventDefault(); return; } }, evaluateUsingTextPrompt: function(expression, showResultOnly) { this._appendCommand(expression, this.prompt.text, false, showResultOnly); }, _enterKeyPressed: function(event) { if (event.altKey || event.ctrlKey || event.shiftKey) return; event.consume(true); this.prompt.clearAutoComplete(true); var str = this.prompt.text; if (!str.length) return; this._appendCommand(str, "", true, false); }, _printResult: function(result, wasThrown, originatingCommand) { if (!result) return; this._appendConsoleMessage(new WebInspector.ConsoleCommandResult(result, wasThrown, originatingCommand, this._linkifier)); }, _appendCommand: function(text, newPromptText, useCommandLineAPI, showResultOnly) { if (!showResultOnly) { var commandMessage = new WebInspector.ConsoleCommand(text); WebInspector.console.interruptRepeatCount(); this._appendConsoleMessage(commandMessage); } this.prompt.text = newPromptText; function printResult(result, wasThrown) { if (!result) return; if (!showResultOnly) { this.prompt.pushHistoryItem(text); WebInspector.settings.consoleHistory.set(this.prompt.historyData.slice(-30)); } this._printResult(result, wasThrown, commandMessage); } WebInspector.runtimeModel.evaluate(text, "console", useCommandLineAPI, false, false, true, printResult.bind(this)); WebInspector.userMetrics.ConsoleEvaluated.record(); }, elementsToRestoreScrollPositionsFor: function() { return [this.messagesElement]; }, __proto__: WebInspector.View.prototype } WebInspector.ConsoleCommand = function(command) { this.command = command; } WebInspector.ConsoleCommand.prototype = { clearHighlight: function() { var highlightedMessage = this._formattedCommand; delete this._formattedCommand; this._formatCommand(); this._element.replaceChild(this._formattedCommand, highlightedMessage); }, highlightSearchResults: function(regexObject) { regexObject.lastIndex = 0; var text = this.command; var match = regexObject.exec(text); var offset = 0; var matchRanges = []; while (match) { matchRanges.push({ offset: match.index, length: match[0].length }); match = regexObject.exec(text); } WebInspector.highlightSearchResults(this._formattedCommand, matchRanges); this._element.scrollIntoViewIfNeeded(); }, matchesRegex: function(regexObject) { return regexObject.test(this.command); }, toMessageElement: function() { if (!this._element) { this._element = document.createElement("div"); this._element.command = this; this._element.className = "console-user-command"; this._formatCommand(); this._element.appendChild(this._formattedCommand); } return this._element; }, _formatCommand: function() { this._formattedCommand = document.createElement("span"); this._formattedCommand.className = "console-message-text source-code"; this._formattedCommand.textContent = this.command; }, } WebInspector.ConsoleCommandResult = function(result, wasThrown, originatingCommand, linkifier) { var level = (wasThrown ? WebInspector.ConsoleMessage.MessageLevel.Error : WebInspector.ConsoleMessage.MessageLevel.Log); this.originatingCommand = originatingCommand; WebInspector.ConsoleMessageImpl.call(this, WebInspector.ConsoleMessage.MessageSource.JS, level, "", linkifier, WebInspector.ConsoleMessage.MessageType.Result, undefined, undefined, undefined, [result]); } WebInspector.ConsoleCommandResult.prototype = { useArrayPreviewInFormatter: function(array) { return false; }, toMessageElement: function() { var element = WebInspector.ConsoleMessageImpl.prototype.toMessageElement.call(this); element.addStyleClass("console-user-command-result"); return element; }, __proto__: WebInspector.ConsoleMessageImpl.prototype } WebInspector.ConsoleGroup = function(parentGroup) { this.parentGroup = parentGroup; var element = document.createElement("div"); element.className = "console-group"; element.group = this; this.element = element; if (parentGroup) { var bracketElement = document.createElement("div"); bracketElement.className = "console-group-bracket"; element.appendChild(bracketElement); } var messagesElement = document.createElement("div"); messagesElement.className = "console-group-messages"; element.appendChild(messagesElement); this.messagesElement = messagesElement; } WebInspector.ConsoleGroup.prototype = { addMessage: function(msg) { var element = msg.toMessageElement(); if (msg.type === WebInspector.ConsoleMessage.MessageType.StartGroup || msg.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) { this.messagesElement.parentNode.insertBefore(element, this.messagesElement); element.addEventListener("click", this._titleClicked.bind(this), false); var groupElement = element.enclosingNodeOrSelfWithClass("console-group"); if (groupElement && msg.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed) groupElement.addStyleClass("collapsed"); } else this.messagesElement.appendChild(element); if (element.previousSibling && msg.originatingCommand && element.previousSibling.command === msg.originatingCommand) element.previousSibling.addStyleClass("console-adjacent-user-command-result"); }, _titleClicked: function(event) { var groupTitleElement = event.target.enclosingNodeOrSelfWithClass("console-group-title"); if (groupTitleElement) { var groupElement = groupTitleElement.enclosingNodeOrSelfWithClass("console-group"); if (groupElement) if (groupElement.hasStyleClass("collapsed")) groupElement.removeStyleClass("collapsed"); else groupElement.addStyleClass("collapsed"); groupTitleElement.scrollIntoViewIfNeeded(true); } event.consume(true); } } WebInspector.consoleView = null; WebInspector.ConsoleMessage.create = function(source, level, message, type, url, line, repeatCount, parameters, stackTrace, requestId, isOutdated) { return new WebInspector.ConsoleMessageImpl(source, level, message, WebInspector.consoleView._linkifier, type, url, line, repeatCount, parameters, stackTrace, requestId, isOutdated); } WebInspector.Panel = function(name) { WebInspector.View.call(this); WebInspector.panels[name] = this; this.element.addStyleClass("panel"); this.element.addStyleClass(name); this._panelName = name; this._shortcuts = {}; WebInspector.settings[this._sidebarWidthSettingName()] = WebInspector.settings.createSetting(this._sidebarWidthSettingName(), undefined); } WebInspector.Panel.counterRightMargin = 25; WebInspector.Panel.prototype = { get name() { return this._panelName; }, show: function() { WebInspector.View.prototype.show.call(this, WebInspector.inspectorView.panelsElement()); }, wasShown: function() { var statusBarItems = this.statusBarItems; if (statusBarItems) { this._statusBarItemContainer = document.createElement("div"); for (var i = 0; i < statusBarItems.length; ++i) this._statusBarItemContainer.appendChild(statusBarItems[i]); document.getElementById("panel-status-bar").appendChild(this._statusBarItemContainer); } this.focus(); }, willHide: function() { if (this._statusBarItemContainer && this._statusBarItemContainer.parentNode) this._statusBarItemContainer.parentNode.removeChild(this._statusBarItemContainer); delete this._statusBarItemContainer; }, reset: function() { this.searchCanceled(); }, defaultFocusedElement: function() { return this.sidebarTreeElement || this.element; }, searchCanceled: function() { WebInspector.searchController.updateSearchMatchesCount(0, this); }, performSearch: function(query) { this.searchCanceled(); }, jumpToNextSearchResult: function() { }, jumpToPreviousSearchResult: function() { }, canSearchAndReplace: function() { return false; }, replaceSelectionWith: function(text) { }, replaceAllWith: function(query, text) { }, canFilter: function() { return false; }, performFilter: function(query) { }, createSidebarView: function(parentElement, position, defaultWidth) { if (this.splitView) return; if (!parentElement) parentElement = this.element; this.splitView = new WebInspector.SidebarView(position || WebInspector.SidebarView.SidebarPosition.Left, this._sidebarWidthSettingName(), defaultWidth); this.splitView.show(parentElement); this.splitView.addEventListener(WebInspector.SidebarView.EventTypes.Resized, this.sidebarResized.bind(this)); this.sidebarElement = this.splitView.sidebarElement; }, createSidebarViewWithTree: function(parentElement, position, defaultWidth) { if (this.splitView) return; this.createSidebarView(parentElement, position); this.sidebarTreeElement = document.createElement("ol"); this.sidebarTreeElement.className = "sidebar-tree"; this.splitView.sidebarElement.appendChild(this.sidebarTreeElement); this.splitView.sidebarElement.addStyleClass("sidebar"); this.sidebarTree = new TreeOutline(this.sidebarTreeElement); this.sidebarTree.panel = this; }, _sidebarWidthSettingName: function() { return this._panelName + "SidebarWidth"; }, get statusBarItems() { }, sidebarResized: function(event) { }, statusBarResized: function() { }, canShowAnchorLocation: function(anchor) { return false; }, showAnchorLocation: function(anchor) { }, elementsToRestoreScrollPositionsFor: function() { return []; }, handleShortcut: function(event) { var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent(event); var handler = this._shortcuts[shortcutKey]; if (handler) { handler(event); event.handled = true; } }, registerShortcuts: function(keys, handler) { for (var i = 0; i < keys.length; ++i) this._shortcuts[keys[i].key] = handler; }, __proto__: WebInspector.View.prototype } WebInspector.PanelDescriptor = function(name, title, className, scriptName, panel) { this._name = name; this._title = title; this._className = className; this._scriptName = scriptName; this._panel = panel; } WebInspector.PanelDescriptor.prototype = { name: function() { return this._name; }, title: function() { return this._title; }, iconURL: function() { return this._iconURL; }, setIconURL: function(iconURL) { this._iconURL = iconURL; }, panel: function() { if (this._panel) return this._panel; if (this._scriptName) importScript(this._scriptName); this._panel = new WebInspector[this._className]; return this._panel; }, registerShortcuts: function() {} } WebInspector.InspectorView = function() { WebInspector.View.call(this); this.markAsRoot(); this.element.id = "main-panels"; this.element.setAttribute("spellcheck", false); this._history = []; this._historyIterator = -1; document.addEventListener("keydown", this._keyDown.bind(this), false); document.addEventListener("keypress", this._keyPress.bind(this), false); this._panelOrder = []; this._panelDescriptors = {}; this._openBracketIdentifiers = ["U+005B", "U+00DB"].keySet(); this._closeBracketIdentifiers = ["U+005D", "U+00DD"].keySet(); this._footerElementContainer = this.element.createChild("div", "inspector-footer status-bar hidden"); this._panelsElement = this.element.createChild("div", "fill"); } WebInspector.InspectorView.Events = { PanelSelected: "PanelSelected" } WebInspector.InspectorView.prototype = { addPanel: function(panelDescriptor) { this._panelOrder.push(panelDescriptor.name()); this._panelDescriptors[panelDescriptor.name()] = panelDescriptor; WebInspector.toolbar.addPanel(panelDescriptor); }, panel: function(panelName) { var panelDescriptor = this._panelDescriptors[panelName]; if (!panelDescriptor && this._panelOrder.length) panelDescriptor = this._panelDescriptors[this._panelOrder[0]]; return panelDescriptor ? panelDescriptor.panel() : null; }, showPanel: function(panelName) { var panel = this.panel(panelName); if (panel) this.setCurrentPanel(panel); return panel; }, currentPanel: function() { return this._currentPanel; }, setCurrentPanel: function(x) { if (this._currentPanel === x) return; if (this._currentPanel) this._currentPanel.detach(); this._currentPanel = x; if (x) { x.show(); this.dispatchEventToListeners(WebInspector.InspectorView.Events.PanelSelected); WebInspector.searchController.cancelSearch(); } for (var panelName in WebInspector.panels) { if (WebInspector.panels[panelName] === x) { WebInspector.settings.lastActivePanel.set(panelName); this._pushToHistory(panelName); WebInspector.userMetrics.panelShown(panelName); } } }, _keyPress: function(event) { if (event.charCode < 32 && WebInspector.isWin()) return; clearTimeout(this._keyDownTimer); delete this._keyDownTimer; }, _keyDown: function(event) { if (!WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)) return; if (!event.shiftKey && !event.altKey && event.keyCode > 0x30 && event.keyCode < 0x3A) { var panelName = this._panelOrder[event.keyCode - 0x31]; if (panelName) { this.showPanel(panelName); event.consume(true); } return; } if (!WebInspector.isWin() || (!this._openBracketIdentifiers[event.keyIdentifier] && !this._closeBracketIdentifiers[event.keyIdentifier])) { this._keyDownInternal(event); return; } this._keyDownTimer = setTimeout(this._keyDownInternal.bind(this, event), 0); }, _keyDownInternal: function(event) { if (this._openBracketIdentifiers[event.keyIdentifier]) { var isRotateLeft = !event.shiftKey && !event.altKey; if (isRotateLeft) { var index = this._panelOrder.indexOf(this.currentPanel().name); index = (index === 0) ? this._panelOrder.length - 1 : index - 1; this.showPanel(this._panelOrder[index]); event.consume(true); return; } var isGoBack = event.altKey; if (isGoBack && this._canGoBackInHistory()) { this._goBackInHistory(); event.consume(true); } return; } if (this._closeBracketIdentifiers[event.keyIdentifier]) { var isRotateRight = !event.shiftKey && !event.altKey; if (isRotateRight) { var index = this._panelOrder.indexOf(this.currentPanel().name); index = (index + 1) % this._panelOrder.length; this.showPanel(this._panelOrder[index]); event.consume(true); return; } var isGoForward = event.altKey; if (isGoForward && this._canGoForwardInHistory()) { this._goForwardInHistory(); event.consume(true); } return; } }, _canGoBackInHistory: function() { return this._historyIterator > 0; }, _goBackInHistory: function() { this._inHistory = true; this.setCurrentPanel(WebInspector.panels[this._history[--this._historyIterator]]); delete this._inHistory; }, _canGoForwardInHistory: function() { return this._historyIterator < this._history.length - 1; }, _goForwardInHistory: function() { this._inHistory = true; this.setCurrentPanel(WebInspector.panels[this._history[++this._historyIterator]]); delete this._inHistory; }, _pushToHistory: function(panelName) { if (this._inHistory) return; this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1); if (!this._history.length || this._history[this._history.length - 1] !== panelName) this._history.push(panelName); this._historyIterator = this._history.length - 1; }, panelsElement: function() { return this._panelsElement; }, setFooterElement: function(element) { if (element) { this._footerElementContainer.removeStyleClass("hidden"); this._footerElementContainer.appendChild(element); this._panelsElement.style.bottom = this._footerElementContainer.offsetHeight + "px"; } else { this._footerElementContainer.addStyleClass("hidden"); this._footerElementContainer.removeChildren(); this._panelsElement.style.bottom = 0; } this.doResize(); }, showPanelForAnchorNavigation: function(panel) { WebInspector.searchController.disableSearchUntilExplicitAction(); this.setCurrentPanel(panel); }, __proto__: WebInspector.View.prototype } WebInspector.inspectorView = null; WebInspector.AdvancedSearchController = function() { this._shortcut = WebInspector.AdvancedSearchController.createShortcut(); this._searchId = 0; WebInspector.settings.advancedSearchConfig = WebInspector.settings.createSetting("advancedSearchConfig", new WebInspector.SearchConfig("", true, false)); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this); } WebInspector.AdvancedSearchController.createShortcut = function() { if (WebInspector.isMac()) return WebInspector.KeyboardShortcut.makeDescriptor("f", WebInspector.KeyboardShortcut.Modifiers.Meta | WebInspector.KeyboardShortcut.Modifiers.Alt); else return WebInspector.KeyboardShortcut.makeDescriptor("f", WebInspector.KeyboardShortcut.Modifiers.Ctrl | WebInspector.KeyboardShortcut.Modifiers.Shift); } WebInspector.AdvancedSearchController.prototype = { handleShortcut: function(event) { if (WebInspector.KeyboardShortcut.makeKeyFromEvent(event) === this._shortcut.key) { if (!this._searchView || !this._searchView.isShowing() || this._searchView._search !== document.activeElement) { WebInspector.showPanel("scripts"); this.show(); } else this.close(); event.consume(true); return true; } return false; }, _frameNavigated: function() { this.resetSearch(); }, registerSearchScope: function(searchScope) { this._searchScope = searchScope; }, show: function() { if (!this._searchView) this._searchView = new WebInspector.SearchView(this); this._searchView.syncToSelection(); if (this._searchView.isShowing()) this._searchView.focus(); else WebInspector.showViewInDrawer(this._searchView._searchPanelElement, this._searchView, this.stopSearch.bind(this)); }, close: function() { this.stopSearch(); WebInspector.closeViewInDrawer(); }, _onSearchResult: function(searchId, searchResult) { if (searchId !== this._searchId) return; this._searchView.addSearchResult(searchResult); if (!searchResult.searchMatches.length) return; if (!this._searchResultsPane) this._searchResultsPane = this._currentSearchScope.createSearchResultsPane(this._searchConfig); this._searchView.resultsPane = this._searchResultsPane; this._searchResultsPane.addSearchResult(searchResult); }, _onSearchFinished: function(searchId, finished) { if (searchId !== this._searchId) return; if (!this._searchResultsPane) this._searchView.nothingFound(); this._searchView.searchFinished(finished); }, startSearch: function(searchConfig) { this.resetSearch(); ++this._searchId; this._searchConfig = searchConfig; this._currentSearchScope = this._searchScope; var totalSearchResultsCount = this._currentSearchScope.performSearch(searchConfig, this._onSearchResult.bind(this, this._searchId), this._onSearchFinished.bind(this, this._searchId)); this._searchView.searchStarted(totalSearchResultsCount); }, resetSearch: function() { this.stopSearch(); if (this._searchResultsPane) { this._searchView.resetResults(); delete this._searchResultsPane; } }, stopSearch: function() { if (this._currentSearchScope) this._currentSearchScope.stopSearch(); } } WebInspector.SearchView = function(controller) { WebInspector.View.call(this); this.registerRequiredCSS("textEditor.css"); this._controller = controller; this.element.className = "search-view"; this._searchPanelElement = document.createElement("span"); this._searchPanelElement.className = "search-drawer-header"; this._searchPanelElement.addEventListener("keydown", this._onKeyDown.bind(this), false); this._searchResultsElement = this.element.createChild("div"); this._searchResultsElement.className = "search-results"; this._searchLabel = this._searchPanelElement.createChild("span"); this._searchLabel.textContent = WebInspector.UIString("Search sources"); this._search = this._searchPanelElement.createChild("input"); this._search.setAttribute("type", "search"); this._search.addStyleClass("search-config-search"); this._search.setAttribute("results", "0"); this._search.setAttribute("size", 30); this._ignoreCaseLabel = this._searchPanelElement.createChild("label"); this._ignoreCaseLabel.addStyleClass("search-config-label"); this._ignoreCaseCheckbox = this._ignoreCaseLabel.createChild("input"); this._ignoreCaseCheckbox.setAttribute("type", "checkbox"); this._ignoreCaseCheckbox.addStyleClass("search-config-checkbox"); this._ignoreCaseLabel.appendChild(document.createTextNode(WebInspector.UIString("Ignore case"))); this._regexLabel = this._searchPanelElement.createChild("label"); this._regexLabel.addStyleClass("search-config-label"); this._regexCheckbox = this._regexLabel.createChild("input"); this._regexCheckbox.setAttribute("type", "checkbox"); this._regexCheckbox.addStyleClass("search-config-checkbox"); this._regexLabel.appendChild(document.createTextNode(WebInspector.UIString("Regular expression"))); this._searchStatusBarElement = document.createElement("div"); this._searchStatusBarElement.className = "search-status-bar-item"; this._searchMessageElement = this._searchStatusBarElement.createChild("div"); this._searchMessageElement.className = "search-status-bar-message"; this._searchResultsMessageElement = document.createElement("span"); this._searchResultsMessageElement.className = "search-results-status-bar-message"; this._load(); } WebInspector.SearchView.maxQueriesCount = 20; WebInspector.SearchView.prototype = { get statusBarItems() { return [this._searchStatusBarElement, this._searchResultsMessageElement]; }, get searchConfig() { return new WebInspector.SearchConfig(this._search.value, this._ignoreCaseCheckbox.checked, this._regexCheckbox.checked); }, syncToSelection: function() { var selection = window.getSelection(); if (selection.rangeCount) this._search.value = selection.toString().replace(/\r?\n.*/, ""); }, set resultsPane(resultsPane) { this.resetResults(); this._searchResultsElement.appendChild(resultsPane.element); }, searchStarted: function(totalSearchResultsCount) { this.resetResults(); this._resetCounters(); this._searchMessageElement.textContent = WebInspector.UIString("Searching..."); this._progressIndicator = new WebInspector.ProgressIndicator(); this._progressIndicator.setTotalWork(totalSearchResultsCount); this._progressIndicator.show(this._searchStatusBarElement); this._updateSearchResultsMessage(); if (!this._searchingView) this._searchingView = new WebInspector.EmptyView(WebInspector.UIString("Searching...")); this._searchingView.show(this._searchResultsElement); }, _updateSearchResultsMessage: function() { if (this._searchMatchesCount && this._searchResultsCount) this._searchResultsMessageElement.textContent = WebInspector.UIString("Found %d matches in %d files.", this._searchMatchesCount, this._nonEmptySearchResultsCount); else this._searchResultsMessageElement.textContent = ""; }, resetResults: function() { if (this._searchingView) this._searchingView.detach(); if (this._notFoundView) this._notFoundView.detach(); this._searchResultsElement.removeChildren(); }, _resetCounters: function() { this._searchMatchesCount = 0; this._searchResultsCount = 0; this._nonEmptySearchResultsCount = 0; }, nothingFound: function() { this.resetResults(); if (!this._notFoundView) this._notFoundView = new WebInspector.EmptyView(WebInspector.UIString("No matches found.")); this._notFoundView.show(this._searchResultsElement); this._searchResultsMessageElement.textContent = WebInspector.UIString("No matches found."); }, addSearchResult: function(searchResult) { this._searchMatchesCount += searchResult.searchMatches.length; this._searchResultsCount++; if (searchResult.searchMatches.length) this._nonEmptySearchResultsCount++; this._updateSearchResultsMessage(); if (this._progressIndicator.isCanceled()) this._onCancel(); else this._progressIndicator.setWorked(this._searchResultsCount); }, searchFinished: function(finished) { this._progressIndicator.done(); this._searchMessageElement.textContent = finished ? WebInspector.UIString("Search finished.") : WebInspector.UIString("Search interrupted."); }, focus: function() { WebInspector.setCurrentFocusElement(this._search); this._search.select(); }, wasShown: function() { this.focus(); }, willHide: function() { this._controller.stopSearch(); }, _onKeyDown: function(event) { switch (event.keyCode) { case WebInspector.KeyboardShortcut.Keys.Enter.code: this._onAction(); break; case WebInspector.KeyboardShortcut.Keys.Esc.code: this._controller.close(); event.consume(true); break; } }, _save: function() { var searchConfig = new WebInspector.SearchConfig(this.searchConfig.query, this.searchConfig.ignoreCase, this.searchConfig.isRegex); WebInspector.settings.advancedSearchConfig.set(searchConfig); }, _load: function() { var searchConfig = WebInspector.settings.advancedSearchConfig.get(); this._search.value = searchConfig.query; this._ignoreCaseCheckbox.checked = searchConfig.ignoreCase; this._regexCheckbox.checked = searchConfig.isRegex; }, _onCancel: function() { this._controller.stopSearch(); this.focus(); }, _onAction: function() { if (!this.searchConfig.query || !this.searchConfig.query.length) return; this._save(); this._controller.startSearch(this.searchConfig); }, __proto__: WebInspector.View.prototype } WebInspector.SearchConfig = function(query, ignoreCase, isRegex) { this.query = query; this.ignoreCase = ignoreCase; this.isRegex = isRegex; } WebInspector.SearchScope = function() { } WebInspector.SearchScope.prototype = { performSearch: function(searchConfig, searchResultCallback, searchFinishedCallback) { }, stopSearch: function() { }, createSearchResultsPane: function(searchConfig) { } } WebInspector.SearchResult = function(offset, length) { this.offset = offset; this.length = length; } WebInspector.SearchResultsPane = function(searchConfig) { this._searchConfig = searchConfig; this.element = document.createElement("div"); } WebInspector.SearchResultsPane.prototype = { get searchConfig() { return this._searchConfig; }, addSearchResult: function(searchResult) { } } WebInspector.FileBasedSearchResultsPane = function(searchConfig) { WebInspector.SearchResultsPane.call(this, searchConfig); this._searchResults = []; this.element.id ="search-results-pane-file-based"; this._treeOutlineElement = document.createElement("ol"); this._treeOutlineElement.className = "search-results-outline-disclosure"; this.element.appendChild(this._treeOutlineElement); this._treeOutline = new TreeOutline(this._treeOutlineElement); this._matchesExpandedCount = 0; } WebInspector.FileBasedSearchResultsPane.matchesExpandedByDefaultCount = 20; WebInspector.FileBasedSearchResultsPane.fileMatchesShownAtOnce = 20; WebInspector.FileBasedSearchResultsPane.prototype = { _createAnchor: function(uiSourceCode, lineNumber, columnNumber) { var anchor = document.createElement("a"); anchor.preferredPanel = "scripts"; anchor.href = sanitizeHref(uiSourceCode.url); anchor.uiSourceCode = uiSourceCode; anchor.lineNumber = lineNumber; return anchor; }, addSearchResult: function(searchResult) { this._searchResults.push(searchResult); var uiSourceCode = searchResult.uiSourceCode; var searchMatches = searchResult.searchMatches; var fileTreeElement = this._addFileTreeElement(uiSourceCode.url, searchMatches.length, this._searchResults.length - 1); }, _fileTreeElementExpanded: function(searchResult, fileTreeElement) { if (fileTreeElement._initialized) return; var toIndex = Math.min(searchResult.searchMatches.length, WebInspector.FileBasedSearchResultsPane.fileMatchesShownAtOnce); if (toIndex < searchResult.searchMatches.length) { this._appendSearchMatches(fileTreeElement, searchResult, 0, toIndex - 1); this._appendShowMoreMatchesElement(fileTreeElement, searchResult, toIndex - 1); } else this._appendSearchMatches(fileTreeElement, searchResult, 0, toIndex); fileTreeElement._initialized = true; }, _appendSearchMatches: function(fileTreeElement, searchResult, fromIndex, toIndex) { var uiSourceCode = searchResult.uiSourceCode; var searchMatches = searchResult.searchMatches; var regex = createSearchRegex(this._searchConfig.query, !this._searchConfig.ignoreCase, this._searchConfig.isRegex); for (var i = fromIndex; i < toIndex; ++i) { var lineNumber = searchMatches[i].lineNumber; var lineContent = searchMatches[i].lineContent; var matchRanges = this._regexMatchRanges(lineContent, regex); var anchor = this._createAnchor(uiSourceCode, lineNumber, matchRanges[0].offset); var numberString = numberToStringWithSpacesPadding(lineNumber + 1, 4); var lineNumberSpan = document.createElement("span"); lineNumberSpan.addStyleClass("webkit-line-number"); lineNumberSpan.addStyleClass("search-match-line-number"); lineNumberSpan.textContent = numberString; anchor.appendChild(lineNumberSpan); var contentSpan = this._createContentSpan(lineContent, matchRanges); anchor.appendChild(contentSpan); var searchMatchElement = new TreeElement("", null, false); fileTreeElement.appendChild(searchMatchElement); searchMatchElement.listItemElement.className = "search-match source-code"; searchMatchElement.listItemElement.appendChild(anchor); } }, _appendShowMoreMatchesElement: function(fileTreeElement, searchResult, startMatchIndex) { var matchesLeftCount = searchResult.searchMatches.length - startMatchIndex; var showMoreMatchesText = WebInspector.UIString("Show all matches (%d more).", matchesLeftCount); var showMoreMatchesElement = new TreeElement(showMoreMatchesText, null, false); fileTreeElement.appendChild(showMoreMatchesElement); showMoreMatchesElement.listItemElement.addStyleClass("show-more-matches"); showMoreMatchesElement.onselect = this._showMoreMatchesElementSelected.bind(this, searchResult, startMatchIndex, showMoreMatchesElement); }, _showMoreMatchesElementSelected: function(searchResult, startMatchIndex, showMoreMatchesElement) { var fileTreeElement = showMoreMatchesElement.parent; fileTreeElement.removeChild(showMoreMatchesElement); this._appendSearchMatches(fileTreeElement, searchResult, startMatchIndex, searchResult.searchMatches.length); }, _addFileTreeElement: function(fileName, searchMatchesCount, searchResultIndex) { var fileTreeElement = new TreeElement("", null, true); fileTreeElement.toggleOnClick = true; fileTreeElement.selectable = false; this._treeOutline.appendChild(fileTreeElement); fileTreeElement.listItemElement.addStyleClass("search-result"); var fileNameSpan = document.createElement("span"); fileNameSpan.className = "search-result-file-name"; fileNameSpan.textContent = fileName; fileTreeElement.listItemElement.appendChild(fileNameSpan); var matchesCountSpan = document.createElement("span"); matchesCountSpan.className = "search-result-matches-count"; if (searchMatchesCount === 1) matchesCountSpan.textContent = WebInspector.UIString("(%d match)", searchMatchesCount); else matchesCountSpan.textContent = WebInspector.UIString("(%d matches)", searchMatchesCount); fileTreeElement.listItemElement.appendChild(matchesCountSpan); var searchResult = this._searchResults[searchResultIndex]; fileTreeElement.onexpand = this._fileTreeElementExpanded.bind(this, searchResult, fileTreeElement); if (this._matchesExpandedCount < WebInspector.FileBasedSearchResultsPane.matchesExpandedByDefaultCount) fileTreeElement.expand(); this._matchesExpandedCount += searchResult.searchMatches.length; return fileTreeElement; }, _regexMatchRanges: function(lineContent, regex) { regex.lastIndex = 0; var match; var offset = 0; var matchRanges = []; while ((regex.lastIndex < lineContent.length) && (match = regex.exec(lineContent))) matchRanges.push(new WebInspector.SearchResult(match.index, match[0].length)); return matchRanges; }, _createContentSpan: function(lineContent, matchRanges) { var contentSpan = document.createElement("span"); contentSpan.className = "search-match-content"; contentSpan.textContent = lineContent; WebInspector.highlightRangesWithStyleClass(contentSpan, matchRanges, "highlighted-match"); return contentSpan; }, __proto__: WebInspector.SearchResultsPane.prototype } WebInspector.FileBasedSearchResultsPane.SearchResult = function(uiSourceCode, searchMatches) { this.uiSourceCode = uiSourceCode; this.searchMatches = searchMatches; } WebInspector.advancedSearchController = null; WebInspector.TimelineGrid = function() { this.element = document.createElement("div"); this._itemsGraphsElement = document.createElement("div"); this._itemsGraphsElement.id = "resources-graphs"; this.element.appendChild(this._itemsGraphsElement); this._dividersElement = document.createElement("div"); this._dividersElement.className = "resources-dividers"; this.element.appendChild(this._dividersElement); this._gridHeaderElement = document.createElement("div"); this._eventDividersElement = document.createElement("div"); this._eventDividersElement.className = "resources-event-dividers"; this._gridHeaderElement.appendChild(this._eventDividersElement); this._dividersLabelBarElement = document.createElement("div"); this._dividersLabelBarElement.className = "resources-dividers-label-bar"; this._gridHeaderElement.appendChild(this._dividersLabelBarElement); this.element.appendChild(this._gridHeaderElement); } WebInspector.TimelineGrid.prototype = { get itemsGraphsElement() { return this._itemsGraphsElement; }, get dividersElement() { return this._dividersElement; }, get dividersLabelBarElement() { return this._dividersLabelBarElement; }, get gridHeaderElement() { return this._gridHeaderElement; }, removeDividers: function() { this._dividersElement.removeChildren(); this._dividersLabelBarElement.removeChildren(); }, updateDividers: function(calculator) { var dividersElementClientWidth = this._dividersElement.clientWidth; var dividerCount = Math.round(dividersElementClientWidth / 64); var slice = calculator.boundarySpan() / dividerCount; this._currentDividerSlice = slice; var divider = this._dividersElement.firstChild; var dividerLabelBar = this._dividersLabelBarElement.firstChild; var paddingLeft = calculator.paddingLeft; for (var i = paddingLeft ? 0 : 1; i <= dividerCount; ++i) { if (!divider) { divider = document.createElement("div"); divider.className = "resources-divider"; this._dividersElement.appendChild(divider); dividerLabelBar = document.createElement("div"); dividerLabelBar.className = "resources-divider"; var label = document.createElement("div"); label.className = "resources-divider-label"; dividerLabelBar._labelElement = label; dividerLabelBar.appendChild(label); this._dividersLabelBarElement.appendChild(dividerLabelBar); } if (i === (paddingLeft ? 0 : 1)) { divider.addStyleClass("first"); dividerLabelBar.addStyleClass("first"); } else { divider.removeStyleClass("first"); dividerLabelBar.removeStyleClass("first"); } if (i === dividerCount) { divider.addStyleClass("last"); dividerLabelBar.addStyleClass("last"); } else { divider.removeStyleClass("last"); dividerLabelBar.removeStyleClass("last"); } var left; if (!slice) { left = dividersElementClientWidth / dividerCount * i + paddingLeft; dividerLabelBar._labelElement.textContent = ""; } else { left = calculator.computePosition(calculator.minimumBoundary() + slice * i); dividerLabelBar._labelElement.textContent = calculator.formatTime(slice * i); } var percentLeft = 100 * left / dividersElementClientWidth; this._setDividerAndBarLeft(divider, dividerLabelBar, percentLeft); divider = divider.nextSibling; dividerLabelBar = dividerLabelBar.nextSibling; } while (divider) { var nextDivider = divider.nextSibling; this._dividersElement.removeChild(divider); divider = nextDivider; } while (dividerLabelBar) { var nextDivider = dividerLabelBar.nextSibling; this._dividersLabelBarElement.removeChild(dividerLabelBar); dividerLabelBar = nextDivider; } return true; }, _setDividerAndBarLeft: function(divider, dividerLabelBar, percentLeft) { var percentStyleLeft = parseFloat(divider.style.left); if (!isNaN(percentStyleLeft) && Math.abs(percentStyleLeft - percentLeft) < 0.1) return; divider.style.left = percentLeft + "%"; dividerLabelBar.style.left = percentLeft + "%"; }, addEventDivider: function(divider) { this._eventDividersElement.appendChild(divider); }, addEventDividers: function(dividers) { this._gridHeaderElement.removeChild(this._eventDividersElement); for (var i = 0; i < dividers.length; ++i) { if (dividers[i]) this._eventDividersElement.appendChild(dividers[i]); } this._gridHeaderElement.appendChild(this._eventDividersElement); }, removeEventDividers: function() { this._eventDividersElement.removeChildren(); }, hideEventDividers: function() { this._eventDividersElement.addStyleClass("hidden"); }, showEventDividers: function() { this._eventDividersElement.removeStyleClass("hidden"); }, setScrollAndDividerTop: function(scrollTop, dividersTop) { this._dividersElement.style.top = scrollTop + "px"; } } WebInspector.TimelineGrid.Calculator = function() { } WebInspector.TimelineGrid.Calculator.prototype = { computePosition: function(time) { }, formatTime: function(time) { }, minimumBoundary: function() { }, maximumBoundary: function() { }, boundarySpan: function() { } } WebInspector.ContentProvider = function() { } WebInspector.ContentProvider.prototype = { contentURL: function() { }, contentType: function() { }, requestContent: function(callback) { }, searchInContent: function(query, caseSensitive, isRegex, callback) { } } WebInspector.ContentProvider.SearchMatch = function(lineNumber, lineContent) { this.lineNumber = lineNumber; this.lineContent = lineContent; } WebInspector.Resource = function(request, url, documentURL, frameId, loaderId, type, mimeType, isHidden, resourceId) { this._request = request; this.url = url; this._documentURL = documentURL; this._frameId = frameId; this._loaderId = loaderId; this._type = type || WebInspector.resourceTypes.Other; this._mimeType = mimeType; this._isHidden = isHidden; this._resourceId = resourceId; this._content; this._contentEncoded; this._pendingContentCallbacks = []; if (this._request && !this._request.finished) this._request.addEventListener(WebInspector.NetworkRequest.Events.FinishedLoading, this._requestFinished, this); } WebInspector.Resource.Events = { MessageAdded: "message-added", MessagesCleared: "messages-cleared", } WebInspector.Resource.prototype = { get request() { return this._request; }, get url() { return this._url; }, set url(x) { this._url = x; this._parsedURL = new WebInspector.ParsedURL(x); }, get parsedURL() { return this._parsedURL; }, get documentURL() { return this._documentURL; }, get frameId() { return this._frameId; }, get loaderId() { return this._loaderId; }, get resourceId() { return this._resourceId; }, get displayName() { return this._parsedURL.displayName; }, get type() { return this._request ? this._request.type : this._type; }, get mimeType() { return this._request ? this._request.mimeType : this._mimeType; }, get messages() { return this._messages || []; }, addMessage: function(msg) { if (!msg.isErrorOrWarning() || !msg.message) return; if (!this._messages) this._messages = []; this._messages.push(msg); this.dispatchEventToListeners(WebInspector.Resource.Events.MessageAdded, msg); }, get errors() { return this._errors || 0; }, set errors(x) { this._errors = x; }, get warnings() { return this._warnings || 0; }, set warnings(x) { this._warnings = x; }, clearErrorsAndWarnings: function() { this._messages = []; this._warnings = 0; this._errors = 0; this.dispatchEventToListeners(WebInspector.Resource.Events.MessagesCleared); }, get content() { return this._content; }, get contentEncoded() { return this._contentEncoded; }, contentURL: function() { return this._url; }, contentType: function() { return this.type; }, requestContent: function(callback) { if (typeof this._content !== "undefined") { callback(this._content, !!this._contentEncoded, this.canonicalMimeType()); return; } this._pendingContentCallbacks.push(callback); if (!this._request || this._request.finished) this._innerRequestContent(); }, canonicalMimeType: function() { return this.type.canonicalMimeType() || this.mimeType; }, searchInContent: function(query, caseSensitive, isRegex, callback) { function callbackWrapper(error, searchMatches) { callback(searchMatches || []); } if (this.frameId) PageAgent.searchInResource(this.frameId, this.url, query, caseSensitive, isRegex, callbackWrapper); else callback([]); }, populateImageSource: function(image) { function onResourceContent() { var imageSrc = WebInspector.contentAsDataURL(this._content, this.mimeType, this._contentEncoded); if (imageSrc === null) imageSrc = this.url; image.src = imageSrc; } this.requestContent(onResourceContent.bind(this)); }, _requestFinished: function() { this._request.removeEventListener(WebInspector.NetworkRequest.Events.FinishedLoading, this._requestFinished, this); if (this._pendingContentCallbacks.length) this._innerRequestContent(); }, _innerRequestContent: function() { if (this._contentRequested) return; this._contentRequested = true; function contentLoaded(content, contentEncoded) { this._content = content; this._contentEncoded = contentEncoded; var callbacks = this._pendingContentCallbacks.slice(); for (var i = 0; i < callbacks.length; ++i) callbacks[i](this._content, this._contentEncoded, this.canonicalMimeType()); this._pendingContentCallbacks.length = 0; delete this._contentRequested; } function resourceContentLoaded(error, content, contentEncoded) { if (error) console.error("Resource content request failed: " + error); contentLoaded.call(this, error ? null : content, contentEncoded); } if (this.request) { function requestContentLoaded(content, contentEncoded, mimeType) { contentLoaded.call(this, content, contentEncoded); } this.request.requestContent(requestContentLoaded.bind(this)); return; } PageAgent.getResourceContent(this.frameId, this.url, this.resourceId, resourceContentLoaded.bind(this)); }, isHidden: function() { return !!this._isHidden; }, __proto__: WebInspector.Object.prototype } WebInspector.NetworkRequest = function(requestId, url, documentURL, frameId, loaderId) { this._requestId = requestId; this.url = url; this._documentURL = documentURL; this._frameId = frameId; this._loaderId = loaderId; this._startTime = -1; this._endTime = -1; this.statusCode = 0; this.statusText = ""; this.requestMethod = ""; this.requestTime = 0; this.receiveHeadersEnd = 0; this._type = WebInspector.resourceTypes.Other; this._contentEncoded = false; this._pendingContentCallbacks = []; this._frames = []; } WebInspector.NetworkRequest.Events = { FinishedLoading: "FinishedLoading", TimingChanged: "TimingChanged", RequestHeadersChanged: "RequestHeadersChanged", ResponseHeadersChanged: "ResponseHeadersChanged", } WebInspector.NetworkRequest.prototype = { get requestId() { return this._requestId; }, set requestId(requestId) { this._requestId = requestId; }, get url() { return this._url; }, set url(x) { if (this._url === x) return; this._url = x; this._parsedURL = new WebInspector.ParsedURL(x); delete this._parsedQueryParameters; delete this._name; delete this._path; }, get documentURL() { return this._documentURL; }, get parsedURL() { return this._parsedURL; }, get frameId() { return this._frameId; }, get loaderId() { return this._loaderId; }, get startTime() { return this._startTime || -1; }, set startTime(x) { this._startTime = x; }, get responseReceivedTime() { return this._responseReceivedTime || -1; }, set responseReceivedTime(x) { this._responseReceivedTime = x; }, get endTime() { return this._endTime || -1; }, set endTime(x) { if (this.timing && this.timing.requestTime) { this._endTime = Math.max(x, this.responseReceivedTime); } else { this._endTime = x; if (this._responseReceivedTime > x) this._responseReceivedTime = x; } }, get duration() { if (this._endTime === -1 || this._startTime === -1) return -1; return this._endTime - this._startTime; }, get latency() { if (this._responseReceivedTime === -1 || this._startTime === -1) return -1; return this._responseReceivedTime - this._startTime; }, get receiveDuration() { if (this._endTime === -1 || this._responseReceivedTime === -1) return -1; return this._endTime - this._responseReceivedTime; }, get resourceSize() { return this._resourceSize || 0; }, set resourceSize(x) { this._resourceSize = x; }, get transferSize() { if (this.cached) return 0; if (this.statusCode === 304) return this.responseHeadersSize; if (this._transferSize !== undefined) return this._transferSize; var bodySize = Number(this.responseHeaderValue("Content-Length") || this.resourceSize); return this.responseHeadersSize + bodySize; }, increaseTransferSize: function(x) { this._transferSize = (this._transferSize || 0) + x; }, get finished() { return this._finished; }, set finished(x) { if (this._finished === x) return; this._finished = x; if (x) { this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.FinishedLoading, this); if (this._pendingContentCallbacks.length) this._innerRequestContent(); } }, get failed() { return this._failed; }, set failed(x) { this._failed = x; }, get canceled() { return this._canceled; }, set canceled(x) { this._canceled = x; }, get cached() { return this._cached; }, set cached(x) { this._cached = x; if (x) delete this._timing; }, get timing() { return this._timing; }, set timing(x) { if (x && !this._cached) { this._startTime = x.requestTime; this._responseReceivedTime = x.requestTime + x.receiveHeadersEnd / 1000.0; this._timing = x; this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.TimingChanged, this); } }, get mimeType() { return this._mimeType; }, set mimeType(x) { this._mimeType = x; }, get displayName() { return this._parsedURL.displayName; }, name: function() { if (this._name) return this._name; this._parseNameAndPathFromURL(); return this._name; }, path: function() { if (this._path) return this._path; this._parseNameAndPathFromURL(); return this._path; }, _parseNameAndPathFromURL: function() { if (this._parsedURL.isDataURL()) { this._name = this._parsedURL.dataURLDisplayName(); this._path = ""; } else if (this._parsedURL.isAboutBlank()) { this._name = this._parsedURL.url; this._path = ""; } else { this._path = this._parsedURL.host + this._parsedURL.folderPathComponents; this._path = this._path.trimURL(WebInspector.inspectedPageDomain ? WebInspector.inspectedPageDomain : ""); if (this._parsedURL.lastPathComponent || this._parsedURL.queryParams) this._name = this._parsedURL.lastPathComponent + (this._parsedURL.queryParams ? "?" + this._parsedURL.queryParams : ""); else if (this._parsedURL.folderPathComponents) { this._name = this._parsedURL.folderPathComponents.substring(this._parsedURL.folderPathComponents.lastIndexOf("/") + 1) + "/"; this._path = this._path.substring(0, this._path.lastIndexOf("/")); } else { this._name = this._parsedURL.host; this._path = ""; } } }, get folder() { var path = this._parsedURL.path; var indexOfQuery = path.indexOf("?"); if (indexOfQuery !== -1) path = path.substring(0, indexOfQuery); var lastSlashIndex = path.lastIndexOf("/"); return lastSlashIndex !== -1 ? path.substring(0, lastSlashIndex) : ""; }, get type() { return this._type; }, set type(x) { this._type = x; }, get redirectSource() { if (this.redirects && this.redirects.length > 0) return this.redirects[this.redirects.length - 1]; return this._redirectSource; }, set redirectSource(x) { this._redirectSource = x; }, get requestHeaders() { return this._requestHeaders || []; }, set requestHeaders(x) { this._requestHeaders = x; delete this._sortedRequestHeaders; delete this._requestCookies; this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RequestHeadersChanged); }, get requestHeadersText() { if (typeof this._requestHeadersText === "undefined") { this._requestHeadersText = this.requestMethod + " " + this.url + " HTTP/1.1\r\n"; for (var i = 0; i < this.requestHeaders.length; ++i) this._requestHeadersText += this.requestHeaders[i].name + ": " + this.requestHeaders[i].value + "\r\n"; } return this._requestHeadersText; }, set requestHeadersText(x) { this._requestHeadersText = x; this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RequestHeadersChanged); }, get requestHeadersSize() { return this.requestHeadersText.length; }, get sortedRequestHeaders() { if (this._sortedRequestHeaders !== undefined) return this._sortedRequestHeaders; this._sortedRequestHeaders = []; this._sortedRequestHeaders = this.requestHeaders.slice(); this._sortedRequestHeaders.sort(function(a,b) { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()) }); return this._sortedRequestHeaders; }, requestHeaderValue: function(headerName) { return this._headerValue(this.requestHeaders, headerName); }, get requestCookies() { if (!this._requestCookies) this._requestCookies = WebInspector.CookieParser.parseCookie(this.requestHeaderValue("Cookie")); return this._requestCookies; }, get requestFormData() { return this._requestFormData; }, set requestFormData(x) { this._requestFormData = x; delete this._parsedFormParameters; }, get requestHttpVersion() { var firstLine = this.requestHeadersText.split(/\r\n/)[0]; var match = firstLine.match(/(HTTP\/\d+\.\d+)$/); return match ? match[1] : undefined; }, get responseHeaders() { return this._responseHeaders || []; }, set responseHeaders(x) { this._responseHeaders = x; delete this._sortedResponseHeaders; delete this._responseCookies; this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.ResponseHeadersChanged); }, get responseHeadersText() { if (typeof this._responseHeadersText === "undefined") { this._responseHeadersText = "HTTP/1.1 " + this.statusCode + " " + this.statusText + "\r\n"; for (var i = 0; i < this.responseHeaders.length; ++i) this._responseHeadersText += this.responseHeaders[i].name + ": " + this.responseHeaders[i].value + "\r\n"; } return this._responseHeadersText; }, set responseHeadersText(x) { this._responseHeadersText = x; this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.ResponseHeadersChanged); }, get responseHeadersSize() { return this.responseHeadersText.length; }, get sortedResponseHeaders() { if (this._sortedResponseHeaders !== undefined) return this._sortedResponseHeaders; this._sortedResponseHeaders = []; this._sortedResponseHeaders = this.responseHeaders.slice(); this._sortedResponseHeaders.sort(function(a,b) { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()) }); return this._sortedResponseHeaders; }, responseHeaderValue: function(headerName) { return this._headerValue(this.responseHeaders, headerName); }, get responseCookies() { if (!this._responseCookies) this._responseCookies = WebInspector.CookieParser.parseSetCookie(this.responseHeaderValue("Set-Cookie")); return this._responseCookies; }, queryString: function() { if (this._queryString) return this._queryString; var queryString = this.url.split("?", 2)[1]; if (!queryString) return null; this._queryString = queryString.split("#", 2)[0]; return this._queryString; }, get queryParameters() { if (this._parsedQueryParameters) return this._parsedQueryParameters; var queryString = this.queryString(); if (!queryString) return null; this._parsedQueryParameters = this._parseParameters(queryString); return this._parsedQueryParameters; }, get formParameters() { if (this._parsedFormParameters) return this._parsedFormParameters; if (!this.requestFormData) return null; var requestContentType = this.requestContentType(); if (!requestContentType || !requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) return null; this._parsedFormParameters = this._parseParameters(this.requestFormData); return this._parsedFormParameters; }, get responseHttpVersion() { var match = this.responseHeadersText.match(/^(HTTP\/\d+\.\d+)/); return match ? match[1] : undefined; }, _parseParameters: function(queryString) { function parseNameValue(pair) { var parameter = {}; var splitPair = pair.split("=", 2); parameter.name = splitPair[0]; if (splitPair.length === 1) parameter.value = ""; else parameter.value = splitPair[1]; return parameter; } return queryString.split("&").map(parseNameValue); }, _headerValue: function(headers, headerName) { headerName = headerName.toLowerCase(); var values = []; for (var i = 0; i < headers.length; ++i) { if (headers[i].name.toLowerCase() === headerName) values.push(headers[i].value); } if (headerName === "set-cookie") return values.join("\n"); return values.join(", "); }, get content() { return this._content; }, get contentEncoded() { return this._contentEncoded; }, contentURL: function() { return this._url; }, contentType: function() { return this._type; }, requestContent: function(callback) { if (this.type === WebInspector.resourceTypes.WebSocket) { callback(null, false, this._mimeType); return; } if (typeof this._content !== "undefined") { callback(this.content || null, this._contentEncoded, this._mimeType); return; } this._pendingContentCallbacks.push(callback); if (this.finished) this._innerRequestContent(); }, searchInContent: function(query, caseSensitive, isRegex, callback) { callback([]); }, isHttpFamily: function() { return !!this.url.match(/^https?:/i); }, requestContentType: function() { return this.requestHeaderValue("Content-Type"); }, isPingRequest: function() { return "text/ping" === this.requestContentType(); }, hasErrorStatusCode: function() { return this.statusCode >= 400; }, populateImageSource: function(image) { function onResourceContent(content, contentEncoded, mimeType) { var imageSrc = this.asDataURL(); if (imageSrc === null) imageSrc = this.url; image.src = imageSrc; } this.requestContent(onResourceContent.bind(this)); }, asDataURL: function() { return WebInspector.contentAsDataURL(this._content, this.mimeType, this._contentEncoded); }, _innerRequestContent: function() { if (this._contentRequested) return; this._contentRequested = true; function onResourceContent(error, content, contentEncoded) { this._content = error ? null : content; this._contentEncoded = contentEncoded; var callbacks = this._pendingContentCallbacks.slice(); for (var i = 0; i < callbacks.length; ++i) callbacks[i](this._content, this._contentEncoded, this._mimeType); this._pendingContentCallbacks.length = 0; delete this._contentRequested; } NetworkAgent.getResponseBody(this._requestId, onResourceContent.bind(this)); }, frames: function() { return this._frames; }, frame: function(position) { return this._frames[position]; }, addFrameError: function(errorMessage, time) { var errorObject = {}; errorObject.errorMessage = errorMessage; errorObject.time = time; this._pushFrame(errorObject); }, addFrame: function(response, time, sent) { response.time = time; if (sent) response.sent = true; this._pushFrame(response); }, _pushFrame: function(object) { if (this._frames.length >= 100) { this._frames.splice(0, 10); } this._frames.push(object); }, __proto__: WebInspector.Object.prototype } WebInspector.UISourceCode = function(workspace, url, contentType, isEditable) { this._workspace = workspace; this._url = url; this._parsedURL = new WebInspector.ParsedURL(url); this._contentType = contentType; this._isEditable = isEditable; this._requestContentCallbacks = []; this._liveLocations = []; this._consoleMessages = []; this.history = []; if (this.isEditable() && this._url) this._restoreRevisionHistory(); this._formatterMapping = new WebInspector.IdentityFormatterSourceMapping(); } WebInspector.UISourceCode.Events = { FormattedChanged: "FormattedChanged", WorkingCopyChanged: "WorkingCopyChanged", WorkingCopyCommitted: "WorkingCopyCommitted", TitleChanged: "TitleChanged", ConsoleMessageAdded: "ConsoleMessageAdded", ConsoleMessageRemoved: "ConsoleMessageRemoved", ConsoleMessagesCleared: "ConsoleMessagesCleared", SourceMappingChanged: "SourceMappingChanged", } WebInspector.UISourceCode.prototype = { get url() { return this._url; }, urlChanged: function(url) { this._url = url; this._parsedURL = new WebInspector.ParsedURL(this._url); this.dispatchEventToListeners(WebInspector.UISourceCode.Events.TitleChanged, null); }, get parsedURL() { return this._parsedURL; }, contentURL: function() { return this._url; }, contentType: function() { return this._contentType; }, scriptFile: function() { return this._scriptFile; }, setScriptFile: function(scriptFile) { this._scriptFile = scriptFile; }, styleFile: function() { return this._styleFile; }, setStyleFile: function(styleFile) { this._styleFile = styleFile; }, requestContent: function(callback) { if (this._content || this._contentLoaded) { callback(this._content, false, this._mimeType); return; } this._requestContentCallbacks.push(callback); if (this._requestContentCallbacks.length === 1) this._workspace.requestFileContent(this, this._fireContentAvailable.bind(this)); }, requestOriginalContent: function(callback) { this._workspace.requestFileContent(this, callback); }, _commitContent: function(content) { this._content = content; this._contentLoaded = true; var lastRevision = this.history.length ? this.history[this.history.length - 1] : null; if (!lastRevision || lastRevision._content !== this._content) { var revision = new WebInspector.Revision(this, this._content, new Date()); this.history.push(revision); revision._persist(); } var oldWorkingCopy = this._workingCopy; delete this._workingCopy; this.dispatchEventToListeners(WebInspector.UISourceCode.Events.WorkingCopyCommitted, {oldWorkingCopy: oldWorkingCopy, workingCopy: this.workingCopy()}); this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.UISourceCodeContentCommitted, { uiSourceCode: this, content: this._content }); if (this._url && WebInspector.fileManager.isURLSaved(this._url)) { WebInspector.fileManager.save(this._url, this._content, false); WebInspector.fileManager.close(this._url); } this._workspace.setFileContent(this, this._content, function() { }); }, addRevision: function(content) { this._commitContent(content); }, _restoreRevisionHistory: function() { if (!window.localStorage) return; var registry = WebInspector.Revision._revisionHistoryRegistry(); var historyItems = registry[this.url]; if (!historyItems || !historyItems.length) return; for (var i = 0; i < historyItems.length; ++i) { var content = window.localStorage[historyItems[i].key]; var timestamp = new Date(historyItems[i].timestamp); var revision = new WebInspector.Revision(this, content, timestamp); this.history.push(revision); } this._content = this.history[this.history.length - 1].content; this._contentLoaded = true; this._mimeType = this.canonicalMimeType(); }, _clearRevisionHistory: function() { if (!window.localStorage) return; var registry = WebInspector.Revision._revisionHistoryRegistry(); var historyItems = registry[this.url]; for (var i = 0; historyItems && i < historyItems.length; ++i) delete window.localStorage[historyItems[i].key]; delete registry[this.url]; window.localStorage["revision-history"] = JSON.stringify(registry); }, revertToOriginal: function() { function callback(content, contentEncoded, mimeType) { if (typeof content !== "string") return; this.addRevision(content); } this.requestOriginalContent(callback.bind(this)); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.ApplyOriginalContent, url: this.url }); }, revertAndClearHistory: function(callback) { function revert(content, contentEncoded, mimeType) { if (typeof content !== "string") return; this.addRevision(content); this._clearRevisionHistory(); this.history = []; callback(this); } this.requestOriginalContent(revert.bind(this)); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.RevertRevision, url: this.url }); }, isEditable: function() { return this._isEditable; }, workingCopy: function() { if (this.isDirty()) return this._workingCopy; return this._content; }, setWorkingCopy: function(newWorkingCopy) { var wasDirty = this.isDirty(); this._mimeType = this.canonicalMimeType(); var oldWorkingCopy = this._workingCopy; if (this._content === newWorkingCopy) delete this._workingCopy; else this._workingCopy = newWorkingCopy; this.dispatchEventToListeners(WebInspector.UISourceCode.Events.WorkingCopyChanged, {oldWorkingCopy: oldWorkingCopy, workingCopy: this.workingCopy(), wasDirty: wasDirty}); }, commitWorkingCopy: function(callback) { if (!this.isDirty()) { callback(null); return; } this._commitContent(this._workingCopy); callback(null); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.FileSaved, url: this.url }); }, isDirty: function() { return typeof this._workingCopy !== "undefined" && this._workingCopy !== this._content; }, mimeType: function() { return this._mimeType; }, canonicalMimeType: function() { return this.contentType().canonicalMimeType() || this._mimeType; }, content: function() { return this._content; }, searchInContent: function(query, caseSensitive, isRegex, callback) { var content = this.content(); if (content) { var provider = new WebInspector.StaticContentProvider(this.contentType(), content); provider.searchInContent(query, caseSensitive, isRegex, callback); return; } this._workspace.searchInFileContent(this, query, caseSensitive, isRegex, callback); }, _fireContentAvailable: function(content, contentEncoded, mimeType) { this._contentLoaded = true; this._mimeType = mimeType; this._content = content; var callbacks = this._requestContentCallbacks.slice(); this._requestContentCallbacks = []; for (var i = 0; i < callbacks.length; ++i) callbacks[i](content, contentEncoded, mimeType); if (this._formatOnLoad) { delete this._formatOnLoad; this.setFormatted(true); } }, contentLoaded: function() { return this._contentLoaded; }, uiLocationToRawLocation: function(lineNumber, columnNumber) { if (!this._sourceMapping) return null; var location = this._formatterMapping.formattedToOriginal(lineNumber, columnNumber); return this._sourceMapping.uiLocationToRawLocation(this, location[0], location[1]); }, addLiveLocation: function(liveLocation) { this._liveLocations.push(liveLocation); }, removeLiveLocation: function(liveLocation) { this._liveLocations.remove(liveLocation); }, updateLiveLocations: function() { var locationsCopy = this._liveLocations.slice(); for (var i = 0; i < locationsCopy.length; ++i) locationsCopy[i].update(); }, overrideLocation: function(uiLocation) { var location = this._formatterMapping.originalToFormatted(uiLocation.lineNumber, uiLocation.columnNumber); uiLocation.lineNumber = location[0]; uiLocation.columnNumber = location[1]; return uiLocation; }, consoleMessages: function() { return this._consoleMessages; }, consoleMessageAdded: function(message) { this._consoleMessages.push(message); this.dispatchEventToListeners(WebInspector.UISourceCode.Events.ConsoleMessageAdded, message); }, consoleMessageRemoved: function(message) { this._consoleMessages.remove(message); this.dispatchEventToListeners(WebInspector.UISourceCode.Events.ConsoleMessageRemoved, message); }, consoleMessagesCleared: function() { this._consoleMessages = []; this.dispatchEventToListeners(WebInspector.UISourceCode.Events.ConsoleMessagesCleared); }, formatted: function() { return !!this._formatted; }, setFormatted: function(formatted) { if (!this.contentLoaded()) { this._formatOnLoad = formatted; return; } if (this._formatted === formatted) return; this._formatted = formatted; this._contentLoaded = false; this._content = false; WebInspector.UISourceCode.prototype.requestContent.call(this, didGetContent.bind(this)); function didGetContent(content, contentEncoded, mimeType) { var formatter; if (!formatted) formatter = new WebInspector.IdentityFormatter(); else formatter = WebInspector.Formatter.createFormatter(this.contentType()); formatter.formatContent(mimeType, content || "", formattedChanged.bind(this)); function formattedChanged(content, formatterMapping) { this._content = content; delete this._workingCopy; this._formatterMapping = formatterMapping; this.dispatchEventToListeners(WebInspector.UISourceCode.Events.FormattedChanged, {content: content}); this.updateLiveLocations(); } } }, createFormatter: function() { return null; }, setSourceMapping: function(sourceMapping) { this._sourceMapping = sourceMapping; this.dispatchEventToListeners(WebInspector.UISourceCode.Events.SourceMappingChanged, null); }, __proto__: WebInspector.Object.prototype } WebInspector.UISourceCodeProvider = function() { } WebInspector.UISourceCodeProvider.Events = { UISourceCodeAdded: "UISourceCodeAdded", TemporaryUISourceCodeAdded: "TemporaryUISourceCodeAdded", TemporaryUISourceCodeRemoved: "TemporaryUISourceCodeRemoved", UISourceCodeRemoved: "UISourceCodeRemoved" } WebInspector.UISourceCodeProvider.prototype = { uiSourceCodes: function() {}, addEventListener: function(eventType, listener, thisObject) { }, removeEventListener: function(eventType, listener, thisObject) { } } WebInspector.UILocation = function(uiSourceCode, lineNumber, columnNumber) { this.uiSourceCode = uiSourceCode; this.lineNumber = lineNumber; this.columnNumber = columnNumber; } WebInspector.UILocation.prototype = { uiLocationToRawLocation: function() { return this.uiSourceCode.uiLocationToRawLocation(this.lineNumber, this.columnNumber); }, url: function() { return this.uiSourceCode.contentURL(); } } WebInspector.RawLocation = function() { } WebInspector.LiveLocation = function(rawLocation, updateDelegate) { this._rawLocation = rawLocation; this._updateDelegate = updateDelegate; this._uiSourceCodes = []; } WebInspector.LiveLocation.prototype = { update: function() { var uiLocation = this.uiLocation(); if (uiLocation) { var uiSourceCode = uiLocation.uiSourceCode; if (this._uiSourceCodes.indexOf(uiSourceCode) === -1) { uiSourceCode.addLiveLocation(this); this._uiSourceCodes.push(uiSourceCode); } var oneTime = this._updateDelegate(uiLocation); if (oneTime) this.dispose(); } }, rawLocation: function() { return this._rawLocation; }, uiLocation: function() { }, dispose: function() { for (var i = 0; i < this._uiSourceCodes.length; ++i) this._uiSourceCodes[i].removeLiveLocation(this); this._uiSourceCodes = []; } } WebInspector.Revision = function(uiSourceCode, content, timestamp) { this._uiSourceCode = uiSourceCode; this._content = content; this._timestamp = timestamp; } WebInspector.Revision._revisionHistoryRegistry = function() { if (!WebInspector.Revision._revisionHistoryRegistryObject) { if (window.localStorage) { var revisionHistory = window.localStorage["revision-history"]; try { WebInspector.Revision._revisionHistoryRegistryObject = revisionHistory ? JSON.parse(revisionHistory) : {}; } catch (e) { WebInspector.Revision._revisionHistoryRegistryObject = {}; } } else WebInspector.Revision._revisionHistoryRegistryObject = {}; } return WebInspector.Revision._revisionHistoryRegistryObject; } WebInspector.Revision.filterOutStaleRevisions = function() { if (!window.localStorage) return; var registry = WebInspector.Revision._revisionHistoryRegistry(); var filteredRegistry = {}; for (var url in registry) { var historyItems = registry[url]; var filteredHistoryItems = []; for (var i = 0; historyItems && i < historyItems.length; ++i) { var historyItem = historyItems[i]; if (historyItem.loaderId === WebInspector.resourceTreeModel.mainFrame.loaderId) { filteredHistoryItems.push(historyItem); filteredRegistry[url] = filteredHistoryItems; } else delete window.localStorage[historyItem.key]; } } WebInspector.Revision._revisionHistoryRegistryObject = filteredRegistry; function persist() { window.localStorage["revision-history"] = JSON.stringify(filteredRegistry); } setTimeout(persist, 0); } WebInspector.Revision.prototype = { get uiSourceCode() { return this._uiSourceCode; }, get timestamp() { return this._timestamp; }, get content() { return this._content || null; }, revertToThis: function() { function revert(content) { if (this._uiSourceCode._content !== content) this._uiSourceCode.addRevision(content); } this.requestContent(revert.bind(this)); }, contentURL: function() { return this._uiSourceCode.url; }, contentType: function() { return this._uiSourceCode.contentType(); }, requestContent: function(callback) { callback(this._content || "", false, this.uiSourceCode.canonicalMimeType()); }, searchInContent: function(query, caseSensitive, isRegex, callback) { callback([]); }, _persist: function() { if (!window.localStorage) return; var url = this.contentURL(); if (!url || url.startsWith("inspector://")) return; var loaderId = WebInspector.resourceTreeModel.mainFrame.loaderId; var timestamp = this.timestamp.getTime(); var key = "revision-history|" + url + "|" + loaderId + "|" + timestamp; var registry = WebInspector.Revision._revisionHistoryRegistry(); var historyItems = registry[url]; if (!historyItems) { historyItems = []; registry[url] = historyItems; } historyItems.push({url: url, loaderId: loaderId, timestamp: timestamp, key: key}); function persist() { window.localStorage[key] = this._content; window.localStorage["revision-history"] = JSON.stringify(registry); } setTimeout(persist.bind(this), 0); } } WebInspector.CSSStyleModel = function() { this._pendingCommandsMajorState = []; this._locations = []; this._sourceMappings = {}; WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.UndoRedoRequested, this._undoRedoRequested, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.UndoRedoCompleted, this._undoRedoCompleted, this); this._resourceBinding = new WebInspector.CSSStyleModelResourceBinding(); this._namedFlowCollections = {}; WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, this._resetNamedFlowCollections, this); InspectorBackend.registerCSSDispatcher(new WebInspector.CSSDispatcher(this)); CSSAgent.enable(); } WebInspector.CSSStyleModel.parseRuleArrayPayload = function(ruleArray) { var result = []; for (var i = 0; i < ruleArray.length; ++i) result.push(WebInspector.CSSRule.parsePayload(ruleArray[i])); return result; } WebInspector.CSSStyleModel.parseRuleMatchArrayPayload = function(matchArray) { var result = []; for (var i = 0; i < matchArray.length; ++i) result.push(WebInspector.CSSRule.parsePayload(matchArray[i].rule, matchArray[i].matchingSelectors)); return result; } WebInspector.CSSStyleModel.Events = { StyleSheetChanged: "StyleSheetChanged", MediaQueryResultChanged: "MediaQueryResultChanged", NamedFlowCreated: "NamedFlowCreated", NamedFlowRemoved: "NamedFlowRemoved", RegionLayoutUpdated: "RegionLayoutUpdated" } WebInspector.CSSStyleModel.MediaTypes = ["all", "braille", "embossed", "handheld", "print", "projection", "screen", "speech", "tty", "tv"]; WebInspector.CSSStyleModel.prototype = { getMatchedStylesAsync: function(nodeId, needPseudo, needInherited, userCallback) { function callback(userCallback, error, matchedPayload, pseudoPayload, inheritedPayload) { if (error) { if (userCallback) userCallback(null); return; } var result = {}; if (matchedPayload) result.matchedCSSRules = WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(matchedPayload); if (pseudoPayload) { result.pseudoElements = []; for (var i = 0; i < pseudoPayload.length; ++i) { var entryPayload = pseudoPayload[i]; result.pseudoElements.push({ pseudoId: entryPayload.pseudoId, rules: WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(entryPayload.matches) }); } } if (inheritedPayload) { result.inherited = []; for (var i = 0; i < inheritedPayload.length; ++i) { var entryPayload = inheritedPayload[i]; var entry = {}; if (entryPayload.inlineStyle) entry.inlineStyle = WebInspector.CSSStyleDeclaration.parsePayload(entryPayload.inlineStyle); if (entryPayload.matchedCSSRules) entry.matchedCSSRules = WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(entryPayload.matchedCSSRules); result.inherited.push(entry); } } if (userCallback) userCallback(result); } CSSAgent.getMatchedStylesForNode(nodeId, needPseudo, needInherited, callback.bind(null, userCallback)); }, getComputedStyleAsync: function(nodeId, userCallback) { function callback(userCallback, error, computedPayload) { if (error || !computedPayload) userCallback(null); else userCallback(WebInspector.CSSStyleDeclaration.parseComputedStylePayload(computedPayload)); } CSSAgent.getComputedStyleForNode(nodeId, callback.bind(null, userCallback)); }, getInlineStylesAsync: function(nodeId, userCallback) { function callback(userCallback, error, inlinePayload, attributesStylePayload) { if (error || !inlinePayload) userCallback(null, null); else userCallback(WebInspector.CSSStyleDeclaration.parsePayload(inlinePayload), attributesStylePayload ? WebInspector.CSSStyleDeclaration.parsePayload(attributesStylePayload) : null); } CSSAgent.getInlineStylesForNode(nodeId, callback.bind(null, userCallback)); }, forcePseudoState: function(nodeId, forcedPseudoClasses, userCallback) { CSSAgent.forcePseudoState(nodeId, forcedPseudoClasses || [], userCallback); }, getNamedFlowCollectionAsync: function(documentNodeId, userCallback) { var namedFlowCollection = this._namedFlowCollections[documentNodeId]; if (namedFlowCollection) { userCallback(namedFlowCollection); return; } function callback(userCallback, error, namedFlowPayload) { if (error || !namedFlowPayload) userCallback(null); else { var namedFlowCollection = new WebInspector.NamedFlowCollection(namedFlowPayload); this._namedFlowCollections[documentNodeId] = namedFlowCollection; userCallback(namedFlowCollection); } } CSSAgent.getNamedFlowCollection(documentNodeId, callback.bind(this, userCallback)); }, getFlowByNameAsync: function(documentNodeId, flowName, userCallback) { var namedFlowCollection = this._namedFlowCollections[documentNodeId]; if (namedFlowCollection) { userCallback(namedFlowCollection.flowByName(flowName)); return; } function callback(userCallback, namedFlowCollection) { if (!namedFlowCollection) userCallback(null); else userCallback(namedFlowCollection.flowByName(flowName)); } this.getNamedFlowCollectionAsync(documentNodeId, callback.bind(this, userCallback)); }, setRuleSelector: function(ruleId, nodeId, newSelector, successCallback, failureCallback) { function checkAffectsCallback(nodeId, successCallback, rulePayload, selectedNodeIds) { if (!selectedNodeIds) return; var doesAffectSelectedNode = (selectedNodeIds.indexOf(nodeId) >= 0); var rule = WebInspector.CSSRule.parsePayload(rulePayload); successCallback(rule, doesAffectSelectedNode); } function callback(nodeId, successCallback, failureCallback, newSelector, error, rulePayload) { this._pendingCommandsMajorState.pop(); if (error) failureCallback(); else { WebInspector.domAgent.markUndoableState(); var ownerDocumentId = this._ownerDocumentId(nodeId); if (ownerDocumentId) WebInspector.domAgent.querySelectorAll(ownerDocumentId, newSelector, checkAffectsCallback.bind(this, nodeId, successCallback, rulePayload)); else failureCallback(); } } this._pendingCommandsMajorState.push(true); CSSAgent.setRuleSelector(ruleId, newSelector, callback.bind(this, nodeId, successCallback, failureCallback, newSelector)); }, addRule: function(nodeId, selector, successCallback, failureCallback) { function checkAffectsCallback(nodeId, successCallback, rulePayload, selectedNodeIds) { if (!selectedNodeIds) return; var doesAffectSelectedNode = (selectedNodeIds.indexOf(nodeId) >= 0); var rule = WebInspector.CSSRule.parsePayload(rulePayload); successCallback(rule, doesAffectSelectedNode); } function callback(successCallback, failureCallback, selector, error, rulePayload) { this._pendingCommandsMajorState.pop(); if (error) { failureCallback(); } else { WebInspector.domAgent.markUndoableState(); var ownerDocumentId = this._ownerDocumentId(nodeId); if (ownerDocumentId) WebInspector.domAgent.querySelectorAll(ownerDocumentId, selector, checkAffectsCallback.bind(this, nodeId, successCallback, rulePayload)); else failureCallback(); } } this._pendingCommandsMajorState.push(true); CSSAgent.addRule(nodeId, selector, callback.bind(this, successCallback, failureCallback, selector)); }, mediaQueryResultChanged: function() { this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged); }, _ownerDocumentId: function(nodeId) { var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) return null; return node.ownerDocument ? node.ownerDocument.id : null; }, _fireStyleSheetChanged: function(styleSheetId) { if (!this._pendingCommandsMajorState.length) return; var majorChange = this._pendingCommandsMajorState[this._pendingCommandsMajorState.length - 1]; if (!majorChange || !styleSheetId || !this.hasEventListeners(WebInspector.CSSStyleModel.Events.StyleSheetChanged)) return; this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.StyleSheetChanged, { styleSheetId: styleSheetId, majorChange: majorChange }); }, _namedFlowCreated: function(namedFlowPayload) { var namedFlow = WebInspector.NamedFlow.parsePayload(namedFlowPayload); var namedFlowCollection = this._namedFlowCollections[namedFlow.documentNodeId]; if (!namedFlowCollection) return; namedFlowCollection._appendNamedFlow(namedFlow); this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.NamedFlowCreated, namedFlow); }, _namedFlowRemoved: function(documentNodeId, flowName) { var namedFlowCollection = this._namedFlowCollections[documentNodeId]; if (!namedFlowCollection) return; namedFlowCollection._removeNamedFlow(flowName); this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.NamedFlowRemoved, { documentNodeId: documentNodeId, flowName: flowName }); }, _regionLayoutUpdated: function(namedFlowPayload) { var namedFlow = WebInspector.NamedFlow.parsePayload(namedFlowPayload); var namedFlowCollection = this._namedFlowCollections[namedFlow.documentNodeId]; if (!namedFlowCollection) return; namedFlowCollection._appendNamedFlow(namedFlow); this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.RegionLayoutUpdated, namedFlow); }, setStyleSheetText: function(styleSheetId, newText, majorChange, userCallback) { function callback(error) { this._pendingCommandsMajorState.pop(); if (!error && majorChange) WebInspector.domAgent.markUndoableState(); if (!error && userCallback) userCallback(error); } this._pendingCommandsMajorState.push(majorChange); CSSAgent.setStyleSheetText(styleSheetId, newText, callback.bind(this)); }, _undoRedoRequested: function() { this._pendingCommandsMajorState.push(true); }, _undoRedoCompleted: function() { this._pendingCommandsMajorState.pop(); }, getViaInspectorResourceForRule: function(rule, callback) { if (!rule.id) { callback(null); return; } this._resourceBinding._requestViaInspectorResource(rule.id.styleSheetId, callback); }, resourceBinding: function() { return this._resourceBinding; }, setSourceMapping: function(url, sourceMapping) { this._sourceMappings[url] = sourceMapping; this._updateLocations(); }, resetSourceMappings: function() { this._sourceMappings = {}; }, _resetNamedFlowCollections: function() { this._namedFlowCollections = {}; }, _updateLocations: function() { for (var i = 0; i < this._locations.length; ++i) this._locations[i].update(); }, createLiveLocation: function(cssRule, updateDelegate) { if (!cssRule._rawLocation) return null; var location = new WebInspector.CSSStyleModel.LiveLocation(cssRule._rawLocation, updateDelegate); if (!location.uiLocation()) return null; this._locations.push(location); location.update(); return location; }, _rawLocationToUILocation: function(rawLocation) { var sourceMapping = this._sourceMappings[rawLocation.url]; return sourceMapping ? sourceMapping.rawLocationToUILocation(rawLocation) : null; }, toggleInlineVisibility: function(nodeId) { function callback(inlineStyles) { var visibility = inlineStyles.getLiveProperty("visibility"); if (visibility) { if (visibility.value === "hidden") visibility.setText("", false, true); else visibility.setValue("hidden", false, true); } else inlineStyles.appendProperty("visibility", "hidden"); } this.getInlineStylesAsync(nodeId, callback.bind(this)); }, __proto__: WebInspector.Object.prototype } WebInspector.CSSStyleModel.LiveLocation = function(rawLocation, updateDelegate) { WebInspector.LiveLocation.call(this, rawLocation, updateDelegate); } WebInspector.CSSStyleModel.LiveLocation.prototype = { uiLocation: function() { var cssLocation = (this.rawLocation()); return WebInspector.cssModel._rawLocationToUILocation(cssLocation); }, dispose: function() { WebInspector.LiveLocation.prototype.dispose.call(this); var locations = WebInspector.cssModel._locations; if (locations) locations.remove(this); }, __proto__: WebInspector.LiveLocation.prototype } WebInspector.CSSLocation = function(url, lineNumber) { this.url = url; this.lineNumber = lineNumber; } WebInspector.CSSStyleDeclaration = function(payload) { this.id = payload.styleId; this.width = payload.width; this.height = payload.height; this.range = payload.range; this._shorthandValues = WebInspector.CSSStyleDeclaration.buildShorthandValueMap(payload.shorthandEntries); this._livePropertyMap = {}; this._allProperties = []; this.__disabledProperties = {}; var payloadPropertyCount = payload.cssProperties.length; var propertyIndex = 0; for (var i = 0; i < payloadPropertyCount; ++i) { var property = WebInspector.CSSProperty.parsePayload(this, i, payload.cssProperties[i]); this._allProperties.push(property); if (property.disabled) this.__disabledProperties[i] = property; if (!property.active && !property.styleBased) continue; var name = property.name; this[propertyIndex] = name; this._livePropertyMap[name] = property; ++propertyIndex; } this.length = propertyIndex; if ("cssText" in payload) this.cssText = payload.cssText; } WebInspector.CSSStyleDeclaration.buildShorthandValueMap = function(shorthandEntries) { var result = {}; for (var i = 0; i < shorthandEntries.length; ++i) result[shorthandEntries[i].name] = shorthandEntries[i].value; return result; } WebInspector.CSSStyleDeclaration.parsePayload = function(payload) { return new WebInspector.CSSStyleDeclaration(payload); } WebInspector.CSSStyleDeclaration.parseComputedStylePayload = function(payload) { var newPayload = ({ cssProperties: [], shorthandEntries: [], width: "", height: "" }); if (payload) newPayload.cssProperties = payload; return new WebInspector.CSSStyleDeclaration(newPayload); } WebInspector.CSSStyleDeclaration.prototype = { get allProperties() { return this._allProperties; }, getLiveProperty: function(name) { return this._livePropertyMap[name]; }, getPropertyValue: function(name) { var property = this._livePropertyMap[name]; return property ? property.value : ""; }, getPropertyPriority: function(name) { var property = this._livePropertyMap[name]; return property ? property.priority : ""; }, isPropertyImplicit: function(name) { var property = this._livePropertyMap[name]; return property ? property.implicit : ""; }, longhandProperties: function(name) { var longhands = WebInspector.CSSMetadata.cssPropertiesMetainfo.longhands(name); var result = []; for (var i = 0; longhands && i < longhands.length; ++i) { var property = this._livePropertyMap[longhands[i]]; if (property) result.push(property); } return result; }, shorthandValue: function(shorthandProperty) { return this._shorthandValues[shorthandProperty]; }, propertyAt: function(index) { return (index < this.allProperties.length) ? this.allProperties[index] : null; }, pastLastSourcePropertyIndex: function() { for (var i = this.allProperties.length - 1; i >= 0; --i) { var property = this.allProperties[i]; if (property.active || property.disabled) return i + 1; } return 0; }, newBlankProperty: function(index) { index = (typeof index === "undefined") ? this.pastLastSourcePropertyIndex() : index; return new WebInspector.CSSProperty(this, index, "", "", "", "active", true, false, ""); }, insertPropertyAt: function(index, name, value, userCallback) { function callback(error, payload) { WebInspector.cssModel._pendingCommandsMajorState.pop(); if (!userCallback) return; if (error) { console.error(error); userCallback(null); } else { userCallback(WebInspector.CSSStyleDeclaration.parsePayload(payload)); } } if (!this.id) throw "No style id"; WebInspector.cssModel._pendingCommandsMajorState.push(true); CSSAgent.setPropertyText(this.id, index, name + ": " + value + ";", false, callback.bind(this)); }, appendProperty: function(name, value, userCallback) { this.insertPropertyAt(this.allProperties.length, name, value, userCallback); } } WebInspector.CSSRule = function(payload, matchingSelectors) { this.id = payload.ruleId; if (matchingSelectors) this.matchingSelectors = matchingSelectors; this.selectors = payload.selectorList.selectors; this.selectorText = this.selectors.join(", "); this.selectorRange = payload.selectorList.range; this.sourceLine = payload.sourceLine; this.sourceURL = payload.sourceURL; if (payload.sourceURL) this._rawLocation = new WebInspector.CSSLocation(payload.sourceURL, payload.sourceLine); this.origin = payload.origin; this.style = WebInspector.CSSStyleDeclaration.parsePayload(payload.style); this.style.parentRule = this; if (payload.media) this.media = WebInspector.CSSMedia.parseMediaArrayPayload(payload.media); } WebInspector.CSSRule.parsePayload = function(payload, matchingIndices) { return new WebInspector.CSSRule(payload, matchingIndices); } WebInspector.CSSRule.prototype = { get isUserAgent() { return this.origin === "user-agent"; }, get isUser() { return this.origin === "user"; }, get isViaInspector() { return this.origin === "inspector"; }, get isRegular() { return this.origin === "regular"; } } WebInspector.CSSProperty = function(ownerStyle, index, name, value, priority, status, parsedOk, implicit, text) { this.ownerStyle = ownerStyle; this.index = index; this.name = name; this.value = value; this.priority = priority; this.status = status; this.parsedOk = parsedOk; this.implicit = implicit; this.text = text; } WebInspector.CSSProperty.parsePayload = function(ownerStyle, index, payload) { var result = new WebInspector.CSSProperty( ownerStyle, index, payload.name, payload.value, payload.priority || "", payload.status || "style", ("parsedOk" in payload) ? !!payload.parsedOk : true, !!payload.implicit, payload.text); return result; } WebInspector.CSSProperty.prototype = { get propertyText() { if (this.text !== undefined) return this.text; if (this.name === "") return ""; return this.name + ": " + this.value + (this.priority ? " !" + this.priority : "") + ";"; }, get isLive() { return this.active || this.styleBased; }, get active() { return this.status === "active"; }, get styleBased() { return this.status === "style"; }, get inactive() { return this.status === "inactive"; }, get disabled() { return this.status === "disabled"; }, setText: function(propertyText, majorChange, overwrite, userCallback) { function enabledCallback(style) { if (userCallback) userCallback(style); } function callback(error, stylePayload) { WebInspector.cssModel._pendingCommandsMajorState.pop(); if (!error) { if (majorChange) WebInspector.domAgent.markUndoableState(); this.text = propertyText; var style = WebInspector.CSSStyleDeclaration.parsePayload(stylePayload); var newProperty = style.allProperties[this.index]; if (newProperty && this.disabled && !propertyText.match(/^\s*$/)) { newProperty.setDisabled(false, enabledCallback); return; } if (userCallback) userCallback(style); } else { if (userCallback) userCallback(null); } } if (!this.ownerStyle) throw "No ownerStyle for property"; if (!this.ownerStyle.id) throw "No owner style id"; WebInspector.cssModel._pendingCommandsMajorState.push(majorChange); CSSAgent.setPropertyText(this.ownerStyle.id, this.index, propertyText, overwrite, callback.bind(this)); }, setValue: function(newValue, majorChange, overwrite, userCallback) { var text = this.name + ": " + newValue + (this.priority ? " !" + this.priority : "") + ";" this.setText(text, majorChange, overwrite, userCallback); }, setDisabled: function(disabled, userCallback) { if (!this.ownerStyle && userCallback) userCallback(null); if (disabled === this.disabled && userCallback) userCallback(this.ownerStyle); function callback(error, stylePayload) { WebInspector.cssModel._pendingCommandsMajorState.pop(); if (error) { if (userCallback) userCallback(null); return; } WebInspector.domAgent.markUndoableState(); if (userCallback) { var style = WebInspector.CSSStyleDeclaration.parsePayload(stylePayload); userCallback(style); } } if (!this.ownerStyle.id) throw "No owner style id"; WebInspector.cssModel._pendingCommandsMajorState.push(false); CSSAgent.toggleProperty(this.ownerStyle.id, this.index, disabled, callback.bind(this)); } } WebInspector.CSSMedia = function(payload) { this.text = payload.text; this.source = payload.source; this.sourceURL = payload.sourceURL || ""; this.sourceLine = typeof payload.sourceLine === "undefined" || this.source === "linkedSheet" ? -1 : payload.sourceLine; } WebInspector.CSSMedia.Source = { LINKED_SHEET: "linkedSheet", INLINE_SHEET: "inlineSheet", MEDIA_RULE: "mediaRule", IMPORT_RULE: "importRule" }; WebInspector.CSSMedia.parsePayload = function(payload) { return new WebInspector.CSSMedia(payload); } WebInspector.CSSMedia.parseMediaArrayPayload = function(payload) { var result = []; for (var i = 0; i < payload.length; ++i) result.push(WebInspector.CSSMedia.parsePayload(payload[i])); return result; } WebInspector.CSSStyleSheet = function(payload) { this.id = payload.styleSheetId; this.rules = []; this.styles = {}; for (var i = 0; i < payload.rules.length; ++i) { var rule = WebInspector.CSSRule.parsePayload(payload.rules[i]); this.rules.push(rule); if (rule.style) this.styles[rule.style.id] = rule.style; } if ("text" in payload) this._text = payload.text; } WebInspector.CSSStyleSheet.createForId = function(styleSheetId, userCallback) { function callback(error, styleSheetPayload) { if (error) userCallback(null); else userCallback(new WebInspector.CSSStyleSheet(styleSheetPayload)); } CSSAgent.getStyleSheet(styleSheetId, callback.bind(this)); } WebInspector.CSSStyleSheet.prototype = { getText: function() { return this._text; }, setText: function(newText, majorChange, userCallback) { function callback(error) { if (!error) WebInspector.domAgent.markUndoableState(); WebInspector.cssModel._pendingCommandsMajorState.pop(); if (userCallback) userCallback(error); } WebInspector.cssModel._pendingCommandsMajorState.push(majorChange); CSSAgent.setStyleSheetText(this.id, newText, callback.bind(this)); } } WebInspector.CSSStyleModelResourceBinding = function() { this._frameAndURLToStyleSheetId = {}; this._styleSheetIdToHeader = {}; WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._inspectedURLChanged, this); } WebInspector.CSSStyleModelResourceBinding.prototype = { requestStyleSheetIdForResource: function(resource, callback) { function innerCallback() { callback(this._styleSheetIdForResource(resource)); } if (this._styleSheetIdForResource(resource)) innerCallback.call(this); else this._loadStyleSheetHeaders(innerCallback.bind(this)); }, requestResourceURLForStyleSheetId: function(styleSheetId, callback) { function innerCallback() { var header = this._styleSheetIdToHeader[styleSheetId]; if (!header) { callback(null); return; } var frame = WebInspector.resourceTreeModel.frameForId(header.frameId); if (!frame) { callback(null); return; } var styleSheetURL = header.origin === "inspector" ? this._viaInspectorResourceURL(header.sourceURL) : header.sourceURL; callback(styleSheetURL); } if (this._styleSheetIdToHeader[styleSheetId]) innerCallback.call(this); else this._loadStyleSheetHeaders(innerCallback.bind(this)); }, _styleSheetIdForResource: function(resource) { return this._frameAndURLToStyleSheetId[resource.frameId + ":" + resource.url]; }, _inspectedURLChanged: function(event) { this._frameAndURLToStyleSheetId = {}; this._styleSheetIdToHeader = {}; }, _loadStyleSheetHeaders: function(callback) { function didGetAllStyleSheets(error, infos) { if (error) { callback(error); return; } for (var i = 0; i < infos.length; ++i) { var info = infos[i]; if (info.origin === "inspector") { this._getOrCreateInspectorResource(info); continue; } this._frameAndURLToStyleSheetId[info.frameId + ":" + info.sourceURL] = info.styleSheetId; this._styleSheetIdToHeader[info.styleSheetId] = info; } callback(null); } CSSAgent.getAllStyleSheets(didGetAllStyleSheets.bind(this)); }, _requestViaInspectorResource: function(styleSheetId, callback) { var header = this._styleSheetIdToHeader[styleSheetId]; if (header) { callback(this._getOrCreateInspectorResource(header)); return; } function headersLoaded() { var header = this._styleSheetIdToHeader[styleSheetId]; if (header) callback(this._getOrCreateInspectorResource(header)); else callback(null); } this._loadStyleSheetHeaders(headersLoaded.bind(this)); }, _getOrCreateInspectorResource: function(header) { var frame = WebInspector.resourceTreeModel.frameForId(header.frameId); if (!frame) return null; var viaInspectorURL = this._viaInspectorResourceURL(header.sourceURL); var inspectorResource = frame.resourceForURL(viaInspectorURL); if (inspectorResource) return inspectorResource; var resource = frame.resourceForURL(header.sourceURL); if (!resource) return null; this._frameAndURLToStyleSheetId[header.frameId + ":" + viaInspectorURL] = header.styleSheetId; this._styleSheetIdToHeader[header.styleSheetId] = header; inspectorResource = new WebInspector.Resource(null, viaInspectorURL, resource.documentURL, resource.frameId, resource.loaderId, WebInspector.resourceTypes.Stylesheet, "text/css", true); function overrideRequestContent(callback) { function callbackWrapper(error, content) { callback(error ? "" : content, false, "text/css"); } CSSAgent.getStyleSheetText(header.styleSheetId, callbackWrapper); } inspectorResource.requestContent = overrideRequestContent; frame.addResource(inspectorResource); return inspectorResource; }, _viaInspectorResourceURL: function(documentURL) { var parsedURL = new WebInspector.ParsedURL(documentURL); var fakeURL = "inspector://" + parsedURL.host + parsedURL.folderPathComponents; if (!fakeURL.endsWith("/")) fakeURL += "/"; fakeURL += "inspector-stylesheet"; return fakeURL; } } WebInspector.CSSDispatcher = function(cssModel) { this._cssModel = cssModel; } WebInspector.CSSDispatcher.prototype = { mediaQueryResultChanged: function() { this._cssModel.mediaQueryResultChanged(); }, styleSheetChanged: function(styleSheetId) { this._cssModel._fireStyleSheetChanged(styleSheetId); }, namedFlowCreated: function(namedFlowPayload) { this._cssModel._namedFlowCreated(namedFlowPayload); }, namedFlowRemoved: function(documentNodeId, flowName) { this._cssModel._namedFlowRemoved(documentNodeId, flowName); }, regionLayoutUpdated: function(namedFlowPayload) { this._cssModel._regionLayoutUpdated(namedFlowPayload); } } WebInspector.NamedFlow = function(payload) { this.documentNodeId = payload.documentNodeId; this.name = payload.name; this.overset = payload.overset; this.content = payload.content; this.regions = payload.regions; } WebInspector.NamedFlow.parsePayload = function(payload) { return new WebInspector.NamedFlow(payload); } WebInspector.NamedFlowCollection = function(payload) { this.namedFlowMap = {}; for (var i = 0; i < payload.length; ++i) { var namedFlow = WebInspector.NamedFlow.parsePayload(payload[i]); this.namedFlowMap[namedFlow.name] = namedFlow; } } WebInspector.NamedFlowCollection.prototype = { _appendNamedFlow: function(namedFlow) { this.namedFlowMap[namedFlow.name] = namedFlow; }, _removeNamedFlow: function(flowName) { delete this.namedFlowMap[flowName]; }, flowByName: function(flowName) { var namedFlow = this.namedFlowMap[flowName]; if (!namedFlow) return null; return namedFlow; } } WebInspector.cssModel = null; WebInspector.NetworkManager = function() { WebInspector.Object.call(this); this._dispatcher = new WebInspector.NetworkDispatcher(this); if (WebInspector.settings.cacheDisabled.get()) NetworkAgent.setCacheDisabled(true); NetworkAgent.enable(); WebInspector.settings.cacheDisabled.addChangeListener(this._cacheDisabledSettingChanged, this); } WebInspector.NetworkManager.EventTypes = { RequestStarted: "RequestStarted", RequestUpdated: "RequestUpdated", RequestFinished: "RequestFinished", RequestUpdateDropped: "RequestUpdateDropped" } WebInspector.NetworkManager._MIMETypes = { "text/html": {"document": true}, "text/xml": {"document": true}, "text/plain": {"document": true}, "application/xhtml+xml": {"document": true}, "text/css": {"stylesheet": true}, "text/xsl": {"stylesheet": true}, "image/jpg": {"image": true}, "image/jpeg": {"image": true}, "image/pjpeg": {"image": true}, "image/png": {"image": true}, "image/gif": {"image": true}, "image/bmp": {"image": true}, "image/svg+xml": {"image": true}, "image/vnd.microsoft.icon": {"image": true}, "image/webp": {"image": true}, "image/x-icon": {"image": true}, "image/x-xbitmap": {"image": true}, "font/ttf": {"font": true}, "font/opentype": {"font": true}, "font/woff": {"font": true}, "application/x-font-type1": {"font": true}, "application/x-font-ttf": {"font": true}, "application/x-font-woff": {"font": true}, "application/x-truetype-font": {"font": true}, "text/javascript": {"script": true}, "text/ecmascript": {"script": true}, "application/javascript": {"script": true}, "application/ecmascript": {"script": true}, "application/x-javascript": {"script": true}, "application/json": {"script": true}, "text/javascript1.1": {"script": true}, "text/javascript1.2": {"script": true}, "text/javascript1.3": {"script": true}, "text/jscript": {"script": true}, "text/livescript": {"script": true}, } WebInspector.NetworkManager.prototype = { inflightRequestForURL: function(url) { return this._dispatcher._inflightRequestsByURL[url]; }, _cacheDisabledSettingChanged: function(event) { var enabled = (event.data); NetworkAgent.setCacheDisabled(enabled); }, __proto__: WebInspector.Object.prototype } WebInspector.NetworkDispatcher = function(manager) { this._manager = manager; this._inflightRequestsById = {}; this._inflightRequestsByURL = {}; InspectorBackend.registerNetworkDispatcher(this); } WebInspector.NetworkDispatcher.prototype = { _headersMapToHeadersArray: function(headersMap) { var result = []; for (var name in headersMap) { var values = headersMap[name].split("\n"); for (var i = 0; i < values.length; ++i) result.push({ name: name, value: values[i] }); } return result; }, _updateNetworkRequestWithRequest: function(networkRequest, request) { networkRequest.requestMethod = request.method; networkRequest.requestHeaders = this._headersMapToHeadersArray(request.headers); networkRequest.requestFormData = request.postData; }, _updateNetworkRequestWithResponse: function(networkRequest, response) { if (!response) return; if (response.url && networkRequest.url !== response.url) networkRequest.url = response.url; networkRequest.mimeType = response.mimeType; networkRequest.statusCode = response.status; networkRequest.statusText = response.statusText; networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers); if (response.headersText) networkRequest.responseHeadersText = response.headersText; if (response.requestHeaders) networkRequest.requestHeaders = this._headersMapToHeadersArray(response.requestHeaders); if (response.requestHeadersText) networkRequest.requestHeadersText = response.requestHeadersText; networkRequest.connectionReused = response.connectionReused; networkRequest.connectionId = response.connectionId; if (response.fromDiskCache) networkRequest.cached = true; else networkRequest.timing = response.timing; if (!this._mimeTypeIsConsistentWithType(networkRequest)) { WebInspector.console.addMessage(WebInspector.ConsoleMessage.create(WebInspector.ConsoleMessage.MessageSource.Network, WebInspector.ConsoleMessage.MessageLevel.Warning, WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s: \"%s\".", networkRequest.type.title(), networkRequest.mimeType, networkRequest.url), WebInspector.ConsoleMessage.MessageType.Log, "", 0, 1, [], null, networkRequest.requestId)); } }, _mimeTypeIsConsistentWithType: function(networkRequest) { if (networkRequest.hasErrorStatusCode() || networkRequest.statusCode === 304 || networkRequest.statusCode === 204) return true; if (typeof networkRequest.type === "undefined" || networkRequest.type === WebInspector.resourceTypes.Other || networkRequest.type === WebInspector.resourceTypes.XHR || networkRequest.type === WebInspector.resourceTypes.WebSocket) return true; if (!networkRequest.mimeType) return true; if (networkRequest.mimeType in WebInspector.NetworkManager._MIMETypes) return networkRequest.type.name() in WebInspector.NetworkManager._MIMETypes[networkRequest.mimeType]; return false; }, _updateNetworkRequestWithCachedResource: function(networkRequest, cachedResource) { networkRequest.type = WebInspector.resourceTypes[cachedResource.type]; networkRequest.resourceSize = cachedResource.bodySize; this._updateNetworkRequestWithResponse(networkRequest, cachedResource.response); }, _isNull: function(response) { if (!response) return true; return !response.status && !response.mimeType && (!response.headers || !Object.keys(response.headers).length); }, requestWillBeSent: function(requestId, frameId, loaderId, documentURL, request, time, initiator, redirectResponse) { var networkRequest = this._inflightRequestsById[requestId]; if (networkRequest) { if (!redirectResponse) return; this.responseReceived(requestId, frameId, loaderId, time, "Other", redirectResponse); networkRequest = this._appendRedirect(requestId, time, request.url); } else networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, request.url, documentURL, initiator); networkRequest.hasNetworkData = true; this._updateNetworkRequestWithRequest(networkRequest, request); networkRequest.startTime = time; this._startNetworkRequest(networkRequest); }, requestServedFromCache: function(requestId) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.cached = true; }, responseReceived: function(requestId, frameId, loaderId, time, resourceType, response) { if (this._isNull(response)) return; var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) { var eventData = {}; eventData.url = response.url; eventData.frameId = frameId; eventData.loaderId = loaderId; eventData.resourceType = resourceType; eventData.mimeType = response.mimeType; this._manager.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdateDropped, eventData); return; } networkRequest.responseReceivedTime = time; networkRequest.type = WebInspector.resourceTypes[resourceType]; this._updateNetworkRequestWithResponse(networkRequest, response); this._updateNetworkRequest(networkRequest); }, dataReceived: function(requestId, time, dataLength, encodedDataLength) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.resourceSize += dataLength; if (encodedDataLength != -1) networkRequest.increaseTransferSize(encodedDataLength); networkRequest.endTime = time; this._updateNetworkRequest(networkRequest); }, loadingFinished: function(requestId, finishTime) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; this._finishNetworkRequest(networkRequest, finishTime); }, loadingFailed: function(requestId, time, localizedDescription, canceled) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.failed = true; networkRequest.canceled = canceled; networkRequest.localizedFailDescription = localizedDescription; this._finishNetworkRequest(networkRequest, time); }, requestServedFromMemoryCache: function(requestId, frameId, loaderId, documentURL, time, initiator, cachedResource) { var networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, cachedResource.url, documentURL, initiator); this._updateNetworkRequestWithCachedResource(networkRequest, cachedResource); networkRequest.cached = true; networkRequest.requestMethod = "GET"; this._startNetworkRequest(networkRequest); networkRequest.startTime = networkRequest.responseReceivedTime = time; this._finishNetworkRequest(networkRequest, time); }, webSocketCreated: function(requestId, requestURL) { var networkRequest = new WebInspector.NetworkRequest(requestId, requestURL, "", "", ""); networkRequest.type = WebInspector.resourceTypes.WebSocket; this._startNetworkRequest(networkRequest); }, webSocketWillSendHandshakeRequest: function(requestId, time, request) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.requestMethod = "GET"; networkRequest.requestHeaders = this._headersMapToHeadersArray(request.headers); networkRequest.webSocketRequestKey3 = request.requestKey3; networkRequest.startTime = time; this._updateNetworkRequest(networkRequest); }, webSocketHandshakeResponseReceived: function(requestId, time, response) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.statusCode = response.status; networkRequest.statusText = response.statusText; networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers); networkRequest.webSocketChallengeResponse = response.challengeResponse; networkRequest.responseReceivedTime = time; this._updateNetworkRequest(networkRequest); }, webSocketFrameReceived: function(requestId, time, response) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.addFrame(response, time); networkRequest.responseReceivedTime = time; this._updateNetworkRequest(networkRequest); }, webSocketFrameSent: function(requestId, time, response) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.addFrame(response, time, true); networkRequest.responseReceivedTime = time; this._updateNetworkRequest(networkRequest); }, webSocketFrameError: function(requestId, time, errorMessage) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.addFrameError(errorMessage, time); networkRequest.responseReceivedTime = time; this._updateNetworkRequest(networkRequest); }, webSocketClosed: function(requestId, time) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; this._finishNetworkRequest(networkRequest, time); }, _appendRedirect: function(requestId, time, redirectURL) { var originalNetworkRequest = this._inflightRequestsById[requestId]; var previousRedirects = originalNetworkRequest.redirects || []; originalNetworkRequest.requestId = "redirected:" + requestId + "." + previousRedirects.length; delete originalNetworkRequest.redirects; if (previousRedirects.length > 0) originalNetworkRequest.redirectSource = previousRedirects[previousRedirects.length - 1]; this._finishNetworkRequest(originalNetworkRequest, time); var newNetworkRequest = this._createNetworkRequest(requestId, originalNetworkRequest.frameId, originalNetworkRequest.loaderId, redirectURL, originalNetworkRequest.documentURL, originalNetworkRequest.initiator); newNetworkRequest.redirects = previousRedirects.concat(originalNetworkRequest); return newNetworkRequest; }, _startNetworkRequest: function(networkRequest) { this._inflightRequestsById[networkRequest.requestId] = networkRequest; this._inflightRequestsByURL[networkRequest.url] = networkRequest; this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestStarted, networkRequest); }, _updateNetworkRequest: function(networkRequest) { this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdated, networkRequest); }, _finishNetworkRequest: function(networkRequest, finishTime) { networkRequest.endTime = finishTime; networkRequest.finished = true; this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestFinished, networkRequest); delete this._inflightRequestsById[networkRequest.requestId]; delete this._inflightRequestsByURL[networkRequest.url]; }, _dispatchEventToListeners: function(eventType, networkRequest) { this._manager.dispatchEventToListeners(eventType, networkRequest); }, _createNetworkRequest: function(requestId, frameId, loaderId, url, documentURL, initiator) { var networkRequest = new WebInspector.NetworkRequest(requestId, url, documentURL, frameId, loaderId); networkRequest.initiator = initiator; return networkRequest; } } WebInspector.networkManager = null; WebInspector.NetworkLog = function() { this._requests = []; this._requestForId = {}; WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestStarted, this._onRequestStarted, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._onMainFrameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.OnLoad, this._onLoad, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.DOMContentLoaded, this._onDOMContentLoaded, this); } WebInspector.NetworkLog.prototype = { get requests() { return this._requests; }, requestForURL: function(url) { for (var i = 0; i < this._requests.length; ++i) { if (this._requests[i].url === url) return this._requests[i]; } return null; }, pageLoadForRequest: function(request) { return request.__page; }, _onMainFrameNavigated: function(event) { var mainFrame = event.data; this._currentPageLoad = null; var oldRequests = this._requests.splice(0, this._requests.length); for (var i = 0; i < oldRequests.length; ++i) { var request = oldRequests[i]; if (request.loaderId === mainFrame.loaderId) { if (!this._currentPageLoad) this._currentPageLoad = new WebInspector.PageLoad(request); this._requests.push(request); request.__page = this._currentPageLoad; } } }, _onRequestStarted: function(event) { var request = (event.data); this._requests.push(request); this._requestForId[request.requestId] = request; request.__page = this._currentPageLoad; }, _onDOMContentLoaded: function(event) { if (this._currentPageLoad) this._currentPageLoad.contentLoadTime = event.data; }, _onLoad: function(event) { if (this._currentPageLoad) this._currentPageLoad.loadTime = event.data; }, requestForId: function(requestId) { return this._requestForId[requestId]; } } WebInspector.networkLog = null; WebInspector.PageLoad = function(mainRequest) { this.id = ++WebInspector.PageLoad._lastIdentifier; this.url = mainRequest.url; this.startTime = mainRequest.startTime; } WebInspector.PageLoad._lastIdentifier = 0; WebInspector.ResourceTreeModel = function(networkManager) { networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestFinished, this._onRequestFinished, this); networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestUpdateDropped, this._onRequestUpdateDropped, this); WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._consoleMessageAdded, this); WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.RepeatCountUpdated, this._consoleMessageAdded, this); WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); PageAgent.enable(); NetworkAgent.enable(); this._fetchResourceTree(); InspectorBackend.registerPageDispatcher(new WebInspector.PageDispatcher(this)); this._pendingConsoleMessages = {}; } WebInspector.ResourceTreeModel.EventTypes = { FrameAdded: "FrameAdded", FrameNavigated: "FrameNavigated", FrameDetached: "FrameDetached", MainFrameNavigated: "MainFrameNavigated", ResourceAdded: "ResourceAdded", WillLoadCachedResources: "WillLoadCachedResources", CachedResourcesLoaded: "CachedResourcesLoaded", DOMContentLoaded: "DOMContentLoaded", OnLoad: "OnLoad", InspectedURLChanged: "InspectedURLChanged" } WebInspector.ResourceTreeModel.prototype = { _fetchResourceTree: function() { this._frames = {}; delete this._cachedResourcesProcessed; PageAgent.getResourceTree(this._processCachedResources.bind(this)); }, _processCachedResources: function(error, mainFramePayload) { if (error) { console.error(JSON.stringify(error)); return; } this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.WillLoadCachedResources); WebInspector.inspectedPageURL = mainFramePayload.frame.url; this._addFramesRecursively(null, mainFramePayload); this._dispatchInspectedURLChanged(); this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded); this._cachedResourcesProcessed = true; }, cachedResourcesLoaded: function() { return this._cachedResourcesProcessed; }, _dispatchInspectedURLChanged: function() { InspectorFrontendHost.inspectedURLChanged(WebInspector.inspectedPageURL); this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, WebInspector.inspectedPageURL); }, _addFrame: function(frame) { this._frames[frame.id] = frame; if (frame.isMainFrame()) this.mainFrame = frame; this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, frame); }, _frameNavigated: function(framePayload) { if (!this._cachedResourcesProcessed) return; var frame = this._frames[framePayload.id]; if (frame) { frame._navigate(framePayload); } else { var parentFrame = this._frames[framePayload.parentId]; frame = new WebInspector.ResourceTreeFrame(this, parentFrame, framePayload); if (frame.isMainFrame() && this.mainFrame) { this._frameDetached(this.mainFrame.id); } this._addFrame(frame); } if (frame.isMainFrame()) WebInspector.inspectedPageURL = frame.url; this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, frame); if (frame.isMainFrame()) this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, frame); var resources = frame.resources(); for (var i = 0; i < resources.length; ++i) this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, resources[i]); if (frame.isMainFrame()) this._dispatchInspectedURLChanged(); }, _frameDetached: function(frameId) { if (!this._cachedResourcesProcessed) return; var frame = this._frames[frameId]; if (!frame) return; if (frame.parentFrame) frame.parentFrame._removeChildFrame(frame); else frame._remove(); }, _onRequestFinished: function(event) { if (!this._cachedResourcesProcessed) return; var request = (event.data); if (request.failed || request.type === WebInspector.resourceTypes.XHR) return; var frame = this._frames[request.frameId]; if (frame) { var resource = frame._addRequest(request); this._addPendingConsoleMessagesToResource(resource); } }, _onRequestUpdateDropped: function(event) { if (!this._cachedResourcesProcessed) return; var frameId = event.data.frameId; var frame = this._frames[frameId]; if (!frame) return; var url = event.data.url; if (frame._resourcesMap[url]) return; var resource = new WebInspector.Resource(null, url, frame.url, frameId, event.data.loaderId, WebInspector.resourceTypes[event.data.resourceType], event.data.mimeType); frame.addResource(resource); }, frameForId: function(frameId) { return this._frames[frameId]; }, forAllResources: function(callback) { if (this.mainFrame) return this.mainFrame._callForFrameResources(callback); return false; }, _consoleMessageAdded: function(event) { var msg = (event.data); var resource = msg.url ? this.resourceForURL(msg.url) : null; if (resource) this._addConsoleMessageToResource(msg, resource); else this._addPendingConsoleMessage(msg); }, _addPendingConsoleMessage: function(msg) { if (!msg.url) return; if (!this._pendingConsoleMessages[msg.url]) this._pendingConsoleMessages[msg.url] = []; this._pendingConsoleMessages[msg.url].push(msg); }, _addPendingConsoleMessagesToResource: function(resource) { var messages = this._pendingConsoleMessages[resource.url]; if (messages) { for (var i = 0; i < messages.length; i++) this._addConsoleMessageToResource(messages[i], resource); delete this._pendingConsoleMessages[resource.url]; } }, _addConsoleMessageToResource: function(msg, resource) { switch (msg.level) { case WebInspector.ConsoleMessage.MessageLevel.Warning: resource.warnings += msg.repeatDelta; break; case WebInspector.ConsoleMessage.MessageLevel.Error: resource.errors += msg.repeatDelta; break; } resource.addMessage(msg); }, _consoleCleared: function() { function callback(resource) { resource.clearErrorsAndWarnings(); } this._pendingConsoleMessages = {}; this.forAllResources(callback); }, resourceForURL: function(url) { return this.mainFrame ? this.mainFrame.resourceForURL(url) : null; }, _addFramesRecursively: function(parentFrame, frameTreePayload) { var framePayload = frameTreePayload.frame; var frame = new WebInspector.ResourceTreeFrame(this, parentFrame, framePayload); this._addFrame(frame); var frameResource = this._createResourceFromFramePayload(framePayload, framePayload.url, WebInspector.resourceTypes.Document, framePayload.mimeType, framePayload.id); if (frame.isMainFrame()) WebInspector.inspectedPageURL = frameResource.url; frame.addResource(frameResource); for (var i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i) this._addFramesRecursively(frame, frameTreePayload.childFrames[i]); for (var i = 0; i < frameTreePayload.resources.length; ++i) { var subresource = frameTreePayload.resources[i]; var resource = this._createResourceFromFramePayload(framePayload, subresource.url, WebInspector.resourceTypes[subresource.type], subresource.mimeType, subresource.resourceId); frame.addResource(resource); } }, _createResourceFromFramePayload: function(frame, url, type, mimeType, resourceId) { return new WebInspector.Resource(null, url, frame.url, frame.id, frame.loaderId, type, mimeType, null, resourceId); }, __proto__: WebInspector.Object.prototype } WebInspector.ResourceTreeFrame = function(model, parentFrame, payload) { this._model = model; this._parentFrame = parentFrame; this._id = payload.id; this._loaderId = payload.loaderId; this._name = payload.name; this._url = payload.url; this._securityOrigin = payload.securityOrigin || ""; this._mimeType = payload.mimeType; this._childFrames = []; this._resourcesMap = {}; if (this._parentFrame) this._parentFrame._childFrames.push(this); } WebInspector.ResourceTreeFrame.prototype = { get id() { return this._id; }, get name() { return this._name || ""; }, get url() { return this._url; }, get securityOrigin() { return this._securityOrigin; }, get loaderId() { return this._loaderId; }, get parentFrame() { return this._parentFrame; }, get childFrames() { return this._childFrames; }, isMainFrame: function() { return !this._parentFrame; }, _navigate: function(framePayload) { this._loaderId = framePayload.loaderId; this._name = framePayload.name; this._url = framePayload.url; this._securityOrigin = framePayload.securityOrigin || ""; this._mimeType = framePayload.mimeType; var mainResource = this._resourcesMap[this._url]; this._resourcesMap = {}; this._removeChildFrames(); if (mainResource && mainResource.loaderId === this._loaderId) this.addResource(mainResource); }, get mainResource() { return this._resourcesMap[this._url]; }, _removeChildFrame: function(frame) { this._childFrames.remove(frame); frame._remove(); }, _removeChildFrames: function() { var copy = this._childFrames.slice(); for (var i = 0; i < copy.length; ++i) this._removeChildFrame(copy[i]); }, _remove: function() { this._removeChildFrames(); delete this._model._frames[this.id]; this._model.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this); }, addResource: function(resource) { if (this._resourcesMap[resource.url] === resource) { return; } this._resourcesMap[resource.url] = resource; this._model.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, resource); }, _addRequest: function(request) { var resource = this._resourcesMap[request.url]; if (resource && resource.request === request) { return resource; } resource = new WebInspector.Resource(request, request.url, request.documentURL, request.frameId, request.loaderId, request.type, request.mimeType); this._resourcesMap[resource.url] = resource; this._model.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, resource); return resource; }, resources: function() { var result = []; for (var url in this._resourcesMap) result.push(this._resourcesMap[url]); return result; }, resourceForURL: function(url) { var result; function filter(resource) { if (resource.url === url) { result = resource; return true; } } this._callForFrameResources(filter); return result; }, _callForFrameResources: function(callback) { for (var url in this._resourcesMap) { if (callback(this._resourcesMap[url])) return true; } for (var i = 0; i < this._childFrames.length; ++i) { if (this._childFrames[i]._callForFrameResources(callback)) return true; } return false; } } WebInspector.PageDispatcher = function(resourceTreeModel) { this._resourceTreeModel = resourceTreeModel; } WebInspector.PageDispatcher.prototype = { domContentEventFired: function(time) { this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.DOMContentLoaded, time); }, loadEventFired: function(time) { this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.OnLoad, time); }, frameNavigated: function(frame) { this._resourceTreeModel._frameNavigated(frame); }, frameDetached: function(frameId) { this._resourceTreeModel._frameDetached(frameId); } } WebInspector.resourceTreeModel = null; WebInspector.ParsedURL = function(url) { this.isValid = false; this.url = url; this.scheme = ""; this.host = ""; this.port = ""; this.path = ""; this.queryParams = ""; this.fragment = ""; this.folderPathComponents = ""; this.lastPathComponent = ""; var match = url.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^\/:]*)(?::([\d]+))?(?:(\/[^#]*)(?:#(.*))?)?$/i); if (match) { this.isValid = true; this.scheme = match[1].toLowerCase(); this.host = match[2]; this.port = match[3]; this.path = match[4] || "/"; this.fragment = match[5]; } else { if (this.url.startsWith("data:")) { this.scheme = "data"; return; } if (this.url === "about:blank") { this.scheme = "about"; return; } this.path = this.url; } var path = this.path; var indexOfQuery = path.indexOf("?"); if (indexOfQuery !== -1) { this.queryParams = path.substring(indexOfQuery + 1) path = path.substring(0, indexOfQuery); } var lastSlashIndex = path.lastIndexOf("/"); if (lastSlashIndex !== -1) { this.folderPathComponents = path.substring(0, lastSlashIndex); this.lastPathComponent = path.substring(lastSlashIndex + 1); } else this.lastPathComponent = path; } WebInspector.ParsedURL.completeURL = function(baseURL, href) { if (href) { var trimmedHref = href.trim(); if (trimmedHref.startsWith("data:") || trimmedHref.startsWith("blob:") || trimmedHref.startsWith("javascript:")) return href; var parsedHref = trimmedHref.asParsedURL(); if (parsedHref && parsedHref.scheme) return trimmedHref; } else return baseURL; var parsedURL = baseURL.asParsedURL(); if (parsedURL) { var path = href; if (path.charAt(0) !== "/") { var basePath = parsedURL.path; var questionMarkIndex = basePath.indexOf("?"); if (questionMarkIndex > 0) basePath = basePath.substring(0, questionMarkIndex); var prefix; if (path.charAt(0) === "?") { var basePathCutIndex = basePath.indexOf("?"); if (basePathCutIndex !== -1) prefix = basePath.substring(0, basePathCutIndex); else prefix = basePath; } else prefix = basePath.substring(0, basePath.lastIndexOf("/")) + "/"; path = prefix + path; } else if (path.length > 1 && path.charAt(1) === "/") { return parsedURL.scheme + ":" + path; } return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + path; } return null; } WebInspector.ParsedURL.prototype = { get displayName() { if (this._displayName) return this._displayName; if (this.isDataURL()) return this.dataURLDisplayName(); if (this.isAboutBlank()) return this.url; this._displayName = this.lastPathComponent; if (!this._displayName) this._displayName = this.host; if (!this._displayName && this.url) this._displayName = this.url.trimURL(WebInspector.inspectedPageDomain ? WebInspector.inspectedPageDomain : ""); if (this._displayName === "/") this._displayName = this.url; return this._displayName; }, dataURLDisplayName: function() { if (this._dataURLDisplayName) return this._dataURLDisplayName; if (!this.isDataURL()) return ""; this._dataURLDisplayName = this.url.trimEnd(20); return this._dataURLDisplayName; }, isAboutBlank: function() { return this.url === "about:blank"; }, isDataURL: function() { return this.scheme === "data"; } } String.prototype.asParsedURL = function() { var parsedURL = new WebInspector.ParsedURL(this.toString()); if (parsedURL.isValid) return parsedURL; return null; } WebInspector.resourceForURL = function(url) { return WebInspector.resourceTreeModel.resourceForURL(url); } WebInspector.forAllResources = function(callback) { WebInspector.resourceTreeModel.forAllResources(callback); } WebInspector.displayNameForURL = function(url) { if (!url) return ""; var resource = WebInspector.resourceForURL(url); if (resource) return resource.displayName; var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(url); if (uiSourceCode) return uiSourceCode.parsedURL.displayName; if (!WebInspector.inspectedPageURL) return url.trimURL(""); var parsedURL = WebInspector.inspectedPageURL.asParsedURL(); var lastPathComponent = parsedURL ? parsedURL.lastPathComponent : parsedURL; var index = WebInspector.inspectedPageURL.indexOf(lastPathComponent); if (index !== -1 && index + lastPathComponent.length === WebInspector.inspectedPageURL.length) { var baseURL = WebInspector.inspectedPageURL.substring(0, index); if (url.startsWith(baseURL)) return url.substring(index); } return parsedURL ? url.trimURL(parsedURL.host) : url; } WebInspector.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier) { var container = document.createDocumentFragment(); var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|data:|www\.)[\w$\-_+*'=\|\/\\(){}[\]^%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({^%@&#~]/; var lineColumnRegEx = /:(\d+)(:(\d+))?$/; while (string) { var linkString = linkStringRegEx.exec(string); if (!linkString) break; linkString = linkString[0]; var linkIndex = string.indexOf(linkString); var nonLink = string.substring(0, linkIndex); container.appendChild(document.createTextNode(nonLink)); var title = linkString; var realURL = (linkString.startsWith("www.") ? "http://" + linkString : linkString); var lineColumnMatch = lineColumnRegEx.exec(realURL); var lineNumber; if (lineColumnMatch) { realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length); lineNumber = parseInt(lineColumnMatch[1], 10); lineNumber = isNaN(lineNumber) ? undefined : lineNumber; } var linkNode = linkifier(title, realURL, lineNumber); container.appendChild(linkNode); string = string.substring(linkIndex + linkString.length, string.length); } if (string) container.appendChild(document.createTextNode(string)); return container; } WebInspector._linkifierPlugins = []; /** * @param {function(string):string} plugin */ WebInspector.registerLinkifierPlugin = function(plugin) { WebInspector._linkifierPlugins.push(plugin); } /** * @param {string} string * @return {DocumentFragment} */ WebInspector.linkifyStringAsFragment = function(string) { /** * @param {string} title * @param {string} url * @param {number=} lineNumber * @return {Node} */ function linkifier(title, url, lineNumber) { for (var i = 0; i < WebInspector._linkifierPlugins.length; ++i) title = WebInspector._linkifierPlugins[i](title); var isExternal = !WebInspector.resourceForURL(url); var urlNode = WebInspector.linkifyURLAsNode(url, title, undefined, isExternal); if (typeof(lineNumber) !== "undefined") { urlNode.lineNumber = lineNumber; urlNode.preferredPanel = "scripts"; } return urlNode; } return WebInspector.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier); } /** * @param {string} url * @param {string=} linkText * @param {string=} classes * @param {boolean=} isExternal * @param {string=} tooltipText * @return {!Element} */ WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, tooltipText) { if (!linkText) linkText = url; classes = (classes ? classes + " " : ""); classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link"; var a = document.createElement("a"); a.href = sanitizeHref(url); a.className = classes; if (typeof tooltipText === "undefined") a.title = url; else if (typeof tooltipText !== "string" || tooltipText.length) a.title = tooltipText; a.textContent = linkText.trimMiddle(WebInspector.Linkifier.MaxLengthForDisplayedURLs); if (isExternal) a.setAttribute("target", "_blank"); return a; } /** * @param {string} url * @param {number=} lineNumber * @return {string} */ WebInspector.formatLinkText = function(url, lineNumber) { var text = url ? WebInspector.displayNameForURL(url) : WebInspector.UIString("(program)"); if (typeof lineNumber === "number") text += ":" + (lineNumber + 1); return text; } /** * @param {string} url * @param {number=} lineNumber * @param {string=} classes * @param {string=} tooltipText * @return {Element} */ WebInspector.linkifyResourceAsNode = function(url, lineNumber, classes, tooltipText) { var linkText = WebInspector.formatLinkText(url, lineNumber); var anchor = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText); anchor.preferredPanel = "resources"; anchor.lineNumber = lineNumber; return anchor; } /** * @param {WebInspector.NetworkRequest} request * @param {string=} classes * @return {Element} */ WebInspector.linkifyRequestAsNode = function(request, classes) { var anchor = WebInspector.linkifyURLAsNode(request.url); anchor.preferredPanel = "network"; anchor.requestId = request.requestId; return anchor; } /** * @param {string} content * @param {string} mimeType * @param {boolean} contentEncoded * @return {?string} */ WebInspector.contentAsDataURL = function(content, mimeType, contentEncoded) { const maxDataUrlSize = 1024 * 1024; if (content == null || content.length > maxDataUrlSize) return null; return "data:" + mimeType + (contentEncoded ? ";base64," : ",") + content; } /* ResourceType.js */ /* * Copyright (C) 2012 Google Inc. All rights reserved. * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @param {string} name * @param {string} title * @param {string} categoryTitle * @param {string} color * @param {boolean} isTextType */ WebInspector.ResourceType = function(name, title, categoryTitle, color, isTextType) { this._name = name; this._title = title; this._categoryTitle = categoryTitle; this._color = color; this._isTextType = isTextType; } WebInspector.ResourceType.prototype = { /** * @return {string} */ name: function() { return this._name; }, /** * @return {string} */ title: function() { return this._title; }, /** * @return {string} */ categoryTitle: function() { return this._categoryTitle; }, /** * @return {string} */ color: function() { return this._color; }, /** * @return {boolean} */ isTextType: function() { return this._isTextType; }, /** * @return {string} */ toString: function() { return this._name; }, /** * @return {string} */ canonicalMimeType: function() { if (this === WebInspector.resourceTypes.Document) return "text/html"; if (this === WebInspector.resourceTypes.Script) return "text/javascript"; if (this === WebInspector.resourceTypes.Stylesheet) return "text/css"; return ""; } } /** * Keep these in sync with WebCore::InspectorPageAgent::resourceTypeJson * @enum {!WebInspector.ResourceType} */ WebInspector.resourceTypes = { Document: new WebInspector.ResourceType("document", "Document", "Documents", "rgb(47,102,236)", true), Stylesheet: new WebInspector.ResourceType("stylesheet", "Stylesheet", "Stylesheets", "rgb(157,231,119)", true), Image: new WebInspector.ResourceType("image", "Image", "Images", "rgb(164,60,255)", false), Script: new WebInspector.ResourceType("script", "Script", "Scripts", "rgb(255,121,0)", true), XHR: new WebInspector.ResourceType("xhr", "XHR", "XHR", "rgb(231,231,10)", true), Font: new WebInspector.ResourceType("font", "Font", "Fonts", "rgb(255,82,62)", false), WebSocket: new WebInspector.ResourceType("websocket", "WebSocket", "WebSockets", "rgb(186,186,186)", false), // FIXME: Decide the color. Other: new WebInspector.ResourceType("other", "Other", "Other", "rgb(186,186,186)", false) } /* TimelineManager.js */ /* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @extends {WebInspector.Object} */ WebInspector.TimelineManager = function() { WebInspector.Object.call(this); this._dispatcher = new WebInspector.TimelineDispatcher(this); this._enablementCount = 0; } WebInspector.TimelineManager.EventTypes = { TimelineStarted: "TimelineStarted", TimelineStopped: "TimelineStopped", TimelineEventRecorded: "TimelineEventRecorded" } WebInspector.TimelineManager.prototype = { /** * @param {number=} maxCallStackDepth */ start: function(maxCallStackDepth) { this._enablementCount++; if (this._enablementCount === 1) TimelineAgent.start(maxCallStackDepth, this._started.bind(this)); }, stop: function() { if (!this._enablementCount) { console.error("WebInspector.TimelineManager start/stop calls are unbalanced"); return; } this._enablementCount--; if (!this._enablementCount) TimelineAgent.stop(this._stopped.bind(this)); }, _started: function() { this.dispatchEventToListeners(WebInspector.TimelineManager.EventTypes.TimelineStarted); }, _stopped: function() { this.dispatchEventToListeners(WebInspector.TimelineManager.EventTypes.TimelineStopped); }, __proto__: WebInspector.Object.prototype } /** * @constructor * @implements {TimelineAgent.Dispatcher} */ WebInspector.TimelineDispatcher = function(manager) { this._manager = manager; InspectorBackend.registerTimelineDispatcher(this); } WebInspector.TimelineDispatcher.prototype = { eventRecorded: function(record) { this._manager.dispatchEventToListeners(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, record); } } /** * @type {WebInspector.TimelineManager} */ WebInspector.timelineManager; /* UserAgentSupport.js */ /* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor */ WebInspector.UserAgentSupport = function() { this._userAgentOverrideEnabled = false; this._deviceMetricsOverrideEnabled = false; this._geolocationPositionOverrideEnabled = false; this._deviceOrientationOverrideEnabled = false; WebInspector.settings.userAgent.addChangeListener(this._userAgentChanged, this); WebInspector.settings.deviceMetrics.addChangeListener(this._deviceMetricsChanged, this); WebInspector.settings.deviceFitWindow.addChangeListener(this._deviceMetricsChanged, this); WebInspector.settings.geolocationOverride.addChangeListener(this._geolocationPositionChanged, this); WebInspector.settings.deviceOrientationOverride.addChangeListener(this._deviceOrientationChanged, this); } /** * @constructor * @param {number} width * @param {number} height * @param {number} fontScaleFactor */ WebInspector.UserAgentSupport.DeviceMetrics = function(width, height, fontScaleFactor) { this.width = width; this.height = height; this.fontScaleFactor = fontScaleFactor; } /** * @return {WebInspector.UserAgentSupport.DeviceMetrics} */ WebInspector.UserAgentSupport.DeviceMetrics.parseSetting = function(value) { if (value) { var splitMetrics = value.split("x"); if (splitMetrics.length === 3) return new WebInspector.UserAgentSupport.DeviceMetrics(parseInt(splitMetrics[0], 10), parseInt(splitMetrics[1], 10), parseFloat(splitMetrics[2])); } return new WebInspector.UserAgentSupport.DeviceMetrics(0, 0, 1); } /** * @return {?WebInspector.UserAgentSupport.DeviceMetrics} */ WebInspector.UserAgentSupport.DeviceMetrics.parseUserInput = function(widthString, heightString, fontScaleFactorString) { function isUserInputValid(value, isInteger) { if (!value) return true; return isInteger ? /^[0]*[1-9][\d]*$/.test(value) : /^[0]*([1-9][\d]*(\.\d+)?|\.\d+)$/.test(value); } if (!widthString ^ !heightString) return null; var isWidthValid = isUserInputValid(widthString, true); var isHeightValid = isUserInputValid(heightString, true); var isFontScaleFactorValid = isUserInputValid(fontScaleFactorString, false); if (!isWidthValid && !isHeightValid && !isFontScaleFactorValid) return null; var width = isWidthValid ? parseInt(widthString || "0", 10) : -1; var height = isHeightValid ? parseInt(heightString || "0", 10) : -1; var fontScaleFactor = isFontScaleFactorValid ? parseFloat(fontScaleFactorString) : -1; return new WebInspector.UserAgentSupport.DeviceMetrics(width, height, fontScaleFactor); } WebInspector.UserAgentSupport.DeviceMetrics.prototype = { /** * @return {boolean} */ isValid: function() { return this.isWidthValid() && this.isHeightValid() && this.isFontScaleFactorValid(); }, /** * @return {boolean} */ isWidthValid: function() { return this.width >= 0; }, /** * @return {boolean} */ isHeightValid: function() { return this.height >= 0; }, /** * @return {boolean} */ isFontScaleFactorValid: function() { return this.fontScaleFactor > 0; }, /** * @return {string} */ toSetting: function() { if (!this.isValid()) return ""; return this.width && this.height ? this.width + "x" + this.height + "x" + this.fontScaleFactor : ""; }, /** * @return {string} */ widthToInput: function() { return this.isWidthValid() && this.width ? String(this.width) : ""; }, /** * @return {string} */ heightToInput: function() { return this.isHeightValid() && this.height ? String(this.height) : ""; }, /** * @return {string} */ fontScaleFactorToInput: function() { return this.isFontScaleFactorValid() && this.fontScaleFactor ? String(this.fontScaleFactor) : ""; } } /** * @constructor * @param {number} latitude * @param {number} longitude */ WebInspector.UserAgentSupport.GeolocationPosition = function(latitude, longitude, error) { this.latitude = latitude; this.longitude = longitude; this.error = error; } WebInspector.UserAgentSupport.GeolocationPosition.prototype = { /** * @return {string} */ toSetting: function() { return (typeof this.latitude === "number" && typeof this.longitude === "number" && typeof this.error === "string") ? this.latitude + "@" + this.longitude + ":" + this.error : ""; } } /** * @return {WebInspector.UserAgentSupport.GeolocationPosition} */ WebInspector.UserAgentSupport.GeolocationPosition.parseSetting = function(value) { if (value) { var splitError = value.split(":"); if (splitError.length === 2) { var splitPosition = splitError[0].split("@") if (splitPosition.length === 2) return new WebInspector.UserAgentSupport.GeolocationPosition(parseFloat(splitPosition[0]), parseFloat(splitPosition[1]), splitError[1]); } } return new WebInspector.UserAgentSupport.GeolocationPosition(0, 0, ""); } /** * @return {?WebInspector.UserAgentSupport.GeolocationPosition} */ WebInspector.UserAgentSupport.GeolocationPosition.parseUserInput = function(latitudeString, longitudeString, errorStatus) { function isUserInputValid(value) { if (!value) return true; return /^[-]?[0-9]*[.]?[0-9]*$/.test(value); } if (!latitudeString ^ !latitudeString) return null; var isLatitudeValid = isUserInputValid(latitudeString); var isLongitudeValid = isUserInputValid(longitudeString); if (!isLatitudeValid && !isLongitudeValid) return null; var latitude = isLatitudeValid ? parseFloat(latitudeString) : -1; var longitude = isLongitudeValid ? parseFloat(longitudeString) : -1; return new WebInspector.UserAgentSupport.GeolocationPosition(latitude, longitude, errorStatus ? "PositionUnavailable" : ""); } WebInspector.UserAgentSupport.GeolocationPosition.clearGeolocationOverride = function() { PageAgent.clearGeolocationOverride(); } /** * @constructor * @param {number} alpha * @param {number} beta * @param {number} gamma */ WebInspector.UserAgentSupport.DeviceOrientation = function(alpha, beta, gamma) { this.alpha = alpha; this.beta = beta; this.gamma = gamma; } WebInspector.UserAgentSupport.DeviceOrientation.prototype = { /** * @return {string} */ toSetting: function() { return JSON.stringify(this); } } /** * @return {WebInspector.UserAgentSupport.DeviceOrientation} */ WebInspector.UserAgentSupport.DeviceOrientation.parseSetting = function(value) { if (value) { var jsonObject = JSON.parse(value); return new WebInspector.UserAgentSupport.DeviceOrientation(jsonObject.alpha, jsonObject.beta, jsonObject.gamma); } return new WebInspector.UserAgentSupport.DeviceOrientation(0, 0, 0); } /** * @return {?WebInspector.UserAgentSupport.DeviceOrientation} */ WebInspector.UserAgentSupport.DeviceOrientation.parseUserInput = function(alphaString, betaString, gammaString) { function isUserInputValid(value) { if (!value) return true; return /^[-]?[0-9]*[.]?[0-9]*$/.test(value); } if (!alphaString ^ !betaString ^ !gammaString) return null; var isAlphaValid = isUserInputValid(alphaString); var isBetaValid = isUserInputValid(betaString); var isGammaValid = isUserInputValid(gammaString); if (!isAlphaValid && !isBetaValid && !isGammaValid) return null; var alpha = isAlphaValid ? parseFloat(alphaString) : -1; var beta = isBetaValid ? parseFloat(betaString) : -1; var gamma = isGammaValid ? parseFloat(gammaString) : -1; return new WebInspector.UserAgentSupport.DeviceOrientation(alpha, beta, gamma); } WebInspector.UserAgentSupport.DeviceOrientation.clearDeviceOrientationOverride = function() { PageAgent.clearDeviceOrientationOverride(); } WebInspector.UserAgentSupport.prototype = { toggleUserAgentOverride: function(enabled) { if (enabled === this._userAgentOverrideEnabled) return; this._userAgentOverrideEnabled = enabled; this._userAgentChanged(); }, toggleDeviceMetricsOverride: function(enabled) { if (enabled === this._deviceMetricsOverrideEnabled) return; this._deviceMetricsOverrideEnabled = enabled; this._deviceMetricsChanged(); }, toggleGeolocationPositionOverride: function(enabled) { if (enabled === this._geolocationPositionOverrideEnabled) return; this._geolocationPositionOverrideEnabled = enabled; this._geolocationPositionChanged(); }, toggleDeviceOrientationOverride: function(enabled) { if (enabled === this._deviceOrientationOverrideEnabled) return; this._deviceOrientationOverrideEnabled = enabled; this._deviceOrientationChanged(); }, _userAgentChanged: function() { NetworkAgent.setUserAgentOverride(this._userAgentOverrideEnabled ? WebInspector.settings.userAgent.get() : ""); }, _deviceMetricsChanged: function() { var metrics = WebInspector.UserAgentSupport.DeviceMetrics.parseSetting(this._deviceMetricsOverrideEnabled ? WebInspector.settings.deviceMetrics.get() : ""); if (metrics.isValid()) PageAgent.setDeviceMetricsOverride(metrics.width, metrics.height, metrics.fontScaleFactor, WebInspector.settings.deviceFitWindow.get()); }, _geolocationPositionChanged: function() { if (!this._geolocationPositionOverrideEnabled) { PageAgent.clearGeolocationOverride(); return; } var geolocation = WebInspector.UserAgentSupport.GeolocationPosition.parseSetting(WebInspector.settings.geolocationOverride.get()); if (geolocation.error) PageAgent.setGeolocationOverride(); else PageAgent.setGeolocationOverride(geolocation.latitude, geolocation.longitude, 150); }, _deviceOrientationChanged: function() { if (!this._deviceOrientationOverrideEnabled) { PageAgent.clearDeviceOrientationOverride(); return; } var deviceOrientation = WebInspector.UserAgentSupport.DeviceOrientation.parseSetting(WebInspector.settings.deviceOrientationOverride.get()); PageAgent.setDeviceOrientationOverride(deviceOrientation.alpha, deviceOrientation.beta, deviceOrientation.gamma); } } /** * @type {WebInspector.UserAgentSupport} */ WebInspector.userAgentSupport; /* Database.js */ /* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @param {WebInspector.DatabaseModel} model */ WebInspector.Database = function(model, id, domain, name, version) { this._model = model; this._id = id; this._domain = domain; this._name = name; this._version = version; } WebInspector.Database.prototype = { /** @return {string} */ get id() { return this._id; }, /** @return {string} */ get name() { return this._name; }, set name(x) { this._name = x; }, /** @return {string} */ get version() { return this._version; }, set version(x) { this._version = x; }, /** @return {string} */ get domain() { return this._domain; }, set domain(x) { this._domain = x; }, /** * @param {function(Array.<string>)} callback */ getTableNames: function(callback) { function sortingCallback(error, names) { if (!error) callback(names.sort()); } DatabaseAgent.getDatabaseTableNames(this._id, sortingCallback); }, /** * @param {string} query * @param {function(Array.<string>=, Array.<*>=)} onSuccess * @param {function(string)} onError */ executeSql: function(query, onSuccess, onError) { /** * @param {?Protocol.Error} error * @param {Array.<string>=} columnNames * @param {Array.<*>=} values * @param {DatabaseAgent.Error=} errorObj */ function callback(error, columnNames, values, errorObj) { if (error) { onError(error); return; } if (errorObj) { var message; if (errorObj.message) message = errorObj.message; else if (errorObj.code == 2) message = WebInspector.UIString("Database no longer has expected version."); else message = WebInspector.UIString("An unexpected error %s occurred.", errorObj.code); onError(message); return; } onSuccess(columnNames, values); } DatabaseAgent.executeSQL(this._id, query, callback.bind(this)); } } /** * @constructor * @extends {WebInspector.Object} */ WebInspector.DatabaseModel = function() { this._databases = []; InspectorBackend.registerDatabaseDispatcher(new WebInspector.DatabaseDispatcher(this)); DatabaseAgent.enable(); } WebInspector.DatabaseModel.Events = { DatabaseAdded: "DatabaseAdded" } WebInspector.DatabaseModel.prototype = { /** * @return {Array.<WebInspector.Database>} */ databases: function() { var result = []; for (var databaseId in this._databases) result.push(this._databases[databaseId]); return result; }, /** * @param {DatabaseAgent.DatabaseId} databaseId * @return {WebInspector.Database} */ databaseForId: function(databaseId) { return this._databases[databaseId]; }, /** * @param {WebInspector.Database} database */ _addDatabase: function(database) { this._databases.push(database); this.dispatchEventToListeners(WebInspector.DatabaseModel.Events.DatabaseAdded, database); }, __proto__: WebInspector.Object.prototype } /** * @constructor * @implements {DatabaseAgent.Dispatcher} * @param {WebInspector.DatabaseModel} model */ WebInspector.DatabaseDispatcher = function(model) { this._model = model; } WebInspector.DatabaseDispatcher.prototype = { /** * @param {DatabaseAgent.Database} payload */ addDatabase: function(payload) { this._model._addDatabase(new WebInspector.Database( this._model, payload.id, payload.domain, payload.name, payload.version)); } } /** * @type {WebInspector.DatabaseModel} */ WebInspector.databaseModel = null; /* DOMStorage.js */ /* * Copyright (C) 2008 Nokia Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor */ WebInspector.DOMStorage = function(id, domain, isLocalStorage) { this._id = id; this._domain = domain; this._isLocalStorage = isLocalStorage; } WebInspector.DOMStorage.prototype = { /** @return {string} */ get id() { return this._id; }, /** @return {string} */ get domain() { return this._domain; }, /** @return {boolean} */ get isLocalStorage() { return this._isLocalStorage; }, /** * @param {function(?Protocol.Error, Array.<DOMStorageAgent.Entry>):void=} callback */ getEntries: function(callback) { DOMStorageAgent.getDOMStorageEntries(this._id, callback); }, /** * @param {string} key * @param {string} value * @param {function(?Protocol.Error, boolean):void=} callback */ setItem: function(key, value, callback) { DOMStorageAgent.setDOMStorageItem(this._id, key, value, callback); }, /** * @param {string} key * @param {function(?Protocol.Error, boolean):void=} callback */ removeItem: function(key, callback) { DOMStorageAgent.removeDOMStorageItem(this._id, key, callback); } } /** * @constructor * @extends {WebInspector.Object} */ WebInspector.DOMStorageModel = function() { this._storages = {}; InspectorBackend.registerDOMStorageDispatcher(new WebInspector.DOMStorageDispatcher(this)); DOMStorageAgent.enable(); } WebInspector.DOMStorageModel.Events = { DOMStorageAdded: "DOMStorageAdded", DOMStorageUpdated: "DOMStorageUpdated" } WebInspector.DOMStorageModel.prototype = { /** * @param {WebInspector.DOMStorage} domStorage */ _addDOMStorage: function(domStorage) { this._storages[domStorage.id] = domStorage; this.dispatchEventToListeners(WebInspector.DOMStorageModel.Events.DOMStorageAdded, domStorage); }, /** * @param {DOMStorageAgent.StorageId} storageId */ _domStorageUpdated: function(storageId) { this.dispatchEventToListeners(WebInspector.DOMStorageModel.Events.DOMStorageUpdated, this._storages[storageId]); }, /** * @param {DOMStorageAgent.StorageId} storageId * @return {WebInspector.DOMStorage} */ storageForId: function(storageId) { return this._storages[storageId]; }, /** * @return {Array.<WebInspector.DOMStorage>} */ storages: function() { var result = []; for (var storageId in this._storages) result.push(this._storages[storageId]); return result; }, __proto__: WebInspector.Object.prototype } /** * @constructor * @implements {DOMStorageAgent.Dispatcher} * @param {WebInspector.DOMStorageModel} model */ WebInspector.DOMStorageDispatcher = function(model) { this._model = model; } WebInspector.DOMStorageDispatcher.prototype = { /** * @param {DOMStorageAgent.Entry} payload */ addDOMStorage: function(payload) { this._model._addDOMStorage(new WebInspector.DOMStorage( payload.id, payload.origin, payload.isLocalStorage)); }, /** * @param {string} storageId */ domStorageUpdated: function(storageId) { this._model._domStorageUpdated(storageId); } } /** * @type {WebInspector.DOMStorageModel} */ WebInspector.domStorageModel = null; /* DataGrid.js */ /* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @extends {WebInspector.View} * @param {function(WebInspector.DataGridNode, number, string, string)=} editCallback * @param {function(WebInspector.DataGridNode)=} deleteCallback */ WebInspector.DataGrid = function(columns, editCallback, deleteCallback) { WebInspector.View.call(this); this.registerRequiredCSS("dataGrid.css"); this.element.className = "data-grid"; this.element.tabIndex = 0; this.element.addEventListener("keydown", this._keyDown.bind(this), false); this._headerTable = document.createElement("table"); this._headerTable.className = "header"; this._headerTableHeaders = {}; this._dataTable = document.createElement("table"); this._dataTable.className = "data"; this._dataTable.addEventListener("mousedown", this._mouseDownInDataTable.bind(this), true); this._dataTable.addEventListener("click", this._clickInDataTable.bind(this), true); this._dataTable.addEventListener("contextmenu", this._contextMenuInDataTable.bind(this), true); // FIXME: Add a createCallback which is different from editCallback and has different // behavior when creating a new node. if (editCallback) { this._dataTable.addEventListener("dblclick", this._ondblclick.bind(this), false); this._editCallback = editCallback; } if (deleteCallback) this._deleteCallback = deleteCallback; this.aligned = {}; this._scrollContainer = document.createElement("div"); this._scrollContainer.className = "data-container"; this._scrollContainer.appendChild(this._dataTable); this.element.appendChild(this._headerTable); this.element.appendChild(this._scrollContainer); var headerRow = document.createElement("tr"); var columnGroup = document.createElement("colgroup"); this._columnCount = 0; for (var columnIdentifier in columns) { var column = columns[columnIdentifier]; if (column.disclosure) this.disclosureColumnIdentifier = columnIdentifier; var col = document.createElement("col"); if (column.width) col.style.width = column.width; column.element = col; columnGroup.appendChild(col); var cell = document.createElement("th"); cell.className = columnIdentifier + "-column"; cell.columnIdentifier = columnIdentifier; this._headerTableHeaders[columnIdentifier] = cell; var div = document.createElement("div"); if (column.titleDOMFragment) div.appendChild(column.titleDOMFragment); else div.textContent = column.title; cell.appendChild(div); if (column.sort) { cell.addStyleClass("sort-" + column.sort); this._sortColumnCell = cell; } if (column.sortable) { cell.addEventListener("click", this._clickInHeaderCell.bind(this), false); cell.addStyleClass("sortable"); } if (column.aligned) this.aligned[columnIdentifier] = column.aligned; headerRow.appendChild(cell); ++this._columnCount; } columnGroup.span = this._columnCount; var cell = document.createElement("th"); cell.className = "corner"; headerRow.appendChild(cell); this._headerTableColumnGroup = columnGroup; this._headerTable.appendChild(this._headerTableColumnGroup); this.headerTableBody.appendChild(headerRow); var fillerRow = document.createElement("tr"); fillerRow.className = "filler"; for (var columnIdentifier in columns) { var column = columns[columnIdentifier]; var td = document.createElement("td"); td.className = columnIdentifier + "-column"; fillerRow.appendChild(td); } this._dataTableColumnGroup = columnGroup.cloneNode(true); this._dataTable.appendChild(this._dataTableColumnGroup); this.dataTableBody.appendChild(fillerRow); this.columns = columns || {}; this._columnsArray = []; for (var columnIdentifier in columns) { columns[columnIdentifier].ordinal = this._columnsArray.length; columns[columnIdentifier].identifier = columnIdentifier; this._columnsArray.push(columns[columnIdentifier]); } for (var i = 0; i < this._columnsArray.length; ++i) this._columnsArray[i].bodyElement = this._dataTableColumnGroup.children[i]; this.selectedNode = null; this.expandNodesWhenArrowing = false; this.setRootNode(new WebInspector.DataGridNode()); this.indentWidth = 15; this.resizers = []; this._columnWidthsInitialized = false; } WebInspector.DataGrid.Events = { SelectedNode: "SelectedNode", DeselectedNode: "DeselectedNode" } /** * @param {Array.<string>} columnNames * @param {Array.<string>} values */ WebInspector.DataGrid.createSortableDataGrid = function(columnNames, values) { var numColumns = columnNames.length; if (!numColumns) return null; var columns = {}; for (var i = 0; i < columnNames.length; ++i) { var column = {}; column.width = columnNames[i].length; column.title = columnNames[i]; column.sortable = true; columns[columnNames[i]] = column; } var nodes = []; for (var i = 0; i < values.length / numColumns; ++i) { var data = {}; for (var j = 0; j < columnNames.length; ++j) data[columnNames[j]] = values[numColumns * i + j]; var node = new WebInspector.DataGridNode(data, false); node.selectable = false; nodes.push(node); } var dataGrid = new WebInspector.DataGrid(columns); var length = nodes.length; for (var i = 0; i < length; ++i) dataGrid.rootNode().appendChild(nodes[i]); dataGrid.addEventListener("sorting changed", sortDataGrid, this); function sortDataGrid() { var nodes = dataGrid._rootNode.children.slice(); var sortColumnIdentifier = dataGrid.sortColumnIdentifier; var sortDirection = dataGrid.sortOrder === "ascending" ? 1 : -1; var columnIsNumeric = true; for (var i = 0; i < nodes.length; i++) { if (isNaN(Number(nodes[i].data[sortColumnIdentifier]))) columnIsNumeric = false; } function comparator(dataGridNode1, dataGridNode2) { var item1 = dataGridNode1.data[sortColumnIdentifier]; var item2 = dataGridNode2.data[sortColumnIdentifier]; var comparison; if (columnIsNumeric) { // Sort numbers based on comparing their values rather than a lexicographical comparison. var number1 = parseFloat(item1); var number2 = parseFloat(item2); comparison = number1 < number2 ? -1 : (number1 > number2 ? 1 : 0); } else comparison = item1 < item2 ? -1 : (item1 > item2 ? 1 : 0); return sortDirection * comparison; } nodes.sort(comparator); dataGrid.rootNode().removeChildren(); for (var i = 0; i < nodes.length; i++) dataGrid._rootNode.appendChild(nodes[i]); } return dataGrid; } WebInspector.DataGrid.prototype = { setRootNode: function(rootNode) { if (this._rootNode) { this._rootNode.removeChildren(); this._rootNode.dataGrid = null; this._rootNode._isRoot = false; } this._rootNode = rootNode; rootNode._isRoot = true; rootNode.hasChildren = false; rootNode._expanded = true; rootNode._revealed = true; rootNode.dataGrid = this; }, rootNode: function() { return this._rootNode; }, get refreshCallback() { return this._refreshCallback; }, set refreshCallback(refreshCallback) { this._refreshCallback = refreshCallback; }, _ondblclick: function(event) { if (this._editing || this._editingNode) return; this._startEditing(event.target); }, _startEditingColumnOfDataGridNode: function(node, column) { this._editing = true; this._editingNode = node; this._editingNode.select(); var element = this._editingNode._element.children[column]; WebInspector.startEditing(element, this._startEditingConfig(element)); window.getSelection().setBaseAndExtent(element, 0, element, 1); }, _startEditing: function(target) { var element = target.enclosingNodeOrSelfWithNodeName("td"); if (!element) return; this._editingNode = this.dataGridNodeFromNode(target); if (!this._editingNode) { if (!this.creationNode) return; this._editingNode = this.creationNode; } // Force editing the 1st column when editing the creation node if (this._editingNode.isCreationNode) return this._startEditingColumnOfDataGridNode(this._editingNode, 0); this._editing = true; WebInspector.startEditing(element, this._startEditingConfig(element)); window.getSelection().setBaseAndExtent(element, 0, element, 1); }, _startEditingConfig: function(element) { return new WebInspector.EditingConfig(this._editingCommitted.bind(this), this._editingCancelled.bind(this), element.textContent); }, _editingCommitted: function(element, newText, oldText, context, moveDirection) { // FIXME: We need more column identifiers here throughout this function. // Not needed yet since only editable DataGrid is DOM Storage, which is Key - Value. // FIXME: Better way to do this than regular expressions? var columnIdentifier = parseInt(element.className.match(/\b(\d+)-column\b/)[1], 10); var textBeforeEditing = this._editingNode.data[columnIdentifier]; var currentEditingNode = this._editingNode; function moveToNextIfNeeded(wasChange) { if (!moveDirection) return; if (moveDirection === "forward") { if (currentEditingNode.isCreationNode && columnIdentifier === 0 && !wasChange) return; if (columnIdentifier === 0) return this._startEditingColumnOfDataGridNode(currentEditingNode, 1); var nextDataGridNode = currentEditingNode.traverseNextNode(true, null, true); if (nextDataGridNode) return this._startEditingColumnOfDataGridNode(nextDataGridNode, 0); if (currentEditingNode.isCreationNode && wasChange) { this.addCreationNode(false); return this._startEditingColumnOfDataGridNode(this.creationNode, 0); } return; } if (moveDirection === "backward") { if (columnIdentifier === 1) return this._startEditingColumnOfDataGridNode(currentEditingNode, 0); var nextDataGridNode = currentEditingNode.traversePreviousNode(true, null, true); if (nextDataGridNode) return this._startEditingColumnOfDataGridNode(nextDataGridNode, 1); return; } } if (textBeforeEditing == newText) { this._editingCancelled(element); moveToNextIfNeeded.call(this, false); return; } // Update the text in the datagrid that we typed this._editingNode.data[columnIdentifier] = newText; // Make the callback - expects an editing node (table row), the column number that is being edited, // the text that used to be there, and the new text. this._editCallback(this._editingNode, columnIdentifier, textBeforeEditing, newText); if (this._editingNode.isCreationNode) this.addCreationNode(false); this._editingCancelled(element); moveToNextIfNeeded.call(this, true); }, _editingCancelled: function(element) { delete this._editing; this._editingNode = null; }, /** * @return {?string} */ get sortColumnIdentifier() { if (!this._sortColumnCell) return null; return this._sortColumnCell.columnIdentifier; }, /** * @return {?string} */ get sortOrder() { if (!this._sortColumnCell || this._sortColumnCell.hasStyleClass("sort-ascending")) return "ascending"; if (this._sortColumnCell.hasStyleClass("sort-descending")) return "descending"; return null; }, get headerTableBody() { if ("_headerTableBody" in this) return this._headerTableBody; this._headerTableBody = this._headerTable.getElementsByTagName("tbody")[0]; if (!this._headerTableBody) { this._headerTableBody = this.element.ownerDocument.createElement("tbody"); this._headerTable.insertBefore(this._headerTableBody, this._headerTable.tFoot); } return this._headerTableBody; }, get dataTableBody() { if ("_dataTableBody" in this) return this._dataTableBody; this._dataTableBody = this._dataTable.getElementsByTagName("tbody")[0]; if (!this._dataTableBody) { this._dataTableBody = this.element.ownerDocument.createElement("tbody"); this._dataTable.insertBefore(this._dataTableBody, this._dataTable.tFoot); } return this._dataTableBody; }, /** * @param {Array.<number>} widths * @param {number} minPercent * @param {number=} maxPercent */ _autoSizeWidths: function(widths, minPercent, maxPercent) { if (minPercent) minPercent = Math.min(minPercent, Math.floor(100 / widths.length)); var totalWidth = 0; for (var i = 0; i < widths.length; ++i) totalWidth += widths[i]; var totalPercentWidth = 0; for (var i = 0; i < widths.length; ++i) { var width = Math.round(100 * widths[i] / totalWidth); if (minPercent && width < minPercent) width = minPercent; else if (maxPercent && width > maxPercent) width = maxPercent; totalPercentWidth += width; widths[i] = width; } var recoupPercent = totalPercentWidth - 100; while (minPercent && recoupPercent > 0) { for (var i = 0; i < widths.length; ++i) { if (widths[i] > minPercent) { --widths[i]; --recoupPercent; if (!recoupPercent) break; } } } while (maxPercent && recoupPercent < 0) { for (var i = 0; i < widths.length; ++i) { if (widths[i] < maxPercent) { ++widths[i]; ++recoupPercent; if (!recoupPercent) break; } } } return widths; }, /** * @param {number} minPercent * @param {number=} maxPercent * @param {number=} maxDescentLevel */ autoSizeColumns: function(minPercent, maxPercent, maxDescentLevel) { var widths = []; var columnIdentifiers = Object.keys(this.columns); for (var i = 0; i < columnIdentifiers.length; ++i) widths[i] = (this.columns[columnIdentifiers[i]].title || "").length; maxDescentLevel = maxDescentLevel || 0; var children = this._enumerateChildren(this._rootNode, [], maxDescentLevel + 1); for (var i = 0; i < children.length; ++i) { var node = children[i]; for (var j = 0; j < columnIdentifiers.length; ++j) { var text = node.data[columnIdentifiers[j]] || ""; if (text.length > widths[j]) widths[j] = text.length; } } widths = this._autoSizeWidths(widths, minPercent, maxPercent); for (var i = 0; i < columnIdentifiers.length; ++i) this.columns[columnIdentifiers[i]].element.style.width = widths[i] + "%"; this._columnWidthsInitialized = false; this.updateWidths(); }, _enumerateChildren: function(rootNode, result, maxLevel) { if (!rootNode._isRoot) result.push(rootNode); if (!maxLevel) return; for (var i = 0; i < rootNode.children.length; ++i) this._enumerateChildren(rootNode.children[i], result, maxLevel - 1); return result; }, onResize: function() { this.updateWidths(); }, // Updates the widths of the table, including the positions of the column // resizers. // // IMPORTANT: This function MUST be called once after the element of the // DataGrid is attached to its parent element and every subsequent time the // width of the parent element is changed in order to make it possible to // resize the columns. // // If this function is not called after the DataGrid is attached to its // parent element, then the DataGrid's columns will not be resizable. updateWidths: function() { var headerTableColumns = this._headerTableColumnGroup.children; var tableWidth = this._dataTable.offsetWidth; var numColumns = headerTableColumns.length; if (!this._columnWidthsInitialized && this.element.offsetWidth) { for (var i = 0; i < numColumns; i++) { var columnWidth = this.headerTableBody.rows[0].cells[i].offsetWidth; var percentWidth = ((columnWidth / tableWidth) * 100) + "%"; this._headerTableColumnGroup.children[i].style.width = percentWidth; this._dataTableColumnGroup.children[i].style.width = percentWidth; } this._columnWidthsInitialized = true; } this._positionResizers(); this.dispatchEventToListeners("width changed"); }, columnWidthsMap: function() { var result = {}; for (var i = 0; i < this._columnsArray.length; ++i) { var width = this._headerTableColumnGroup.children[i].style.width; result[this._columnsArray[i].columnIdentifier] = parseFloat(width); } return result; }, applyColumnWidthsMap: function(columnWidthsMap) { for (var columnIdentifier in this.columns) { var column = this.columns[columnIdentifier]; var width = (columnWidthsMap[columnIdentifier] || 0) + "%"; this._headerTableColumnGroup.children[column.ordinal].style.width = width; this._dataTableColumnGroup.children[column.ordinal].style.width = width; } delete this._columnWidthsInitialized; this.updateWidths(); }, isColumnVisible: function(columnIdentifier) { var column = this.columns[columnIdentifier]; var columnElement = column.element; return !columnElement.hidden; }, showColumn: function(columnIdentifier) { var column = this.columns[columnIdentifier]; var columnElement = column.element; if (!columnElement.hidden) return; columnElement.hidden = false; columnElement.removeStyleClass("hidden"); var columnBodyElement = column.bodyElement; columnBodyElement.hidden = false; columnBodyElement.removeStyleClass("hidden"); }, hideColumn: function(columnIdentifier) { var column = this.columns[columnIdentifier]; var columnElement = column.element; if (columnElement.hidden) return; var oldWidth = parseFloat(columnElement.style.width); columnElement.hidden = true; columnElement.addStyleClass("hidden"); columnElement.style.width = 0; var columnBodyElement = column.bodyElement; columnBodyElement.hidden = true; columnBodyElement.addStyleClass("hidden"); columnBodyElement.style.width = 0; this._columnWidthsInitialized = false; }, get scrollContainer() { return this._scrollContainer; }, isScrolledToLastRow: function() { return this._scrollContainer.isScrolledToBottom(); }, scrollToLastRow: function() { this._scrollContainer.scrollTop = this._scrollContainer.scrollHeight - this._scrollContainer.offsetHeight; }, _positionResizers: function() { var headerTableColumns = this._headerTableColumnGroup.children; var numColumns = headerTableColumns.length; var left = 0; var previousResizer = null; for (var i = 0; i < numColumns - 1; i++) { var resizer = this.resizers[i]; if (!resizer) { resizer = document.createElement("div"); resizer.addStyleClass("data-grid-resizer"); WebInspector.installDragHandle(resizer, this._startResizerDragging.bind(this), this._resizerDragging.bind(this), this._endResizerDragging.bind(this), "col-resize"); this.element.appendChild(resizer); this.resizers[i] = resizer; } left += this.headerTableBody.rows[0].cells[i].offsetWidth; var columnIsVisible = !this._headerTableColumnGroup.children[i].hidden; if (columnIsVisible) { resizer.style.removeProperty("display"); resizer.style.left = left + "px"; resizer.leftNeighboringColumnID = i; if (previousResizer) previousResizer.rightNeighboringColumnID = i; previousResizer = resizer; } else { resizer.style.setProperty("display", "none"); resizer.leftNeighboringColumnID = 0; resizer.rightNeighboringColumnID = 0; } } if (previousResizer) previousResizer.rightNeighboringColumnID = numColumns - 1; }, addCreationNode: function(hasChildren) { if (this.creationNode) this.creationNode.makeNormal(); var emptyData = {}; for (var column in this.columns) emptyData[column] = ''; this.creationNode = new WebInspector.CreationDataGridNode(emptyData, hasChildren); this.rootNode().appendChild(this.creationNode); }, sortNodes: function(comparator, reverseMode) { function comparatorWrapper(a, b) { if (a._dataGridNode._data.summaryRow) return 1; if (b._dataGridNode._data.summaryRow) return -1; var aDataGirdNode = a._dataGridNode; var bDataGirdNode = b._dataGridNode; return reverseMode ? comparator(bDataGirdNode, aDataGirdNode) : comparator(aDataGirdNode, bDataGirdNode); } var tbody = this.dataTableBody; var tbodyParent = tbody.parentElement; tbodyParent.removeChild(tbody); var childNodes = tbody.childNodes; var fillerRow = childNodes[childNodes.length - 1]; var sortedRows = Array.prototype.slice.call(childNodes, 0, childNodes.length - 1); sortedRows.sort(comparatorWrapper); var sortedRowsLength = sortedRows.length; tbody.removeChildren(); var previousSiblingNode = null; for (var i = 0; i < sortedRowsLength; ++i) { var row = sortedRows[i]; var node = row._dataGridNode; node.previousSibling = previousSiblingNode; if (previousSiblingNode) previousSiblingNode.nextSibling = node; tbody.appendChild(row); previousSiblingNode = node; } if (previousSiblingNode) previousSiblingNode.nextSibling = null; tbody.appendChild(fillerRow); tbodyParent.appendChild(tbody); }, _keyDown: function(event) { if (!this.selectedNode || event.shiftKey || event.metaKey || event.ctrlKey || this._editing) return; var handled = false; var nextSelectedNode; if (event.keyIdentifier === "Up" && !event.altKey) { nextSelectedNode = this.selectedNode.traversePreviousNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) nextSelectedNode = nextSelectedNode.traversePreviousNode(true); handled = nextSelectedNode ? true : false; } else if (event.keyIdentifier === "Down" && !event.altKey) { nextSelectedNode = this.selectedNode.traverseNextNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) nextSelectedNode = nextSelectedNode.traverseNextNode(true); handled = nextSelectedNode ? true : false; } else if (event.keyIdentifier === "Left") { if (this.selectedNode.expanded) { if (event.altKey) this.selectedNode.collapseRecursively(); else this.selectedNode.collapse(); handled = true; } else if (this.selectedNode.parent && !this.selectedNode.parent._isRoot) { handled = true; if (this.selectedNode.parent.selectable) { nextSelectedNode = this.selectedNode.parent; handled = nextSelectedNode ? true : false; } else if (this.selectedNode.parent) this.selectedNode.parent.collapse(); } } else if (event.keyIdentifier === "Right") { if (!this.selectedNode.revealed) { this.selectedNode.reveal(); handled = true; } else if (this.selectedNode.hasChildren) { handled = true; if (this.selectedNode.expanded) { nextSelectedNode = this.selectedNode.children[0]; handled = nextSelectedNode ? true : false; } else { if (event.altKey) this.selectedNode.expandRecursively(); else this.selectedNode.expand(); } } } else if (event.keyCode === 8 || event.keyCode === 46) { if (this._deleteCallback) { handled = true; this._deleteCallback(this.selectedNode); } } else if (isEnterKey(event)) { if (this._editCallback) { handled = true; this._startEditing(this.selectedNode._element.children[0]); } } if (nextSelectedNode) { nextSelectedNode.reveal(); nextSelectedNode.select(); } if (handled) event.consume(true); }, dataGridNodeFromNode: function(target) { var rowElement = target.enclosingNodeOrSelfWithNodeName("tr"); return rowElement && rowElement._dataGridNode; }, dataGridNodeFromPoint: function(x, y) { var node = this._dataTable.ownerDocument.elementFromPoint(x, y); var rowElement = node.enclosingNodeOrSelfWithNodeName("tr"); return rowElement && rowElement._dataGridNode; }, _clickInHeaderCell: function(event) { var cell = event.target.enclosingNodeOrSelfWithNodeName("th"); if (!cell || !cell.columnIdentifier || !cell.hasStyleClass("sortable")) return; var sortOrder = this.sortOrder; if (this._sortColumnCell) this._sortColumnCell.removeMatchingStyleClasses("sort-\\w+"); if (cell == this._sortColumnCell) { if (sortOrder === "ascending") sortOrder = "descending"; else sortOrder = "ascending"; } this._sortColumnCell = cell; cell.addStyleClass("sort-" + sortOrder); this.dispatchEventToListeners("sorting changed"); }, markColumnAsSortedBy: function(columnIdentifier, sortOrder) { if (this._sortColumnCell) this._sortColumnCell.removeMatchingStyleClasses("sort-\\w+"); this._sortColumnCell = this._headerTableHeaders[columnIdentifier]; this._sortColumnCell.addStyleClass("sort-" + sortOrder); }, headerTableHeader: function(columnIdentifier) { return this._headerTableHeaders[columnIdentifier]; }, _mouseDownInDataTable: function(event) { var gridNode = this.dataGridNodeFromNode(event.target); if (!gridNode || !gridNode.selectable) return; if (gridNode.isEventWithinDisclosureTriangle(event)) return; if (event.metaKey) { if (gridNode.selected) gridNode.deselect(); else gridNode.select(); } else gridNode.select(); }, _contextMenuInDataTable: function(event) { var contextMenu = new WebInspector.ContextMenu(event); var gridNode = this.dataGridNodeFromNode(event.target); if (this._refreshCallback && (!gridNode || gridNode !== this.creationNode)) contextMenu.appendItem(WebInspector.UIString("Refresh"), this._refreshCallback.bind(this)); if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) { if (this._editCallback) { if (gridNode === this.creationNode) contextMenu.appendItem(WebInspector.UIString("Add New"), this._startEditing.bind(this, event.target)); else contextMenu.appendItem(WebInspector.UIString("Edit"), this._startEditing.bind(this, event.target)); } if (this._deleteCallback && gridNode !== this.creationNode) contextMenu.appendItem(WebInspector.UIString("Delete"), this._deleteCallback.bind(this, gridNode)); } contextMenu.show(); }, _clickInDataTable: function(event) { var gridNode = this.dataGridNodeFromNode(event.target); if (!gridNode || !gridNode.hasChildren) return; if (!gridNode.isEventWithinDisclosureTriangle(event)) return; if (gridNode.expanded) { if (event.altKey) gridNode.collapseRecursively(); else gridNode.collapse(); } else { if (event.altKey) gridNode.expandRecursively(); else gridNode.expand(); } }, get resizeMethod() { if (typeof this._resizeMethod === "undefined") return WebInspector.DataGrid.ResizeMethod.Nearest; return this._resizeMethod; }, set resizeMethod(method) { this._resizeMethod = method; }, _startResizerDragging: function(event) { this._currentResizer = event.target; return !!this._currentResizer.rightNeighboringColumnID }, _resizerDragging: function(event) { var resizer = this._currentResizer; if (!resizer) return; var dragPoint = event.clientX - this.element.totalOffsetLeft(); var leftCellIndex = resizer.leftNeighboringColumnID; var rightCellIndex = resizer.rightNeighboringColumnID; var firstRowCells = this.headerTableBody.rows[0].cells; var leftEdgeOfPreviousColumn = 0; for (var i = 0; i < leftCellIndex; i++) leftEdgeOfPreviousColumn += firstRowCells[i].offsetWidth; if (this.resizeMethod == WebInspector.DataGrid.ResizeMethod.Last) { rightCellIndex = this.resizers.length; } else if (this.resizeMethod == WebInspector.DataGrid.ResizeMethod.First) { leftEdgeOfPreviousColumn += firstRowCells[leftCellIndex].offsetWidth - firstRowCells[0].offsetWidth; leftCellIndex = 0; } var rightEdgeOfNextColumn = leftEdgeOfPreviousColumn + firstRowCells[leftCellIndex].offsetWidth + firstRowCells[rightCellIndex].offsetWidth; var leftMinimum = leftEdgeOfPreviousColumn + this.ColumnResizePadding; var rightMaximum = rightEdgeOfNextColumn - this.ColumnResizePadding; dragPoint = Number.constrain(dragPoint, leftMinimum, rightMaximum); resizer.style.left = (dragPoint - this.CenterResizerOverBorderAdjustment) + "px"; var percentLeftColumn = (((dragPoint - leftEdgeOfPreviousColumn) / this._dataTable.offsetWidth) * 100) + "%"; this._headerTableColumnGroup.children[leftCellIndex].style.width = percentLeftColumn; this._dataTableColumnGroup.children[leftCellIndex].style.width = percentLeftColumn; var percentRightColumn = (((rightEdgeOfNextColumn - dragPoint) / this._dataTable.offsetWidth) * 100) + "%"; this._headerTableColumnGroup.children[rightCellIndex].style.width = percentRightColumn; this._dataTableColumnGroup.children[rightCellIndex].style.width = percentRightColumn; this._positionResizers(); event.preventDefault(); this.dispatchEventToListeners("width changed"); }, _endResizerDragging: function(event) { this._currentResizer = null; this.dispatchEventToListeners("width changed"); }, ColumnResizePadding: 10, CenterResizerOverBorderAdjustment: 3, __proto__: WebInspector.View.prototype } WebInspector.DataGrid.ResizeMethod = { Nearest: "nearest", First: "first", Last: "last" } WebInspector.DataGridNode = function(data, hasChildren) { this._expanded = false; this._selected = false; this._shouldRefreshChildren = true; this._data = data || {}; this.hasChildren = hasChildren || false; this.children = []; this.dataGrid = null; this.parent = null; this.previousSibling = null; this.nextSibling = null; this.disclosureToggleWidth = 10; } WebInspector.DataGridNode.prototype = { selectable: true, _isRoot: false, get element() { if (this._element) return this._element; if (!this.dataGrid) return null; this._element = document.createElement("tr"); this._element._dataGridNode = this; if (this.hasChildren) this._element.addStyleClass("parent"); if (this.expanded) this._element.addStyleClass("expanded"); if (this.selected) this._element.addStyleClass("selected"); if (this.revealed) this._element.addStyleClass("revealed"); this.createCells(); return this._element; }, createCells: function() { for (var columnIdentifier in this.dataGrid.columns) { var cell = this.createCell(columnIdentifier); this._element.appendChild(cell); } }, get data() { return this._data; }, set data(x) { this._data = x || {}; this.refresh(); }, get revealed() { if ("_revealed" in this) return this._revealed; var currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { if (!currentAncestor.expanded) { this._revealed = false; return false; } currentAncestor = currentAncestor.parent; } this._revealed = true; return true; }, set hasChildren(x) { if (this._hasChildren === x) return; this._hasChildren = x; if (!this._element) return; if (this._hasChildren) { this._element.addStyleClass("parent"); if (this.expanded) this._element.addStyleClass("expanded"); } else { this._element.removeStyleClass("parent"); this._element.removeStyleClass("expanded"); } }, get hasChildren() { return this._hasChildren; }, set revealed(x) { if (this._revealed === x) return; this._revealed = x; if (this._element) { if (this._revealed) this._element.addStyleClass("revealed"); else this._element.removeStyleClass("revealed"); } for (var i = 0; i < this.children.length; ++i) this.children[i].revealed = x && this.expanded; }, get depth() { if ("_depth" in this) return this._depth; if (this.parent && !this.parent._isRoot) this._depth = this.parent.depth + 1; else this._depth = 0; return this._depth; }, get leftPadding() { if (typeof(this._leftPadding) === "number") return this._leftPadding; this._leftPadding = this.depth * this.dataGrid.indentWidth; return this._leftPadding; }, get shouldRefreshChildren() { return this._shouldRefreshChildren; }, set shouldRefreshChildren(x) { this._shouldRefreshChildren = x; if (x && this.expanded) this.expand(); }, get selected() { return this._selected; }, set selected(x) { if (x) this.select(); else this.deselect(); }, get expanded() { return this._expanded; }, set expanded(x) { if (x) this.expand(); else this.collapse(); }, refresh: function() { if (!this._element || !this.dataGrid) return; this._element.removeChildren(); this.createCells(); }, createCell: function(columnIdentifier) { var cell = document.createElement("td"); cell.className = columnIdentifier + "-column"; var alignment = this.dataGrid.aligned[columnIdentifier]; if (alignment) cell.addStyleClass(alignment); var data = this.data[columnIdentifier]; var div = document.createElement("div"); if (data instanceof Node) div.appendChild(data); else div.textContent = data; cell.appendChild(div); if (columnIdentifier === this.dataGrid.disclosureColumnIdentifier) { cell.addStyleClass("disclosure"); if (this.leftPadding) cell.style.setProperty("padding-left", this.leftPadding + "px"); } return cell; }, nodeHeight: function() { var rowHeight = 16; if (!this.revealed) return 0; if (!this.expanded) return rowHeight; var result = rowHeight; for (var i = 0; i < this.children.length; i++) result += this.children[i].nodeHeight(); return result; }, appendChild: function(child) { this.insertChild(child, this.children.length); }, insertChild: function(child, index) { if (!child) throw("insertChild: Node can't be undefined or null."); if (child.parent === this) throw("insertChild: Node is already a child of this node."); if (child.parent) child.parent.removeChild(child); this.children.splice(index, 0, child); this.hasChildren = true; child.parent = this; child.dataGrid = this.dataGrid; child._recalculateSiblings(index); delete child._depth; delete child._revealed; delete child._attached; child._shouldRefreshChildren = true; var current = child.children[0]; while (current) { current.dataGrid = this.dataGrid; delete current._depth; delete current._revealed; delete current._attached; current._shouldRefreshChildren = true; current = current.traverseNextNode(false, child, true); } if (this.expanded) child._attach(); if (!this.revealed) child.revealed = false; }, removeChild: function(child) { if (!child) throw("removeChild: Node can't be undefined or null."); if (child.parent !== this) throw("removeChild: Node is not a child of this node."); child.deselect(); child._detach(); this.children.remove(child, true); if (child.previousSibling) child.previousSibling.nextSibling = child.nextSibling; if (child.nextSibling) child.nextSibling.previousSibling = child.previousSibling; child.dataGrid = null; child.parent = null; child.nextSibling = null; child.previousSibling = null; if (this.children.length <= 0) this.hasChildren = false; }, removeChildren: function() { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; child.deselect(); child._detach(); child.dataGrid = null; child.parent = null; child.nextSibling = null; child.previousSibling = null; } this.children = []; this.hasChildren = false; }, _recalculateSiblings: function(myIndex) { if (!this.parent) return; var previousChild = (myIndex > 0 ? this.parent.children[myIndex - 1] : null); if (previousChild) { previousChild.nextSibling = this; this.previousSibling = previousChild; } else this.previousSibling = null; var nextChild = this.parent.children[myIndex + 1]; if (nextChild) { nextChild.previousSibling = this; this.nextSibling = nextChild; } else this.nextSibling = null; }, collapse: function() { if (this._isRoot) return; if (this._element) this._element.removeStyleClass("expanded"); this._expanded = false; for (var i = 0; i < this.children.length; ++i) this.children[i].revealed = false; this.dispatchEventToListeners("collapsed"); }, collapseRecursively: function() { var item = this; while (item) { if (item.expanded) item.collapse(); item = item.traverseNextNode(false, this, true); } }, expand: function() { if (!this.hasChildren || this.expanded) return; if (this._isRoot) return; if (this.revealed && !this._shouldRefreshChildren) for (var i = 0; i < this.children.length; ++i) this.children[i].revealed = true; if (this._shouldRefreshChildren) { for (var i = 0; i < this.children.length; ++i) this.children[i]._detach(); this.dispatchEventToListeners("populate"); if (this._attached) { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (this.revealed) child.revealed = true; child._attach(); } } delete this._shouldRefreshChildren; } if (this._element) this._element.addStyleClass("expanded"); this._expanded = true; this.dispatchEventToListeners("expanded"); }, expandRecursively: function() { var item = this; while (item) { item.expand(); item = item.traverseNextNode(false, this); } }, reveal: function() { if (this._isRoot) return; var currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { if (!currentAncestor.expanded) currentAncestor.expand(); currentAncestor = currentAncestor.parent; } this.element.scrollIntoViewIfNeeded(false); this.dispatchEventToListeners("revealed"); }, select: function(supressSelectedEvent) { if (!this.dataGrid || !this.selectable || this.selected) return; if (this.dataGrid.selectedNode) this.dataGrid.selectedNode.deselect(); this._selected = true; this.dataGrid.selectedNode = this; if (this._element) this._element.addStyleClass("selected"); if (!supressSelectedEvent) { this.dispatchEventToListeners("selected"); this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.SelectedNode); } }, revealAndSelect: function() { if (this._isRoot) return; this.reveal(); this.select(); }, deselect: function(supressDeselectedEvent) { if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected) return; this._selected = false; this.dataGrid.selectedNode = null; if (this._element) this._element.removeStyleClass("selected"); if (!supressDeselectedEvent) { this.dispatchEventToListeners("deselected"); this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.DeselectedNode); } }, traverseNextNode: function(skipHidden, stayWithin, dontPopulate, info) { if (!dontPopulate && this.hasChildren) this.dispatchEventToListeners("populate"); if (info) info.depthChange = 0; var node = (!skipHidden || this.revealed) ? this.children[0] : null; if (node && (!skipHidden || this.expanded)) { if (info) info.depthChange = 1; return node; } if (this === stayWithin) return null; node = (!skipHidden || this.revealed) ? this.nextSibling : null; if (node) return node; node = this; while (node && !node._isRoot && !((!skipHidden || node.revealed) ? node.nextSibling : null) && node.parent !== stayWithin) { if (info) info.depthChange -= 1; node = node.parent; } if (!node) return null; return (!skipHidden || node.revealed) ? node.nextSibling : null; }, traversePreviousNode: function(skipHidden, dontPopulate) { var node = (!skipHidden || this.revealed) ? this.previousSibling : null; if (!dontPopulate && node && node.hasChildren) node.dispatchEventToListeners("populate"); while (node && ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null)) { if (!dontPopulate && node.hasChildren) node.dispatchEventToListeners("populate"); node = ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null); } if (node) return node; if (!this.parent || this.parent._isRoot) return null; return this.parent; }, isEventWithinDisclosureTriangle: function(event) { if (!this.hasChildren) return false; var cell = event.target.enclosingNodeOrSelfWithNodeName("td"); if (!cell.hasStyleClass("disclosure")) return false; var left = cell.totalOffsetLeft() + this.leftPadding; return event.pageX >= left && event.pageX <= left + this.disclosureToggleWidth; }, _attach: function() { if (!this.dataGrid || this._attached) return; this._attached = true; var nextNode = null; var previousNode = this.traversePreviousNode(true, true); if (previousNode && previousNode.element.parentNode && previousNode.element.nextSibling) nextNode = previousNode.element.nextSibling; if (!nextNode) nextNode = this.dataGrid.dataTableBody.firstChild; this.dataGrid.dataTableBody.insertBefore(this.element, nextNode); if (this.expanded) for (var i = 0; i < this.children.length; ++i) this.children[i]._attach(); }, _detach: function() { if (!this._attached) return; this._attached = false; if (this._element && this._element.parentNode) this._element.parentNode.removeChild(this._element); for (var i = 0; i < this.children.length; ++i) this.children[i]._detach(); this.wasDetached(); }, wasDetached: function() { }, savePosition: function() { if (this._savedPosition) return; if (!this.parent) throw("savePosition: Node must have a parent."); this._savedPosition = { parent: this.parent, index: this.parent.children.indexOf(this) }; }, restorePosition: function() { if (!this._savedPosition) return; if (this.parent !== this._savedPosition.parent) this._savedPosition.parent.insertChild(this, this._savedPosition.index); delete this._savedPosition; }, __proto__: WebInspector.Object.prototype } WebInspector.CreationDataGridNode = function(data, hasChildren) { WebInspector.DataGridNode.call(this, data, hasChildren); this.isCreationNode = true; } WebInspector.CreationDataGridNode.prototype = { makeNormal: function() { delete this.isCreationNode; delete this.makeNormal; }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.ShowMoreDataGridNode = function(callback, startPosition, endPosition, chunkSize) { WebInspector.DataGridNode.call(this, {summaryRow:true}, false); this._callback = callback; this._startPosition = startPosition; this._endPosition = endPosition; this._chunkSize = chunkSize; this.showNext = document.createElement("button"); this.showNext.setAttribute("type", "button"); this.showNext.addEventListener("click", this._showNextChunk.bind(this), false); this.showNext.textContent = WebInspector.UIString("Show %d before", this._chunkSize); this.showAll = document.createElement("button"); this.showAll.setAttribute("type", "button"); this.showAll.addEventListener("click", this._showAll.bind(this), false); this.showLast = document.createElement("button"); this.showLast.setAttribute("type", "button"); this.showLast.addEventListener("click", this._showLastChunk.bind(this), false); this.showLast.textContent = WebInspector.UIString("Show %d after", this._chunkSize); this._updateLabels(); this.selectable = false; } WebInspector.ShowMoreDataGridNode.prototype = { _showNextChunk: function() { this._callback(this._startPosition, this._startPosition + this._chunkSize); }, _showAll: function() { this._callback(this._startPosition, this._endPosition); }, _showLastChunk: function() { this._callback(this._endPosition - this._chunkSize, this._endPosition); }, _updateLabels: function() { var totalSize = this._endPosition - this._startPosition; if (totalSize > this._chunkSize) { this.showNext.removeStyleClass("hidden"); this.showLast.removeStyleClass("hidden"); } else { this.showNext.addStyleClass("hidden"); this.showLast.addStyleClass("hidden"); } this.showAll.textContent = WebInspector.UIString("Show all %d", totalSize); }, createCells: function() { var cell = document.createElement("td"); if (this.depth) cell.style.setProperty("padding-left", (this.depth * this.dataGrid.indentWidth) + "px"); cell.appendChild(this.showNext); cell.appendChild(this.showAll); cell.appendChild(this.showLast); this._element.appendChild(cell); var columns = this.dataGrid.columns; var count = 0; for (var c in columns) ++count; while (--count > 0) { cell = document.createElement("td"); this._element.appendChild(cell); } }, setStartPosition: function(from) { this._startPosition = from; this._updateLabels(); }, setEndPosition: function(to) { this._endPosition = to; this._updateLabels(); }, nodeHeight: function() { return 32; }, dispose: function() { }, __proto__: WebInspector.DataGridNode.prototype } WebInspector.CookiesTable = function(expandable, deleteCallback, refreshCallback) { WebInspector.View.call(this); this.element.className = "fill"; var columns = { 0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {} }; columns[0].title = WebInspector.UIString("Name"); columns[0].sortable = true; columns[0].disclosure = expandable; columns[0].width = "24%"; columns[0].sort = "ascending"; columns[1].title = WebInspector.UIString("Value"); columns[1].sortable = true; columns[1].width = "34%"; columns[2].title = WebInspector.UIString("Domain"); columns[2].sortable = true; columns[2].width = "7%"; columns[3].title = WebInspector.UIString("Path"); columns[3].sortable = true; columns[3].width = "7%"; columns[4].title = WebInspector.UIString("Expires / Max-Age"); columns[4].sortable = true; columns[4].width = "7%"; columns[5].title = WebInspector.UIString("Size"); columns[5].aligned = "right"; columns[5].sortable = true; columns[5].width = "7%"; columns[6].title = WebInspector.UIString("HTTP"); columns[6].aligned = "centered"; columns[6].sortable = true; columns[6].width = "7%"; columns[7].title = WebInspector.UIString("Secure"); columns[7].aligned = "centered"; columns[7].sortable = true; columns[7].width = "7%"; this._dataGrid = new WebInspector.DataGrid(columns, undefined, deleteCallback ? this._onDeleteFromGrid.bind(this, deleteCallback) : undefined); this._dataGrid.addEventListener("sorting changed", this._rebuildTable, this); this._dataGrid.refreshCallback = refreshCallback; this._dataGrid.show(this.element); this._data = []; } WebInspector.CookiesTable.prototype = { updateWidths: function() { if (this._dataGrid) this._dataGrid.updateWidths(); }, setCookies: function(cookies) { this._data = [{cookies: cookies}]; this._rebuildTable(); }, addCookiesFolder: function(folderName, cookies) { this._data.push({cookies: cookies, folderName: folderName}); this._rebuildTable(); }, get selectedCookie() { var node = this._dataGrid.selectedNode; return node ? node.cookie : null; }, _rebuildTable: function() { this._dataGrid.rootNode().removeChildren(); for (var i = 0; i < this._data.length; ++i) { var item = this._data[i]; if (item.folderName) { var groupData = [ item.folderName, "", "", "", "", this._totalSize(item.cookies), "", "" ]; var groupNode = new WebInspector.DataGridNode(groupData); groupNode.selectable = true; this._dataGrid.rootNode().appendChild(groupNode); groupNode.element.addStyleClass("row-group"); this._populateNode(groupNode, item.cookies); groupNode.expand(); } else this._populateNode(this._dataGrid.rootNode(), item.cookies); } }, _populateNode: function(parentNode, cookies) { var selectedCookie = this.selectedCookie; parentNode.removeChildren(); if (!cookies) return; this._sortCookies(cookies); for (var i = 0; i < cookies.length; ++i) { var cookieNode = this._createGridNode(cookies[i]); parentNode.appendChild(cookieNode); if (selectedCookie === cookies[i]) cookieNode.selected = true; } }, _totalSize: function(cookies) { var totalSize = 0; for (var i = 0; cookies && i < cookies.length; ++i) totalSize += cookies[i].size(); return totalSize; }, _sortCookies: function(cookies) { var sortDirection = this._dataGrid.sortOrder === "ascending" ? 1 : -1; function localeCompare(getter, cookie1, cookie2) { return sortDirection * (getter.apply(cookie1) + "").localeCompare(getter.apply(cookie2) + "") } function numberCompare(getter, cookie1, cookie2) { return sortDirection * (getter.apply(cookie1) - getter.apply(cookie2)); } function expiresCompare(cookie1, cookie2) { if (cookie1.session() !== cookie2.session()) return sortDirection * (cookie1.session() ? 1 : -1); if (cookie1.session()) return 0; if (cookie1.maxAge() && cookie2.maxAge()) return sortDirection * (cookie1.maxAge() - cookie2.maxAge()); if (cookie1.expires() && cookie2.expires()) return sortDirection * (cookie1.expires() - cookie2.expires()); return sortDirection * (cookie1.expires() ? 1 : -1); } var comparator; switch (parseInt(this._dataGrid.sortColumnIdentifier, 10)) { case 0: comparator = localeCompare.bind(null, WebInspector.Cookie.prototype.name); break; case 1: comparator = localeCompare.bind(null, WebInspector.Cookie.prototype.value); break; case 2: comparator = localeCompare.bind(null, WebInspector.Cookie.prototype.domain); break; case 3: comparator = localeCompare.bind(null, WebInspector.Cookie.prototype.path); break; case 4: comparator = expiresCompare; break; case 5: comparator = numberCompare.bind(null, WebInspector.Cookie.prototype.size); break; case 6: comparator = localeCompare.bind(null, WebInspector.Cookie.prototype.httpOnly); break; case 7: comparator = localeCompare.bind(null, WebInspector.Cookie.prototype.secure); break; default: localeCompare.bind(null, WebInspector.Cookie.prototype.name); } cookies.sort(comparator); }, _createGridNode: function(cookie) { var data = {}; data[0] = cookie.name(); data[1] = cookie.value(); data[2] = cookie.domain() || ""; data[3] = cookie.path() || ""; if (cookie.type() === WebInspector.Cookie.Type.Request) data[4] = ""; else if (cookie.maxAge()) data[4] = Number.secondsToString(parseInt(cookie.maxAge(), 10)); else if (cookie.expires()) data[4] = new Date(cookie.expires()).toGMTString(); else data[4] = WebInspector.UIString("Session"); data[5] = cookie.size(); const checkmark = "\u2713"; data[6] = (cookie.httpOnly() ? checkmark : ""); data[7] = (cookie.secure() ? checkmark : ""); var node = new WebInspector.DataGridNode(data); node.cookie = cookie; node.selectable = true; return node; }, _onDeleteFromGrid: function(deleteCallback, node) { deleteCallback(node.cookie); }, __proto__: WebInspector.View.prototype } WebInspector.CookieItemsView = function(treeElement, cookieDomain) { WebInspector.View.call(this); this.element.addStyleClass("storage-view"); this._deleteButton = new WebInspector.StatusBarButton(WebInspector.UIString("Delete"), "delete-storage-status-bar-item"); this._deleteButton.visible = false; this._deleteButton.addEventListener("click", this._deleteButtonClicked, this); this._refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item"); this._refreshButton.addEventListener("click", this._refreshButtonClicked, this); this._treeElement = treeElement; this._cookieDomain = cookieDomain; this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("This site has no cookies.")); this._emptyView.show(this.element); this.element.addEventListener("contextmenu", this._contextMenu.bind(this), true); } WebInspector.CookieItemsView.prototype = { get statusBarItems() { return [this._refreshButton.element, this._deleteButton.element]; }, wasShown: function() { this._update(); }, willHide: function() { this._deleteButton.visible = false; }, _update: function() { WebInspector.Cookies.getCookiesAsync(this._updateWithCookies.bind(this)); }, _updateWithCookies: function(allCookies, isAdvanced) { this._cookies = isAdvanced ? this._filterCookiesForDomain(allCookies) : allCookies; if (!this._cookies.length) { this._emptyView.show(this.element); this._deleteButton.visible = false; if (this._cookiesTable) this._cookiesTable.detach(); return; } if (!this._cookiesTable) this._cookiesTable = isAdvanced ? new WebInspector.CookiesTable(false, this._deleteCookie.bind(this), this._update.bind(this)) : new WebInspector.SimpleCookiesTable(); this._cookiesTable.setCookies(this._cookies); this._emptyView.detach(); this._cookiesTable.show(this.element); if (isAdvanced) { this._treeElement.subtitle = String.sprintf(WebInspector.UIString("%d cookies (%s)"), this._cookies.length, Number.bytesToString(this._totalSize)); this._deleteButton.visible = true; } }, _filterCookiesForDomain: function(allCookies) { var cookies = []; var resourceURLsForDocumentURL = []; this._totalSize = 0; function populateResourcesForDocuments(resource) { var url = resource.documentURL.asParsedURL(); if (url && url.host == this._cookieDomain) resourceURLsForDocumentURL.push(resource.url); } WebInspector.forAllResources(populateResourcesForDocuments.bind(this)); for (var i = 0; i < allCookies.length; ++i) { var pushed = false; var size = allCookies[i].size(); for (var j = 0; j < resourceURLsForDocumentURL.length; ++j) { var resourceURL = resourceURLsForDocumentURL[j]; if (WebInspector.Cookies.cookieMatchesResourceURL(allCookies[i], resourceURL)) { this._totalSize += size; if (!pushed) { pushed = true; cookies.push(allCookies[i]); } } } } return cookies; }, _deleteCookie: function(cookie) { PageAgent.deleteCookie(cookie.name(), this._cookieDomain); this._update(); }, _deleteButtonClicked: function() { if (this._cookiesTable.selectedCookie) this._deleteCookie(this._cookiesTable.selectedCookie); }, _refreshButtonClicked: function(event) { this._update(); }, _contextMenu: function(event) { if (!this._cookies.length) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Refresh"), this._update.bind(this)); contextMenu.show(); } }, __proto__: WebInspector.View.prototype } WebInspector.SimpleCookiesTable = function() { WebInspector.View.call(this); var columns = {}; columns[0] = {}; columns[1] = {}; columns[0].title = WebInspector.UIString("Name"); columns[1].title = WebInspector.UIString("Value"); this._dataGrid = new WebInspector.DataGrid(columns); this._dataGrid.autoSizeColumns(20, 80); this._dataGrid.show(this.element); } WebInspector.SimpleCookiesTable.prototype = { setCookies: function(cookies) { this._dataGrid.rootNode().removeChildren(); var addedCookies = {}; for (var i = 0; i < cookies.length; ++i) { if (addedCookies[cookies[i].name()]) continue; addedCookies[cookies[i].name()] = true; var data = {}; data[0] = cookies[i].name(); data[1] = cookies[i].value(); var node = new WebInspector.DataGridNode(data, false); node.selectable = true; this._dataGrid.rootNode().appendChild(node); } this._dataGrid.rootNode().children[0].selected = true; }, __proto__: WebInspector.View.prototype } WebInspector.ApplicationCacheModel = function() { ApplicationCacheAgent.enable(); InspectorBackend.registerApplicationCacheDispatcher(new WebInspector.ApplicationCacheDispatcher(this)); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this); this._statuses = {}; this._manifestURLsByFrame = {}; this._mainFrameNavigated(); this._onLine = true; } WebInspector.ApplicationCacheModel.EventTypes = { FrameManifestStatusUpdated: "FrameManifestStatusUpdated", FrameManifestAdded: "FrameManifestAdded", FrameManifestRemoved: "FrameManifestRemoved", NetworkStateChanged: "NetworkStateChanged" } WebInspector.ApplicationCacheModel.prototype = { _frameNavigated: function(event) { var frame = (event.data); if (frame.isMainFrame()) { this._mainFrameNavigated(); return; } ApplicationCacheAgent.getManifestForFrame(frame.id, this._manifestForFrameLoaded.bind(this, frame.id)); }, _frameDetached: function(event) { var frame = (event.data); this._frameManifestRemoved(frame.id); }, _mainFrameNavigated: function() { ApplicationCacheAgent.getFramesWithManifests(this._framesWithManifestsLoaded.bind(this)); }, _manifestForFrameLoaded: function(frameId, error, manifestURL) { if (error) { console.error(error); return; } if (!manifestURL) this._frameManifestRemoved(frameId); }, _framesWithManifestsLoaded: function(error, framesWithManifests) { if (error) { console.error(error); return; } for (var i = 0; i < framesWithManifests.length; ++i) this._frameManifestUpdated(framesWithManifests[i].frameId, framesWithManifests[i].manifestURL, framesWithManifests[i].status); }, _frameManifestUpdated: function(frameId, manifestURL, status) { if (status === applicationCache.UNCACHED) { this._frameManifestRemoved(frameId); return; } if (!manifestURL) return; if (this._manifestURLsByFrame[frameId] && manifestURL !== this._manifestURLsByFrame[frameId]) this._frameManifestRemoved(frameId); var statusChanged = this._statuses[frameId] !== status; this._statuses[frameId] = status; if (!this._manifestURLsByFrame[frameId]) { this._manifestURLsByFrame[frameId] = manifestURL; this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestAdded, frameId); } if (statusChanged) this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestStatusUpdated, frameId); }, _frameManifestRemoved: function(frameId) { if (!this._manifestURLsByFrame[frameId]) return; var manifestURL = this._manifestURLsByFrame[frameId]; delete this._manifestURLsByFrame[frameId]; delete this._statuses[frameId]; this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestRemoved, frameId); }, frameManifestURL: function(frameId) { return this._manifestURLsByFrame[frameId] || ""; }, frameManifestStatus: function(frameId) { return this._statuses[frameId] || applicationCache.UNCACHED; }, get onLine() { return this._onLine; }, _statusUpdated: function(frameId, manifestURL, status) { this._frameManifestUpdated(frameId, manifestURL, status); }, requestApplicationCache: function(frameId, callback) { function callbackWrapper(error, applicationCache) { if (error) { console.error(error); callback(null); return; } callback(applicationCache); } ApplicationCacheAgent.getApplicationCacheForFrame(frameId, callbackWrapper.bind(this)); }, _networkStateUpdated: function(isNowOnline) { this._onLine = isNowOnline; this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.NetworkStateChanged, isNowOnline); }, __proto__: WebInspector.Object.prototype } WebInspector.ApplicationCacheDispatcher = function(applicationCacheModel) { this._applicationCacheModel = applicationCacheModel; } WebInspector.ApplicationCacheDispatcher.prototype = { applicationCacheStatusUpdated: function(frameId, manifestURL, status) { this._applicationCacheModel._statusUpdated(frameId, manifestURL, status); }, networkStateUpdated: function(isNowOnline) { this._applicationCacheModel._networkStateUpdated(isNowOnline); } } WebInspector.IndexedDBModel = function() { IndexedDBAgent.enable(); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this); this._frames = {}; this._databases = new Map(); this._frameIdsBySecurityOrigin = {}; this._databaseNamesBySecurityOrigin = {}; this.refreshDatabaseNames(); } WebInspector.IndexedDBModel.KeyTypes = { NumberType: "number", StringType: "string", DateType: "date", ArrayType: "array" }; WebInspector.IndexedDBModel.KeyPathTypes = { NullType: "null", StringType: "string", ArrayType: "array" }; WebInspector.IndexedDBModel.keyFromIDBKey = function(idbKey) { if (typeof(idbKey) === "undefined" || idbKey === null) return null; var key = {}; switch (typeof(idbKey)) { case "number": key.number = idbKey; key.type = WebInspector.IndexedDBModel.KeyTypes.NumberType; break; case "string": key.string = idbKey; key.type = WebInspector.IndexedDBModel.KeyTypes.StringType; break; case "object": if (idbKey instanceof Date) { key.date = idbKey.getTime(); key.type = WebInspector.IndexedDBModel.KeyTypes.DateType; } else if (idbKey instanceof Array) { key.array = []; for (var i = 0; i < idbKey.length; ++i) key.array.push(WebInspector.IndexedDBModel.keyFromIDBKey(idbKey[i])); key.type = WebInspector.IndexedDBModel.KeyTypes.ArrayType; } break; default: return null; } return key; } WebInspector.IndexedDBModel.keyRangeFromIDBKeyRange = function(idbKeyRange) { var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange; if (typeof(idbKeyRange) === "undefined" || idbKeyRange === null) return null; var keyRange = {}; keyRange.lower = WebInspector.IndexedDBModel.keyFromIDBKey(idbKeyRange.lower); keyRange.upper = WebInspector.IndexedDBModel.keyFromIDBKey(idbKeyRange.upper); keyRange.lowerOpen = idbKeyRange.lowerOpen; keyRange.upperOpen = idbKeyRange.upperOpen; return keyRange; } WebInspector.IndexedDBModel.idbKeyPathFromKeyPath = function(keyPath) { var idbKeyPath; switch (keyPath.type) { case WebInspector.IndexedDBModel.KeyPathTypes.NullType: idbKeyPath = null; break; case WebInspector.IndexedDBModel.KeyPathTypes.StringType: idbKeyPath = keyPath.string; break; case WebInspector.IndexedDBModel.KeyPathTypes.ArrayType: idbKeyPath = keyPath.array; break; } return idbKeyPath; } WebInspector.IndexedDBModel.keyPathStringFromIDBKeyPath = function(idbKeyPath) { if (typeof idbKeyPath === "string") return "\"" + idbKeyPath + "\""; if (idbKeyPath instanceof Array) return "[\"" + idbKeyPath.join("\", \"") + "\"]"; return null; } WebInspector.IndexedDBModel.EventTypes = { DatabaseAdded: "DatabaseAdded", DatabaseRemoved: "DatabaseRemoved", DatabaseLoaded: "DatabaseLoaded" } WebInspector.IndexedDBModel.prototype = { refreshDatabaseNames: function() { this._reset(); if (WebInspector.resourceTreeModel.mainFrame) this._framesNavigatedRecursively(WebInspector.resourceTreeModel.mainFrame); }, refreshDatabase: function(databaseId) { this._loadDatabase(databaseId); }, _framesNavigatedRecursively: function(resourceTreeFrame) { this._processFrameNavigated(resourceTreeFrame); for (var i = 0; i < resourceTreeFrame.childFrames.length; ++i) this._framesNavigatedRecursively(resourceTreeFrame.childFrames[i]); }, _frameNavigated: function(event) { var resourceTreeFrame = (event.data); this._processFrameNavigated(resourceTreeFrame); }, _frameDetached: function(event) { var resourceTreeFrame = (event.data); this._originRemovedFromFrame(resourceTreeFrame.id); }, _reset: function() { for (var frameId in this._frames) this._originRemovedFromFrame(frameId); }, _processFrameNavigated: function(resourceTreeFrame) { if (resourceTreeFrame.securityOrigin === "null") return; if (this._frameIdsBySecurityOrigin[resourceTreeFrame.securityOrigin]) this._originAddedToFrame(resourceTreeFrame.id, resourceTreeFrame.securityOrigin); else this._loadDatabaseNamesForFrame(resourceTreeFrame.id); }, _originAddedToFrame: function(frameId, securityOrigin) { if (!this._frameIdsBySecurityOrigin[securityOrigin]) { this._frameIdsBySecurityOrigin[securityOrigin] = []; this._frameIdsBySecurityOrigin[securityOrigin].push(frameId); this._databaseNamesBySecurityOrigin[securityOrigin] = []; } this._frames[frameId] = new WebInspector.IndexedDBModel.Frame(frameId, securityOrigin); }, _originRemovedFromFrame: function(frameId) { var currentSecurityOrigin = this._frames[frameId] ? this._frames[frameId].securityOrigin : null; if (!currentSecurityOrigin) return; delete this._frames[frameId]; var frameIdsForOrigin = this._frameIdsBySecurityOrigin[currentSecurityOrigin]; for (var i = 0; i < frameIdsForOrigin; ++i) { if (frameIdsForOrigin[i] === frameId) { frameIdsForOrigin.splice(i, 1); break; } } if (!frameIdsForOrigin.length) this._originRemoved(currentSecurityOrigin); }, _originRemoved: function(securityOrigin) { var frameIdsForOrigin = this._frameIdsBySecurityOrigin[securityOrigin]; for (var i = 0; i < frameIdsForOrigin; ++i) delete this._frames[frameIdsForOrigin[i]]; delete this._frameIdsBySecurityOrigin[securityOrigin]; for (var i = 0; i < this._databaseNamesBySecurityOrigin[securityOrigin].length; ++i) this._databaseRemoved(securityOrigin, this._databaseNamesBySecurityOrigin[securityOrigin][i]); delete this._databaseNamesBySecurityOrigin[securityOrigin]; }, _updateOriginDatabaseNames: function(securityOrigin, databaseNames) { var newDatabaseNames = {}; for (var i = 0; i < databaseNames.length; ++i) newDatabaseNames[databaseNames[i]] = true; var oldDatabaseNames = {}; for (var i = 0; i < this._databaseNamesBySecurityOrigin[securityOrigin].length; ++i) oldDatabaseNames[databaseNames[i]] = true; this._databaseNamesBySecurityOrigin[securityOrigin] = databaseNames; for (var databaseName in oldDatabaseNames) { if (!newDatabaseNames[databaseName]) this._databaseRemoved(securityOrigin, databaseName); } for (var databaseName in newDatabaseNames) { if (!oldDatabaseNames[databaseName]) this._databaseAdded(securityOrigin, databaseName); } if (!this._databaseNamesBySecurityOrigin[securityOrigin].length) this._originRemoved(securityOrigin); }, _databaseAdded: function(securityOrigin, databaseName) { var databaseId = new WebInspector.IndexedDBModel.DatabaseId(securityOrigin, databaseName); this.dispatchEventToListeners(WebInspector.IndexedDBModel.EventTypes.DatabaseAdded, databaseId); }, _databaseRemoved: function(securityOrigin, databaseName) { var databaseId = new WebInspector.IndexedDBModel.DatabaseId(securityOrigin, databaseName); this.dispatchEventToListeners(WebInspector.IndexedDBModel.EventTypes.DatabaseRemoved, databaseId); }, _loadDatabaseNamesForFrame: function(frameId) { function callback(error, securityOriginWithDatabaseNames) { if (error) { console.error("IndexedDBAgent error: " + error); return; } var databaseNames = securityOriginWithDatabaseNames.databaseNames; var oldSecurityOrigin = this._frames[frameId] ? this._frames[frameId].securityOrigin : null; if (!oldSecurityOrigin || oldSecurityOrigin !== securityOriginWithDatabaseNames.securityOrigin) { this._originRemovedFromFrame(frameId); this._originAddedToFrame(frameId, securityOriginWithDatabaseNames.securityOrigin); } this._updateOriginDatabaseNames(securityOriginWithDatabaseNames.securityOrigin, securityOriginWithDatabaseNames.databaseNames); } IndexedDBAgent.requestDatabaseNamesForFrame(frameId, callback.bind(this)); }, _assertFrameId: function(databaseId) { var frameIds = this._frameIdsBySecurityOrigin[databaseId.securityOrigin]; if (!frameIds || !frameIds.length) return null; return frameIds[0]; }, _loadDatabase: function(databaseId) { var frameId = this._assertFrameId(databaseId); if (!frameId) return; function callback(error, databaseWithObjectStores) { if (error) { console.error("IndexedDBAgent error: " + error); return; } if (!this._frames[frameId]) return; var databaseModel = new WebInspector.IndexedDBModel.Database(databaseId, databaseWithObjectStores.version, databaseWithObjectStores.intVersion); this._databases.put(databaseId, databaseModel); for (var i = 0; i < databaseWithObjectStores.objectStores.length; ++i) { var objectStore = databaseWithObjectStores.objectStores[i]; var objectStoreIDBKeyPath = WebInspector.IndexedDBModel.idbKeyPathFromKeyPath(objectStore.keyPath); var objectStoreModel = new WebInspector.IndexedDBModel.ObjectStore(objectStore.name, objectStoreIDBKeyPath, objectStore.autoIncrement); for (var j = 0; j < objectStore.indexes.length; ++j) { var index = objectStore.indexes[j]; var indexIDBKeyPath = WebInspector.IndexedDBModel.idbKeyPathFromKeyPath(index.keyPath); var indexModel = new WebInspector.IndexedDBModel.Index(index.name, indexIDBKeyPath, index.unique, index.multiEntry); objectStoreModel.indexes[indexModel.name] = indexModel; } databaseModel.objectStores[objectStoreModel.name] = objectStoreModel; } this.dispatchEventToListeners(WebInspector.IndexedDBModel.EventTypes.DatabaseLoaded, databaseModel); } IndexedDBAgent.requestDatabase(frameId, databaseId.name, callback.bind(this)); }, loadObjectStoreData: function(databaseId, objectStoreName, idbKeyRange, skipCount, pageSize, callback) { this._requestData(databaseId, databaseId.name, objectStoreName, "", idbKeyRange, skipCount, pageSize, callback); }, loadIndexData: function(databaseId, objectStoreName, indexName, idbKeyRange, skipCount, pageSize, callback) { this._requestData(databaseId, databaseId.name, objectStoreName, indexName, idbKeyRange, skipCount, pageSize, callback); }, _requestData: function(databaseId, databaseName, objectStoreName, indexName, idbKeyRange, skipCount, pageSize, callback) { var frameId = this._assertFrameId(databaseId); if (!frameId) return; function innerCallback(error, dataEntries, hasMore) { if (error) { console.error("IndexedDBAgent error: " + error); return; } if (!this._frames[frameId]) return; var entries = []; for (var i = 0; i < dataEntries.length; ++i) { var key = WebInspector.RemoteObject.fromPayload(dataEntries[i].key); var primaryKey = WebInspector.RemoteObject.fromPayload(dataEntries[i].primaryKey); var value = WebInspector.RemoteObject.fromPayload(dataEntries[i].value); entries.push(new WebInspector.IndexedDBModel.Entry(key, primaryKey, value)); } callback(entries, hasMore); } var keyRange = WebInspector.IndexedDBModel.keyRangeFromIDBKeyRange(idbKeyRange); IndexedDBAgent.requestData(frameId, databaseName, objectStoreName, indexName, skipCount, pageSize, keyRange ? keyRange : undefined, innerCallback.bind(this)); }, __proto__: WebInspector.Object.prototype } WebInspector.IndexedDBModel.Entry = function(key, primaryKey, value) { this.key = key; this.primaryKey = primaryKey; this.value = value; } WebInspector.IndexedDBModel.Frame = function(frameId, securityOrigin) { this.frameId = frameId; this.securityOrigin = securityOrigin; this.databaseNames = {}; } WebInspector.IndexedDBModel.DatabaseId = function(securityOrigin, name) { this.securityOrigin = securityOrigin; this.name = name; } WebInspector.IndexedDBModel.DatabaseId.prototype = { equals: function(databaseId) { return this.name === databaseId.name && this.securityOrigin === databaseId.securityOrigin; }, } WebInspector.IndexedDBModel.Database = function(databaseId, version, intVersion) { this.databaseId = databaseId; this.version = version; this.intVersion = intVersion; this.objectStores = {}; } WebInspector.IndexedDBModel.ObjectStore = function(name, keyPath, autoIncrement) { this.name = name; this.keyPath = keyPath; this.autoIncrement = autoIncrement; this.indexes = {}; } WebInspector.IndexedDBModel.ObjectStore.prototype = { get keyPathString() { return WebInspector.IndexedDBModel.keyPathStringFromIDBKeyPath(this.keyPath); } } WebInspector.IndexedDBModel.Index = function(name, keyPath, unique, multiEntry) { this.name = name; this.keyPath = keyPath; this.unique = unique; this.multiEntry = multiEntry; } WebInspector.IndexedDBModel.Index.prototype = { get keyPathString() { return WebInspector.IndexedDBModel.keyPathStringFromIDBKeyPath(this.keyPath); } } WebInspector.Spectrum = function() { WebInspector.View.call(this); this.registerRequiredCSS("spectrum.css"); this.element.className = "spectrum-container"; this.element.tabIndex = 0; var topElement = this.element.createChild("div", "spectrum-top"); topElement.createChild("div", "spectrum-fill"); var topInnerElement = topElement.createChild("div", "spectrum-top-inner fill"); this._draggerElement = topInnerElement.createChild("div", "spectrum-color"); this._dragHelperElement = this._draggerElement.createChild("div", "spectrum-sat fill").createChild("div", "spectrum-val fill").createChild("div", "spectrum-dragger"); this._sliderElement = topInnerElement.createChild("div", "spectrum-hue"); this.slideHelper = this._sliderElement.createChild("div", "spectrum-slider"); var rangeContainer = this.element.createChild("div", "spectrum-range-container"); var alphaLabel = rangeContainer.createChild("label"); alphaLabel.textContent = WebInspector.UIString("\u03B1:"); this._alphaElement = rangeContainer.createChild("input", "spectrum-range"); this._alphaElement.setAttribute("type", "range"); this._alphaElement.setAttribute("min", "0"); this._alphaElement.setAttribute("max", "100"); this._alphaElement.addEventListener("change", alphaDrag.bind(this), false); var swatchElement = document.createElement("span"); swatchElement.className = "swatch"; this._swatchInnerElement = swatchElement.createChild("span", "swatch-inner"); var displayContainer = this.element.createChild("div"); displayContainer.appendChild(swatchElement); this._displayElement = displayContainer.createChild("span", "source-code spectrum-display-value"); WebInspector.Spectrum.draggable(this._sliderElement, hueDrag.bind(this)); WebInspector.Spectrum.draggable(this._draggerElement, colorDrag.bind(this), colorDragStart.bind(this)); function hueDrag(element, dragX, dragY) { this.hsv[0] = (dragY / this.slideHeight); this._onchange(); } var initialHelperOffset; function colorDragStart(element, dragX, dragY) { initialHelperOffset = { x: this._dragHelperElement.offsetLeft, y: this._dragHelperElement.offsetTop }; } function colorDrag(element, dragX, dragY, event) { if (event.shiftKey) { if (Math.abs(dragX - initialHelperOffset.x) >= Math.abs(dragY - initialHelperOffset.y)) dragY = initialHelperOffset.y; else dragX = initialHelperOffset.x; } this.hsv[1] = dragX / this.dragWidth; this.hsv[2] = (this.dragHeight - dragY) / this.dragHeight; this._onchange(); } function alphaDrag() { this.hsv[3] = this._alphaElement.value / 100; this._onchange(); } }; WebInspector.Spectrum.Events = { ColorChanged: "ColorChanged" }; WebInspector.Spectrum.hsvaToRGBA = function(h, s, v, a) { var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch(i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a]; }; WebInspector.Spectrum.rgbaToHSVA = function(r, g, b, a) { r = r / 255; g = g / 255; b = b / 255; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var h; var s; var v = max; var d = max - min; s = max ? d / max : 0; if(max === min) { h = 0; } else { switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, v, a]; }; WebInspector.Spectrum.draggable = function(element, onmove, onstart, onstop) { var doc = document; var dragging; var offset; var scrollOffset; var maxHeight; var maxWidth; function consume(e) { e.consume(true); } function move(e) { if (dragging) { var dragX = Math.max(0, Math.min(e.pageX - offset.left + scrollOffset.left, maxWidth)); var dragY = Math.max(0, Math.min(e.pageY - offset.top + scrollOffset.top, maxHeight)); if (onmove) onmove(element, dragX, dragY, e); } } function start(e) { var rightClick = e.which ? (e.which === 3) : (e.button === 2); if (!rightClick && !dragging) { if (onstart) onstart(element, e) dragging = true; maxHeight = element.clientHeight; maxWidth = element.clientWidth; scrollOffset = element.scrollOffset(); offset = element.totalOffset(); doc.addEventListener("selectstart", consume, false); doc.addEventListener("dragstart", consume, false); doc.addEventListener("mousemove", move, false); doc.addEventListener("mouseup", stop, false); move(e); consume(e); } } function stop(e) { if (dragging) { doc.removeEventListener("selectstart", consume, false); doc.removeEventListener("dragstart", consume, false); doc.removeEventListener("mousemove", move, false); doc.removeEventListener("mouseup", stop, false); if (onstop) onstop(element, e); } dragging = false; } element.addEventListener("mousedown", start, false); }; WebInspector.Spectrum.prototype = { set color(color) { var rgba = (color.rgba || color.rgb).slice(0); if (rgba.length === 3) rgba[3] = 1; this.hsv = WebInspector.Spectrum.rgbaToHSVA(rgba[0], rgba[1], rgba[2], rgba[3]); }, get color() { var rgba = WebInspector.Spectrum.hsvaToRGBA(this.hsv[0], this.hsv[1], this.hsv[2], this.hsv[3]); var color; if (rgba[3] === 1) color = WebInspector.Color.fromRGB(rgba[0], rgba[1], rgba[2]); else color = WebInspector.Color.fromRGBA(rgba[0], rgba[1], rgba[2], rgba[3]); var colorValue = color.toString(this.outputColorFormat); if (!colorValue) colorValue = color.toString(); return new WebInspector.Color(colorValue); }, get outputColorFormat() { var cf = WebInspector.Color.Format; var format = this._originalFormat; if (this.hsv[3] === 1) { if (format === cf.RGBA) format = cf.RGB; else if (format === cf.HSLA) format = cf.HSL; } else { if (format === cf.HSL || format === cf.HSLA) format = cf.HSLA; else format = cf.RGBA; } return format; }, get colorHueOnly() { var rgba = WebInspector.Spectrum.hsvaToRGBA(this.hsv[0], 1, 1, 1); return WebInspector.Color.fromRGBA(rgba[0], rgba[1], rgba[2], rgba[3]); }, set displayText(text) { this._displayElement.textContent = text; }, _onchange: function() { this._updateUI(); this.dispatchEventToListeners(WebInspector.Spectrum.Events.ColorChanged, this.color); }, _updateHelperLocations: function() { var h = this.hsv[0]; var s = this.hsv[1]; var v = this.hsv[2]; var dragX = s * this.dragWidth; var dragY = this.dragHeight - (v * this.dragHeight); dragX = Math.max(-this._dragHelperElementHeight, Math.min(this.dragWidth - this._dragHelperElementHeight, dragX - this._dragHelperElementHeight)); dragY = Math.max(-this._dragHelperElementHeight, Math.min(this.dragHeight - this._dragHelperElementHeight, dragY - this._dragHelperElementHeight)); this._dragHelperElement.positionAt(dragX, dragY); var slideY = (h * this.slideHeight) - this.slideHelperHeight; this.slideHelper.style.top = slideY + "px"; this._alphaElement.value = this.hsv[3] * 100; }, _updateUI: function() { this._updateHelperLocations(); var rgb = (this.color.rgba || this.color.rgb).slice(0); if (rgb.length === 3) rgb[3] = 1; var rgbHueOnly = this.colorHueOnly.rgb; var flatColor = "rgb(" + rgbHueOnly[0] + ", " + rgbHueOnly[1] + ", " + rgbHueOnly[2] + ")"; var fullColor = "rgba(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ", " + rgb[3] + ")"; this._draggerElement.style.backgroundColor = flatColor; this._swatchInnerElement.style.backgroundColor = fullColor; this._alphaElement.value = this.hsv[3] * 100; }, wasShown: function() { this.slideHeight = this._sliderElement.offsetHeight; this.dragWidth = this._draggerElement.offsetWidth; this.dragHeight = this._draggerElement.offsetHeight; this._dragHelperElementHeight = this._dragHelperElement.offsetHeight / 2; this.slideHelperHeight = this.slideHelper.offsetHeight / 2; this._updateUI(); }, __proto__: WebInspector.View.prototype } WebInspector.SpectrumPopupHelper = function() { this._spectrum = new WebInspector.Spectrum(); this._spectrum.element.addEventListener("keydown", this._onKeyDown.bind(this), false); this._popover = new WebInspector.Popover(); this._popover.setCanShrink(false); this._popover.element.addEventListener("mousedown", consumeEvent, false); this._hideProxy = this.hide.bind(this, true); } WebInspector.SpectrumPopupHelper.Events = { Hidden: "Hidden" }; WebInspector.SpectrumPopupHelper.prototype = { spectrum: function() { return this._spectrum; }, toggle: function(element, color, format) { if (this._popover.isShowing()) this.hide(true); else this.show(element, color, format); return this._popover.isShowing(); }, show: function(element, color, format) { if (this._popover.isShowing()) { if (this._anchorElement === element) return false; this.hide(true); } this._anchorElement = element; this._spectrum.color = color; this._spectrum._originalFormat = format || color.format; this.reposition(element); document.addEventListener("mousedown", this._hideProxy, false); window.addEventListener("blur", this._hideProxy, false); return true; }, reposition: function(element) { if (!this._previousFocusElement) this._previousFocusElement = WebInspector.currentFocusElement(); this._popover.showView(this._spectrum, element); WebInspector.setCurrentFocusElement(this._spectrum.element); }, hide: function(commitEdit) { if (!this._popover.isShowing()) return; this._popover.hide(); document.removeEventListener("mousedown", this._hideProxy, false); window.removeEventListener("blur", this._hideProxy, false); this.dispatchEventToListeners(WebInspector.SpectrumPopupHelper.Events.Hidden, !!commitEdit); WebInspector.setCurrentFocusElement(this._previousFocusElement); delete this._previousFocusElement; delete this._anchorElement; }, _onKeyDown: function(event) { if (event.keyIdentifier === "Enter") { this.hide(true); event.consume(true); return; } if (event.keyIdentifier === "U+001B") { this.hide(false); event.consume(true); } }, __proto__: WebInspector.Object.prototype } WebInspector.ColorSwatch = function() { this.element = document.createElement("span"); this._swatchInnerElement = this.element.createChild("span", "swatch-inner"); this.element.title = WebInspector.UIString("Click to open a colorpicker. Shift-click to change color format"); this.element.className = "swatch"; this.element.addEventListener("mousedown", consumeEvent, false); this.element.addEventListener("dblclick", consumeEvent, false); } WebInspector.ColorSwatch.prototype = { setColorString: function(colorString) { this._swatchInnerElement.style.backgroundColor = colorString; } } WebInspector.SidebarPane = function(title) { this.element = document.createElement("div"); this.element.className = "pane"; this.titleElement = document.createElement("div"); this.titleElement.className = "title"; this.titleElement.tabIndex = 0; this.titleElement.addEventListener("click", this.toggleExpanded.bind(this), false); this.titleElement.addEventListener("keydown", this._onTitleKeyDown.bind(this), false); this.bodyElement = document.createElement("div"); this.bodyElement.className = "body"; this.element.appendChild(this.titleElement); this.element.appendChild(this.bodyElement); this.title = title; this.growbarVisible = false; this.expanded = false; } WebInspector.SidebarPane.prototype = { get title() { return this._title; }, set title(x) { if (this._title === x) return; this._title = x; this.titleElement.textContent = x; }, get growbarVisible() { return this._growbarVisible; }, set growbarVisible(x) { if (this._growbarVisible === x) return; this._growbarVisible = x; if (x && !this._growbarElement) { this._growbarElement = document.createElement("div"); this._growbarElement.className = "growbar"; this.element.appendChild(this._growbarElement); } else if (!x && this._growbarElement) { if (this._growbarElement.parentNode) this._growbarElement.parentNode(this._growbarElement); delete this._growbarElement; } }, get expanded() { return this._expanded; }, set expanded(x) { if (x) this.expand(); else this.collapse(); }, expand: function() { if (this._expanded) return; this._expanded = true; this.element.addStyleClass("expanded"); this.onexpand(); }, onexpand: function() { }, collapse: function() { if (!this._expanded) return; this._expanded = false; this.element.removeStyleClass("expanded"); }, toggleExpanded: function() { this.expanded = !this.expanded; }, _onTitleKeyDown: function(event) { if (isEnterKey(event) || event.keyCode === WebInspector.KeyboardShortcut.Keys.Space.code) this.toggleExpanded(); }, __proto__: WebInspector.Object.prototype } WebInspector.ElementsTreeOutline = function(omitRootDOMNode, selectEnabled, showInElementsPanelEnabled, contextMenuCallback, setPseudoClassCallback) { this.element = document.createElement("ol"); this.element.addEventListener("mousedown", this._onmousedown.bind(this), false); this.element.addEventListener("mousemove", this._onmousemove.bind(this), false); this.element.addEventListener("mouseout", this._onmouseout.bind(this), false); this.element.addEventListener("dragstart", this._ondragstart.bind(this), false); this.element.addEventListener("dragover", this._ondragover.bind(this), false); this.element.addEventListener("dragleave", this._ondragleave.bind(this), false); this.element.addEventListener("drop", this._ondrop.bind(this), false); this.element.addEventListener("dragend", this._ondragend.bind(this), false); this.element.addEventListener("keydown", this._onkeydown.bind(this), false); TreeOutline.call(this, this.element); this._includeRootDOMNode = !omitRootDOMNode; this._selectEnabled = selectEnabled; this._showInElementsPanelEnabled = showInElementsPanelEnabled; this._rootDOMNode = null; this._selectDOMNode = null; this._eventSupport = new WebInspector.Object(); this._visible = false; this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true); this._contextMenuCallback = contextMenuCallback; this._setPseudoClassCallback = setPseudoClassCallback; this._createNodeDecorators(); } WebInspector.ElementsTreeOutline.Events = { SelectedNodeChanged: "SelectedNodeChanged" } WebInspector.ElementsTreeOutline.MappedCharToEntity = { "\u00a0": "nbsp", "\u2002": "ensp", "\u2003": "emsp", "\u2009": "thinsp", "\u200b": "#8203", "\u200c": "zwnj", "\u200d": "zwj", "\u200e": "lrm", "\u200f": "rlm", "\u202a": "#8234", "\u202b": "#8235", "\u202c": "#8236", "\u202d": "#8237", "\u202e": "#8238" } WebInspector.ElementsTreeOutline.prototype = { _createNodeDecorators: function() { this._nodeDecorators = []; this._nodeDecorators.push(new WebInspector.ElementsTreeOutline.PseudoStateDecorator()); }, wireToDomAgent: function() { this._elementsTreeUpdater = new WebInspector.ElementsTreeUpdater(this); }, setVisible: function(visible) { this._visible = visible; if (!this._visible) return; this._updateModifiedNodes(); if (this._selectedDOMNode) this._revealAndSelectNode(this._selectedDOMNode, false); }, addEventListener: function(eventType, listener, thisObject) { this._eventSupport.addEventListener(eventType, listener, thisObject); }, removeEventListener: function(eventType, listener, thisObject) { this._eventSupport.removeEventListener(eventType, listener, thisObject); }, get rootDOMNode() { return this._rootDOMNode; }, set rootDOMNode(x) { if (this._rootDOMNode === x) return; this._rootDOMNode = x; this._isXMLMimeType = x && x.isXMLNode(); this.update(); }, get isXMLMimeType() { return this._isXMLMimeType; }, selectedDOMNode: function() { return this._selectedDOMNode; }, selectDOMNode: function(node, focus) { if (this._selectedDOMNode === node) { this._revealAndSelectNode(node, !focus); return; } this._selectedDOMNode = node; this._revealAndSelectNode(node, !focus); if (this._selectedDOMNode === node) this._selectedNodeChanged(); }, update: function() { var selectedNode = this.selectedTreeElement ? this.selectedTreeElement.representedObject : null; this.removeChildren(); if (!this.rootDOMNode) return; var treeElement; if (this._includeRootDOMNode) { treeElement = new WebInspector.ElementsTreeElement(this.rootDOMNode); treeElement.selectable = this._selectEnabled; this.appendChild(treeElement); } else { var node = this.rootDOMNode.firstChild; while (node) { treeElement = new WebInspector.ElementsTreeElement(node); treeElement.selectable = this._selectEnabled; this.appendChild(treeElement); node = node.nextSibling; } } if (selectedNode) this._revealAndSelectNode(selectedNode, true); }, updateSelection: function() { if (!this.selectedTreeElement) return; var element = this.treeOutline.selectedTreeElement; element.updateSelection(); }, updateOpenCloseTags: function(node) { var treeElement = this.findTreeElement(node); if (treeElement) treeElement.updateTitle(); var children = treeElement.children; var closingTagElement = children[children.length - 1]; if (closingTagElement && closingTagElement._elementCloseTag) closingTagElement.updateTitle(); }, _selectedNodeChanged: function() { this._eventSupport.dispatchEventToListeners(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._selectedDOMNode); }, findTreeElement: function(node) { function isAncestorNode(ancestor, node) { return ancestor.isAncestor(node); } function parentNode(node) { return node.parentNode; } var treeElement = TreeOutline.prototype.findTreeElement.call(this, node, isAncestorNode, parentNode); if (!treeElement && node.nodeType() === Node.TEXT_NODE) { treeElement = TreeOutline.prototype.findTreeElement.call(this, node.parentNode, isAncestorNode, parentNode); } return treeElement; }, createTreeElementFor: function(node) { var treeElement = this.findTreeElement(node); if (treeElement) return treeElement; if (!node.parentNode) return null; treeElement = this.createTreeElementFor(node.parentNode); if (treeElement && treeElement.showChild(node.index)) return treeElement.children[node.index]; return null; }, set suppressRevealAndSelect(x) { if (this._suppressRevealAndSelect === x) return; this._suppressRevealAndSelect = x; }, _revealAndSelectNode: function(node, omitFocus) { if (!node || this._suppressRevealAndSelect) return; var treeElement = this.createTreeElementFor(node); if (!treeElement) return; treeElement.revealAndSelect(omitFocus); }, _treeElementFromEvent: function(event) { var scrollContainer = this.element.parentElement; var x = scrollContainer.totalOffsetLeft() + scrollContainer.offsetWidth - 36; var y = event.pageY; var elementUnderMouse = this.treeElementFromPoint(x, y); var elementAboveMouse = this.treeElementFromPoint(x, y - 2); var element; if (elementUnderMouse === elementAboveMouse) element = elementUnderMouse; else element = this.treeElementFromPoint(x, y + 2); return element; }, _onmousedown: function(event) { var element = this._treeElementFromEvent(event); if (!element || element.isEventWithinDisclosureTriangle(event)) return; element.select(); }, _onmousemove: function(event) { var element = this._treeElementFromEvent(event); if (element && this._previousHoveredElement === element) return; if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; delete this._previousHoveredElement; } if (element) { element.hovered = true; this._previousHoveredElement = element; } WebInspector.domAgent.highlightDOMNode(element ? element.representedObject.id : 0); }, _onmouseout: function(event) { var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.element)) return; if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; delete this._previousHoveredElement; } WebInspector.domAgent.hideDOMNodeHighlight(); }, _ondragstart: function(event) { if (!window.getSelection().isCollapsed) return false; if (event.target.nodeName === "A") return false; var treeElement = this._treeElementFromEvent(event); if (!treeElement) return false; if (!this._isValidDragSourceOrTarget(treeElement)) return false; if (treeElement.representedObject.nodeName() === "BODY" || treeElement.representedObject.nodeName() === "HEAD") return false; event.dataTransfer.setData("text/plain", treeElement.listItemElement.textContent); event.dataTransfer.effectAllowed = "copyMove"; this._treeElementBeingDragged = treeElement; WebInspector.domAgent.hideDOMNodeHighlight(); return true; }, _ondragover: function(event) { if (!this._treeElementBeingDragged) return false; var treeElement = this._treeElementFromEvent(event); if (!this._isValidDragSourceOrTarget(treeElement)) return false; var node = treeElement.representedObject; while (node) { if (node === this._treeElementBeingDragged.representedObject) return false; node = node.parentNode; } treeElement.updateSelection(); treeElement.listItemElement.addStyleClass("elements-drag-over"); this._dragOverTreeElement = treeElement; event.preventDefault(); event.dataTransfer.dropEffect = 'move'; return false; }, _ondragleave: function(event) { this._clearDragOverTreeElementMarker(); event.preventDefault(); return false; }, _isValidDragSourceOrTarget: function(treeElement) { if (!treeElement) return false; var node = treeElement.representedObject; if (!(node instanceof WebInspector.DOMNode)) return false; if (!node.parentNode || node.parentNode.nodeType() !== Node.ELEMENT_NODE) return false; return true; }, _ondrop: function(event) { event.preventDefault(); var treeElement = this._treeElementFromEvent(event); if (treeElement) this._doMove(treeElement); }, _doMove: function(treeElement) { if (!this._treeElementBeingDragged) return; var parentNode; var anchorNode; if (treeElement._elementCloseTag) { parentNode = treeElement.representedObject; } else { var dragTargetNode = treeElement.representedObject; parentNode = dragTargetNode.parentNode; anchorNode = dragTargetNode; } var wasExpanded = this._treeElementBeingDragged.expanded; this._treeElementBeingDragged.representedObject.moveTo(parentNode, anchorNode, this._selectNodeAfterEdit.bind(this, null, wasExpanded)); delete this._treeElementBeingDragged; }, _ondragend: function(event) { event.preventDefault(); this._clearDragOverTreeElementMarker(); delete this._treeElementBeingDragged; }, _clearDragOverTreeElementMarker: function() { if (this._dragOverTreeElement) { this._dragOverTreeElement.updateSelection(); this._dragOverTreeElement.listItemElement.removeStyleClass("elements-drag-over"); delete this._dragOverTreeElement; } }, _onkeydown: function(event) { var keyboardEvent = (event); var node = this.selectedDOMNode(); var treeElement = this.getCachedTreeElement(node); if (!treeElement) return; if (!treeElement._editing && WebInspector.KeyboardShortcut.hasNoModifiers(keyboardEvent) && keyboardEvent.keyCode === WebInspector.KeyboardShortcut.Keys.H.code) { WebInspector.cssModel.toggleInlineVisibility(node.id); event.consume(true); return; } }, _contextMenuEventFired: function(event) { if (!this._showInElementsPanelEnabled) return; var treeElement = this._treeElementFromEvent(event); if (!treeElement) return; function focusElement() { WebInspector.showPanel("elements"); WebInspector.domAgent.inspectElement(treeElement.representedObject.id); } var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Reveal in Elements Panel"), focusElement.bind(this)); contextMenu.show(); }, populateContextMenu: function(contextMenu, event) { var treeElement = this._treeElementFromEvent(event); if (!treeElement) return false; var isTag = treeElement.representedObject.nodeType() === Node.ELEMENT_NODE; var textNode = event.target.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (textNode && textNode.hasStyleClass("bogus")) textNode = null; var commentNode = event.target.enclosingNodeOrSelfWithClass("webkit-html-comment"); contextMenu.appendApplicableItems(event.target); if (textNode) { contextMenu.appendSeparator(); treeElement._populateTextContextMenu(contextMenu, textNode); } else if (isTag) { contextMenu.appendSeparator(); treeElement._populateTagContextMenu(contextMenu, event); } else if (commentNode) { contextMenu.appendSeparator(); treeElement._populateNodeContextMenu(contextMenu, textNode); } }, adjustCollapsedRange: function() { }, _updateModifiedNodes: function() { if (this._elementsTreeUpdater) this._elementsTreeUpdater._updateModifiedNodes(); }, _populateContextMenu: function(contextMenu, node) { if (this._contextMenuCallback) this._contextMenuCallback(contextMenu, node); }, handleShortcut: function(event) { var node = this.selectedDOMNode(); var treeElement = this.getCachedTreeElement(node); if (!node || !treeElement) return; if (event.keyIdentifier === "F2") { this._toggleEditAsHTML(node); event.handled = true; return; } if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) && node.parentNode) { if (event.keyIdentifier === "Up" && node.previousSibling) { node.moveTo(node.parentNode, node.previousSibling, this._selectNodeAfterEdit.bind(this, null, treeElement.expanded)); event.handled = true; return; } if (event.keyIdentifier === "Down" && node.nextSibling) { node.moveTo(node.parentNode, node.nextSibling.nextSibling, this._selectNodeAfterEdit.bind(this, null, treeElement.expanded)); event.handled = true; return; } } }, _toggleEditAsHTML: function(node) { var treeElement = this.getCachedTreeElement(node); if (!treeElement) return; if (treeElement._editing && treeElement._htmlEditElement && WebInspector.isBeingEdited(treeElement._htmlEditElement)) treeElement._editing.commit(); else treeElement._editAsHTML(); }, _selectNodeAfterEdit: function(fallbackNode, wasExpanded, error, nodeId) { if (error) return; this._updateModifiedNodes(); var newNode = WebInspector.domAgent.nodeForId(nodeId) || fallbackNode; if (!newNode) return; this.selectDOMNode(newNode, true); var newTreeItem = this.findTreeElement(newNode); if (wasExpanded) { if (newTreeItem) newTreeItem.expand(); } return newTreeItem; }, __proto__: TreeOutline.prototype } WebInspector.ElementsTreeOutline.ElementDecorator = function() { } WebInspector.ElementsTreeOutline.ElementDecorator.prototype = { decorate: function(node) { }, decorateAncestor: function(node) { } } WebInspector.ElementsTreeOutline.PseudoStateDecorator = function() { WebInspector.ElementsTreeOutline.ElementDecorator.call(this); } WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName = "pseudoState"; WebInspector.ElementsTreeOutline.PseudoStateDecorator.prototype = { decorate: function(node) { if (node.nodeType() !== Node.ELEMENT_NODE) return null; var propertyValue = node.getUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName); if (!propertyValue) return null; return WebInspector.UIString("Element state: %s", ":" + propertyValue.join(", :")); }, decorateAncestor: function(node) { if (node.nodeType() !== Node.ELEMENT_NODE) return null; var descendantCount = node.descendantUserPropertyCount(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName); if (!descendantCount) return null; if (descendantCount === 1) return WebInspector.UIString("%d descendant with forced state", descendantCount); return WebInspector.UIString("%d descendants with forced state", descendantCount); }, __proto__: WebInspector.ElementsTreeOutline.ElementDecorator.prototype } WebInspector.ElementsTreeElement = function(node, elementCloseTag) { this._elementCloseTag = elementCloseTag; var hasChildrenOverride = !elementCloseTag && node.hasChildNodes() && !this._showInlineText(node); TreeElement.call(this, "", node, hasChildrenOverride); if (this.representedObject.nodeType() == Node.ELEMENT_NODE && !elementCloseTag) this._canAddAttributes = true; this._searchQuery = null; this._expandedChildrenLimit = WebInspector.ElementsTreeElement.InitialChildrenLimit; } WebInspector.ElementsTreeElement.InitialChildrenLimit = 500; WebInspector.ElementsTreeElement.ForbiddenClosingTagElements = [ "area", "base", "basefont", "br", "canvas", "col", "command", "embed", "frame", "hr", "img", "input", "isindex", "keygen", "link", "meta", "param", "source" ].keySet(); WebInspector.ElementsTreeElement.EditTagBlacklist = [ "html", "head", "body" ].keySet(); WebInspector.ElementsTreeElement.prototype = { highlightSearchResults: function(searchQuery) { if (this._searchQuery !== searchQuery) { this._updateSearchHighlight(false); delete this._highlightResult; } this._searchQuery = searchQuery; this._searchHighlightsVisible = true; this.updateTitle(true); }, hideSearchHighlights: function() { delete this._searchHighlightsVisible; this._updateSearchHighlight(false); }, _updateSearchHighlight: function(show) { if (!this._highlightResult) return; function updateEntryShow(entry) { switch (entry.type) { case "added": entry.parent.insertBefore(entry.node, entry.nextSibling); break; case "changed": entry.node.textContent = entry.newText; break; } } function updateEntryHide(entry) { switch (entry.type) { case "added": if (entry.node.parentElement) entry.node.parentElement.removeChild(entry.node); break; case "changed": entry.node.textContent = entry.oldText; break; } } if (show) { for (var i = 0, size = this._highlightResult.length; i < size; ++i) updateEntryShow(this._highlightResult[i]); } else { for (var i = (this._highlightResult.length - 1); i >= 0; --i) updateEntryHide(this._highlightResult[i]); } }, get hovered() { return this._hovered; }, set hovered(x) { if (this._hovered === x) return; this._hovered = x; if (this.listItemElement) { if (x) { this.updateSelection(); this.listItemElement.addStyleClass("hovered"); } else { this.listItemElement.removeStyleClass("hovered"); } } }, get expandedChildrenLimit() { return this._expandedChildrenLimit; }, set expandedChildrenLimit(x) { if (this._expandedChildrenLimit === x) return; this._expandedChildrenLimit = x; if (this.treeOutline && !this._updateChildrenInProgress) this._updateChildren(true); }, get expandedChildCount() { var count = this.children.length; if (count && this.children[count - 1]._elementCloseTag) count--; if (count && this.children[count - 1].expandAllButton) count--; return count; }, showChild: function(index) { if (this._elementCloseTag) return; if (index >= this.expandedChildrenLimit) { this._expandedChildrenLimit = index + 1; this._updateChildren(true); } return this.expandedChildCount > index; }, updateSelection: function() { var listItemElement = this.listItemElement; if (!listItemElement) return; if (!this._readyToUpdateSelection) { if (document.body.offsetWidth > 0) this._readyToUpdateSelection = true; else { return; } } if (!this.selectionElement) { this.selectionElement = document.createElement("div"); this.selectionElement.className = "selection selected"; listItemElement.insertBefore(this.selectionElement, listItemElement.firstChild); } this.selectionElement.style.height = listItemElement.offsetHeight + "px"; }, onattach: function() { if (this._hovered) { this.updateSelection(); this.listItemElement.addStyleClass("hovered"); } this.updateTitle(); this._preventFollowingLinksOnDoubleClick(); this.listItemElement.draggable = true; }, _preventFollowingLinksOnDoubleClick: function() { var links = this.listItemElement.querySelectorAll("li > .webkit-html-tag > .webkit-html-attribute > .webkit-html-external-link, li > .webkit-html-tag > .webkit-html-attribute > .webkit-html-resource-link"); if (!links) return; for (var i = 0; i < links.length; ++i) links[i].preventFollowOnDoubleClick = true; }, onpopulate: function() { if (this.children.length || this._showInlineText(this.representedObject) || this._elementCloseTag) return; this.updateChildren(); }, updateChildren: function(fullRefresh) { if (this._elementCloseTag) return; this.representedObject.getChildNodes(this._updateChildren.bind(this, fullRefresh)); }, insertChildElement: function(child, index, closingTag) { var newElement = new WebInspector.ElementsTreeElement(child, closingTag); newElement.selectable = this.treeOutline._selectEnabled; this.insertChild(newElement, index); return newElement; }, moveChild: function(child, targetIndex) { var wasSelected = child.selected; this.removeChild(child); this.insertChild(child, targetIndex); if (wasSelected) child.select(); }, _updateChildren: function(fullRefresh) { if (this._updateChildrenInProgress || !this.treeOutline._visible) return; this._updateChildrenInProgress = true; var selectedNode = this.treeOutline.selectedDOMNode(); var originalScrollTop = 0; if (fullRefresh) { var treeOutlineContainerElement = this.treeOutline.element.parentNode; originalScrollTop = treeOutlineContainerElement.scrollTop; var selectedTreeElement = this.treeOutline.selectedTreeElement; if (selectedTreeElement && selectedTreeElement.hasAncestor(this)) this.select(); this.removeChildren(); } var treeElement = this; var treeChildIndex = 0; var elementToSelect; function updateChildrenOfNode(node) { var treeOutline = treeElement.treeOutline; var child = node.firstChild; while (child) { var currentTreeElement = treeElement.children[treeChildIndex]; if (!currentTreeElement || currentTreeElement.representedObject !== child) { var existingTreeElement = null; for (var i = (treeChildIndex + 1), size = treeElement.expandedChildCount; i < size; ++i) { if (treeElement.children[i].representedObject === child) { existingTreeElement = treeElement.children[i]; break; } } if (existingTreeElement && existingTreeElement.parent === treeElement) { treeElement.moveChild(existingTreeElement, treeChildIndex); } else { if (treeChildIndex < treeElement.expandedChildrenLimit) { var newElement = treeElement.insertChildElement(child, treeChildIndex); if (child === selectedNode) elementToSelect = newElement; if (treeElement.expandedChildCount > treeElement.expandedChildrenLimit) treeElement.expandedChildrenLimit++; } } } child = child.nextSibling; ++treeChildIndex; } } for (var i = (this.children.length - 1); i >= 0; --i) { var currentChild = this.children[i]; var currentNode = currentChild.representedObject; var currentParentNode = currentNode.parentNode; if (currentParentNode === this.representedObject) continue; var selectedTreeElement = this.treeOutline.selectedTreeElement; if (selectedTreeElement && (selectedTreeElement === currentChild || selectedTreeElement.hasAncestor(currentChild))) this.select(); this.removeChildAtIndex(i); } updateChildrenOfNode(this.representedObject); this.adjustCollapsedRange(); var lastChild = this.children[this.children.length - 1]; if (this.representedObject.nodeType() == Node.ELEMENT_NODE && (!lastChild || !lastChild._elementCloseTag)) this.insertChildElement(this.representedObject, this.children.length, true); if (fullRefresh && elementToSelect) { elementToSelect.select(); if (treeOutlineContainerElement && originalScrollTop <= treeOutlineContainerElement.scrollHeight) treeOutlineContainerElement.scrollTop = originalScrollTop; } delete this._updateChildrenInProgress; }, adjustCollapsedRange: function() { if (this.expandAllButtonElement && this.expandAllButtonElement.__treeElement.parent) this.removeChild(this.expandAllButtonElement.__treeElement); const node = this.representedObject; if (!node.children) return; const childNodeCount = node.children.length; for (var i = this.expandedChildCount, limit = Math.min(this.expandedChildrenLimit, childNodeCount); i < limit; ++i) this.insertChildElement(node.children[i], i); const expandedChildCount = this.expandedChildCount; if (childNodeCount > this.expandedChildCount) { var targetButtonIndex = expandedChildCount; if (!this.expandAllButtonElement) { var button = document.createElement("button"); button.className = "show-all-nodes"; button.value = ""; var item = new TreeElement(button, null, false); item.selectable = false; item.expandAllButton = true; this.insertChild(item, targetButtonIndex); this.expandAllButtonElement = item.listItemElement.firstChild; this.expandAllButtonElement.__treeElement = item; this.expandAllButtonElement.addEventListener("click", this.handleLoadAllChildren.bind(this), false); } else if (!this.expandAllButtonElement.__treeElement.parent) this.insertChild(this.expandAllButtonElement.__treeElement, targetButtonIndex); this.expandAllButtonElement.textContent = WebInspector.UIString("Show All Nodes (%d More)", childNodeCount - expandedChildCount); } else if (this.expandAllButtonElement) delete this.expandAllButtonElement; }, handleLoadAllChildren: function() { this.expandedChildrenLimit = Math.max(this.representedObject._childNodeCount, this.expandedChildrenLimit + WebInspector.ElementsTreeElement.InitialChildrenLimit); }, onexpand: function() { if (this._elementCloseTag) return; this.updateTitle(); this.treeOutline.updateSelection(); }, oncollapse: function() { if (this._elementCloseTag) return; this.updateTitle(); this.treeOutline.updateSelection(); }, onreveal: function() { if (this.listItemElement) { var tagSpans = this.listItemElement.getElementsByClassName("webkit-html-tag-name"); if (tagSpans.length) tagSpans[0].scrollIntoViewIfNeeded(false); else this.listItemElement.scrollIntoViewIfNeeded(false); } }, onselect: function(selectedByUser) { this.treeOutline.suppressRevealAndSelect = true; this.treeOutline.selectDOMNode(this.representedObject, selectedByUser); if (selectedByUser) WebInspector.domAgent.highlightDOMNode(this.representedObject.id); this.updateSelection(); this.treeOutline.suppressRevealAndSelect = false; return true; }, ondelete: function() { var startTagTreeElement = this.treeOutline.findTreeElement(this.representedObject); startTagTreeElement ? startTagTreeElement.remove() : this.remove(); return true; }, onenter: function() { if (this._editing) return false; this._startEditing(); return true; }, selectOnMouseDown: function(event) { TreeElement.prototype.selectOnMouseDown.call(this, event); if (this._editing) return; if (this.treeOutline._showInElementsPanelEnabled) { WebInspector.showPanel("elements"); this.treeOutline.selectDOMNode(this.representedObject, true); } if (event.detail >= 2) event.preventDefault(); }, ondblclick: function(event) { if (this._editing || this._elementCloseTag) return; if (this._startEditingTarget(event.target)) return; if (this.hasChildren && !this.expanded) this.expand(); }, _insertInLastAttributePosition: function(tag, node) { if (tag.getElementsByClassName("webkit-html-attribute").length > 0) tag.insertBefore(node, tag.lastChild); else { var nodeName = tag.textContent.match(/^<(.*?)>$/)[1]; tag.textContent = ''; tag.appendChild(document.createTextNode('<'+nodeName)); tag.appendChild(node); tag.appendChild(document.createTextNode('>')); } this.updateSelection(); }, _startEditingTarget: function(eventTarget) { if (this.treeOutline.selectedDOMNode() != this.representedObject) return; if (this.representedObject.nodeType() != Node.ELEMENT_NODE && this.representedObject.nodeType() != Node.TEXT_NODE) return false; var textNode = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (textNode) return this._startEditingTextNode(textNode); var attribute = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-attribute"); if (attribute) return this._startEditingAttribute(attribute, eventTarget); var tagName = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-tag-name"); if (tagName) return this._startEditingTagName(tagName); var newAttribute = eventTarget.enclosingNodeOrSelfWithClass("add-attribute"); if (newAttribute) return this._addNewAttribute(); return false; }, _populateTagContextMenu: function(contextMenu, event) { var attribute = event.target.enclosingNodeOrSelfWithClass("webkit-html-attribute"); var newAttribute = event.target.enclosingNodeOrSelfWithClass("add-attribute"); var treeElement = this._elementCloseTag ? this.treeOutline.findTreeElement(this.representedObject) : this; contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Add attribute" : "Add Attribute"), this._addNewAttribute.bind(treeElement)); if (attribute && !newAttribute) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Edit attribute" : "Edit Attribute"), this._startEditingAttribute.bind(this, attribute, event.target)); contextMenu.appendSeparator(); if (this.treeOutline._setPseudoClassCallback) { var pseudoSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Force element state" : "Force Element State")); this._populateForcedPseudoStateItems(pseudoSubMenu); contextMenu.appendSeparator(); } this._populateNodeContextMenu(contextMenu); this.treeOutline._populateContextMenu(contextMenu, this.representedObject); contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Scroll into view" : "Scroll Into View"), this._scrollIntoView.bind(this)); }, _populateForcedPseudoStateItems: function(subMenu) { const pseudoClasses = ["active", "hover", "focus", "visited"]; var node = this.representedObject; var forcedPseudoState = (node ? node.getUserProperty("pseudoState") : null) || []; for (var i = 0; i < pseudoClasses.length; ++i) { var pseudoClassForced = forcedPseudoState.indexOf(pseudoClasses[i]) >= 0; subMenu.appendCheckboxItem(":" + pseudoClasses[i], this.treeOutline._setPseudoClassCallback.bind(null, node.id, pseudoClasses[i], !pseudoClassForced), pseudoClassForced, false); } }, _populateTextContextMenu: function(contextMenu, textNode) { contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Edit text" : "Edit Text"), this._startEditingTextNode.bind(this, textNode)); this._populateNodeContextMenu(contextMenu); }, _populateNodeContextMenu: function(contextMenu) { contextMenu.appendItem(WebInspector.UIString("Edit as HTML"), this._editAsHTML.bind(this)); contextMenu.appendItem(WebInspector.UIString("Copy as HTML"), this._copyHTML.bind(this)); contextMenu.appendItem(WebInspector.UIString("Copy XPath"), this._copyXPath.bind(this)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Delete node" : "Delete Node"), this.remove.bind(this)); }, _startEditing: function() { if (this.treeOutline.selectedDOMNode() !== this.representedObject) return; var listItem = this._listItemNode; if (this._canAddAttributes) { var attribute = listItem.getElementsByClassName("webkit-html-attribute")[0]; if (attribute) return this._startEditingAttribute(attribute, attribute.getElementsByClassName("webkit-html-attribute-value")[0]); return this._addNewAttribute(); } if (this.representedObject.nodeType() === Node.TEXT_NODE) { var textNode = listItem.getElementsByClassName("webkit-html-text-node")[0]; if (textNode) return this._startEditingTextNode(textNode); return; } }, _addNewAttribute: function() { var container = document.createElement("span"); this._buildAttributeDOM(container, " ", ""); var attr = container.firstChild; attr.style.marginLeft = "2px"; attr.style.marginRight = "2px"; var tag = this.listItemElement.getElementsByClassName("webkit-html-tag")[0]; this._insertInLastAttributePosition(tag, attr); attr.scrollIntoViewIfNeeded(true); return this._startEditingAttribute(attr, attr); }, _triggerEditAttribute: function(attributeName) { var attributeElements = this.listItemElement.getElementsByClassName("webkit-html-attribute-name"); for (var i = 0, len = attributeElements.length; i < len; ++i) { if (attributeElements[i].textContent === attributeName) { for (var elem = attributeElements[i].nextSibling; elem; elem = elem.nextSibling) { if (elem.nodeType !== Node.ELEMENT_NODE) continue; if (elem.hasStyleClass("webkit-html-attribute-value")) return this._startEditingAttribute(elem.parentNode, elem); } } } }, _startEditingAttribute: function(attribute, elementForSelection) { if (WebInspector.isBeingEdited(attribute)) return true; var attributeNameElement = attribute.getElementsByClassName("webkit-html-attribute-name")[0]; if (!attributeNameElement) return false; var attributeName = attributeNameElement.textContent; function removeZeroWidthSpaceRecursive(node) { if (node.nodeType === Node.TEXT_NODE) { node.nodeValue = node.nodeValue.replace(/\u200B/g, ""); return; } if (node.nodeType !== Node.ELEMENT_NODE) return; for (var child = node.firstChild; child; child = child.nextSibling) removeZeroWidthSpaceRecursive(child); } removeZeroWidthSpaceRecursive(attribute); var config = new WebInspector.EditingConfig(this._attributeEditingCommitted.bind(this), this._editingCancelled.bind(this), attributeName); function handleKeyDownEvents(event) { var isMetaOrCtrl = WebInspector.isMac() ? event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey : event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey; if (isEnterKey(event) && (event.isMetaOrCtrlForTest || !config.multiline || isMetaOrCtrl)) return "commit"; else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B") return "cancel"; else if (event.keyIdentifier === "U+0009") return "move-" + (event.shiftKey ? "backward" : "forward"); else { WebInspector.handleElementValueModifications(event, attribute); return ""; } } config.customFinishHandler = handleKeyDownEvents.bind(this); this._editing = WebInspector.startEditing(attribute, config); window.getSelection().setBaseAndExtent(elementForSelection, 0, elementForSelection, 1); return true; }, _startEditingTextNode: function(textNodeElement) { if (WebInspector.isBeingEdited(textNodeElement)) return true; var textNode = this.representedObject; if (textNode.nodeType() === Node.ELEMENT_NODE && textNode.firstChild) textNode = textNode.firstChild; var container = textNodeElement.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (container) container.textContent = textNode.nodeValue(); var config = new WebInspector.EditingConfig(this._textNodeEditingCommitted.bind(this, textNode), this._editingCancelled.bind(this)); this._editing = WebInspector.startEditing(textNodeElement, config); window.getSelection().setBaseAndExtent(textNodeElement, 0, textNodeElement, 1); return true; }, _startEditingTagName: function(tagNameElement) { if (!tagNameElement) { tagNameElement = this.listItemElement.getElementsByClassName("webkit-html-tag-name")[0]; if (!tagNameElement) return false; } var tagName = tagNameElement.textContent; if (WebInspector.ElementsTreeElement.EditTagBlacklist[tagName.toLowerCase()]) return false; if (WebInspector.isBeingEdited(tagNameElement)) return true; var closingTagElement = this._distinctClosingTagElement(); function keyupListener(event) { if (closingTagElement) closingTagElement.textContent = "</" + tagNameElement.textContent + ">"; } function editingComitted(element, newTagName) { tagNameElement.removeEventListener('keyup', keyupListener, false); this._tagNameEditingCommitted.apply(this, arguments); } function editingCancelled() { tagNameElement.removeEventListener('keyup', keyupListener, false); this._editingCancelled.apply(this, arguments); } tagNameElement.addEventListener('keyup', keyupListener, false); var config = new WebInspector.EditingConfig(editingComitted.bind(this), editingCancelled.bind(this), tagName); this._editing = WebInspector.startEditing(tagNameElement, config); window.getSelection().setBaseAndExtent(tagNameElement, 0, tagNameElement, 1); return true; }, _startEditingAsHTML: function(commitCallback, error, initialValue) { if (error) return; if (this._htmlEditElement && WebInspector.isBeingEdited(this._htmlEditElement)) return; function consume(event) { if (event.eventPhase === Event.AT_TARGET) event.consume(true); } initialValue = this._convertWhitespaceToEntities(initialValue); this._htmlEditElement = document.createElement("div"); this._htmlEditElement.className = "source-code elements-tree-editor"; this._htmlEditElement.textContent = initialValue; var child = this.listItemElement.firstChild; while (child) { child.style.display = "none"; child = child.nextSibling; } if (this._childrenListNode) this._childrenListNode.style.display = "none"; this.listItemElement.appendChild(this._htmlEditElement); this.treeOutline.childrenListElement.parentElement.addEventListener("mousedown", consume, false); this.updateSelection(); function commit() { commitCallback(initialValue, this._htmlEditElement.textContent); dispose.call(this); } function dispose() { delete this._editing; this.listItemElement.removeChild(this._htmlEditElement); delete this._htmlEditElement; if (this._childrenListNode) this._childrenListNode.style.removeProperty("display"); var child = this.listItemElement.firstChild; while (child) { child.style.removeProperty("display"); child = child.nextSibling; } this.treeOutline.childrenListElement.parentElement.removeEventListener("mousedown", consume, false); this.updateSelection(); } var config = new WebInspector.EditingConfig(commit.bind(this), dispose.bind(this)); config.setMultiline(true); this._editing = WebInspector.startEditing(this._htmlEditElement, config); }, _attributeEditingCommitted: function(element, newText, oldText, attributeName, moveDirection) { delete this._editing; var treeOutline = this.treeOutline; function moveToNextAttributeIfNeeded(error) { if (error) this._editingCancelled(element, attributeName); if (!moveDirection) return; treeOutline._updateModifiedNodes(); var attributes = this.representedObject.attributes(); for (var i = 0; i < attributes.length; ++i) { if (attributes[i].name !== attributeName) continue; if (moveDirection === "backward") { if (i === 0) this._startEditingTagName(); else this._triggerEditAttribute(attributes[i - 1].name); } else { if (i === attributes.length - 1) this._addNewAttribute(); else this._triggerEditAttribute(attributes[i + 1].name); } return; } if (moveDirection === "backward") { if (newText === " ") { if (attributes.length > 0) this._triggerEditAttribute(attributes[attributes.length - 1].name); } else { if (attributes.length > 1) this._triggerEditAttribute(attributes[attributes.length - 2].name); } } else if (moveDirection === "forward") { if (!/^\s*$/.test(newText)) this._addNewAttribute(); else this._startEditingTagName(); } } if (oldText !== newText) this.representedObject.setAttribute(attributeName, newText, moveToNextAttributeIfNeeded.bind(this)); else moveToNextAttributeIfNeeded.call(this); }, _tagNameEditingCommitted: function(element, newText, oldText, tagName, moveDirection) { delete this._editing; var self = this; function cancel() { var closingTagElement = self._distinctClosingTagElement(); if (closingTagElement) closingTagElement.textContent = "</" + tagName + ">"; self._editingCancelled(element, tagName); moveToNextAttributeIfNeeded.call(self); } function moveToNextAttributeIfNeeded() { if (moveDirection !== "forward") { this._addNewAttribute(); return; } var attributes = this.representedObject.attributes(); if (attributes.length > 0) this._triggerEditAttribute(attributes[0].name); else this._addNewAttribute(); } newText = newText.trim(); if (newText === oldText) { cancel(); return; } var treeOutline = this.treeOutline; var wasExpanded = this.expanded; function changeTagNameCallback(error, nodeId) { if (error || !nodeId) { cancel(); return; } var newTreeItem = treeOutline._selectNodeAfterEdit(null, wasExpanded, error, nodeId); moveToNextAttributeIfNeeded.call(newTreeItem); } this.representedObject.setNodeName(newText, changeTagNameCallback); }, _textNodeEditingCommitted: function(textNode, element, newText) { delete this._editing; function callback() { this.updateTitle(); } textNode.setNodeValue(newText, callback.bind(this)); }, _editingCancelled: function(element, context) { delete this._editing; this.updateTitle(); }, _distinctClosingTagElement: function() { if (this.expanded) { var closers = this._childrenListNode.querySelectorAll(".close"); return closers[closers.length-1]; } var tags = this.listItemElement.getElementsByClassName("webkit-html-tag"); return (tags.length === 1 ? null : tags[tags.length-1]); }, updateTitle: function(onlySearchQueryChanged) { if (this._editing) return; if (onlySearchQueryChanged) { if (this._highlightResult) this._updateSearchHighlight(false); } else { var highlightElement = document.createElement("span"); highlightElement.className = "highlight"; highlightElement.appendChild(this._nodeTitleInfo(WebInspector.linkifyURLAsNode).titleDOM); this.title = highlightElement; this._updateDecorations(); delete this._highlightResult; } delete this.selectionElement; if (this.selected) this.updateSelection(); this._preventFollowingLinksOnDoubleClick(); this._highlightSearchResults(); }, _createDecoratorElement: function() { var node = this.representedObject; var decoratorMessages = []; var parentDecoratorMessages = []; for (var i = 0; i < this.treeOutline._nodeDecorators.length; ++i) { var decorator = this.treeOutline._nodeDecorators[i]; var message = decorator.decorate(node); if (message) { decoratorMessages.push(message); continue; } if (this.expanded || this._elementCloseTag) continue; message = decorator.decorateAncestor(node); if (message) parentDecoratorMessages.push(message) } if (!decoratorMessages.length && !parentDecoratorMessages.length) return null; var decoratorElement = document.createElement("div"); decoratorElement.addStyleClass("elements-gutter-decoration"); if (!decoratorMessages.length) decoratorElement.addStyleClass("elements-has-decorated-children"); decoratorElement.title = decoratorMessages.concat(parentDecoratorMessages).join("\n"); return decoratorElement; }, _updateDecorations: function() { if (this._decoratorElement && this._decoratorElement.parentElement) this._decoratorElement.parentElement.removeChild(this._decoratorElement); this._decoratorElement = this._createDecoratorElement(); if (this._decoratorElement && this.listItemElement) this.listItemElement.insertBefore(this._decoratorElement, this.listItemElement.firstChild); }, _buildAttributeDOM: function(parentElement, name, value, node, linkify) { var hasText = (value.length > 0); var attrSpanElement = parentElement.createChild("span", "webkit-html-attribute"); var attrNameElement = attrSpanElement.createChild("span", "webkit-html-attribute-name"); attrNameElement.textContent = name; if (hasText) attrSpanElement.appendChild(document.createTextNode("=\u200B\"")); if (linkify && (name === "src" || name === "href")) { var rewrittenHref = node.resolveURL(value); value = value.replace(/([\/;:\)\]\}])/g, "$1\u200B"); if (rewrittenHref === null) { var attrValueElement = attrSpanElement.createChild("span", "webkit-html-attribute-value"); attrValueElement.textContent = value; } else { if (value.startsWith("data:")) value = value.trimMiddle(60); attrSpanElement.appendChild(linkify(rewrittenHref, value, "webkit-html-attribute-value", node.nodeName().toLowerCase() === "a")); } } else { value = value.replace(/([\/;:\)\]\}])/g, "$1\u200B"); var attrValueElement = attrSpanElement.createChild("span", "webkit-html-attribute-value"); attrValueElement.textContent = value; } if (hasText) attrSpanElement.appendChild(document.createTextNode("\"")); }, _buildTagDOM: function(parentElement, tagName, isClosingTag, isDistinctTreeElement, linkify) { var node = (this.representedObject); var classes = [ "webkit-html-tag" ]; if (isClosingTag && isDistinctTreeElement) classes.push("close"); if (node.isInShadowTree()) classes.push("shadow"); var tagElement = parentElement.createChild("span", classes.join(" ")); tagElement.appendChild(document.createTextNode("<")); var tagNameElement = tagElement.createChild("span", isClosingTag ? "" : "webkit-html-tag-name"); tagNameElement.textContent = (isClosingTag ? "/" : "") + tagName; if (!isClosingTag && node.hasAttributes()) { var attributes = node.attributes(); for (var i = 0; i < attributes.length; ++i) { var attr = attributes[i]; tagElement.appendChild(document.createTextNode(" ")); this._buildAttributeDOM(tagElement, attr.name, attr.value, node, linkify); } } tagElement.appendChild(document.createTextNode(">")); parentElement.appendChild(document.createTextNode("\u200B")); }, _convertWhitespaceToEntities: function(text) { var result = ""; var lastIndexAfterEntity = 0; var charToEntity = WebInspector.ElementsTreeOutline.MappedCharToEntity; for (var i = 0, size = text.length; i < size; ++i) { var char = text.charAt(i); if (charToEntity[char]) { result += text.substring(lastIndexAfterEntity, i) + "&" + charToEntity[char] + ";"; lastIndexAfterEntity = i + 1; } } if (result) { result += text.substring(lastIndexAfterEntity); return result; } return text; }, _nodeTitleInfo: function(linkify) { var node = this.representedObject; var info = {titleDOM: document.createDocumentFragment(), hasChildren: this.hasChildren}; switch (node.nodeType()) { case Node.ATTRIBUTE_NODE: var value = node.value || "\u200B"; this._buildAttributeDOM(info.titleDOM, node.name, value); break; case Node.ELEMENT_NODE: var tagName = node.nodeNameInCorrectCase(); if (this._elementCloseTag) { this._buildTagDOM(info.titleDOM, tagName, true, true); info.hasChildren = false; break; } this._buildTagDOM(info.titleDOM, tagName, false, false, linkify); var textChild = this._singleTextChild(node); var showInlineText = textChild && textChild.nodeValue().length < Preferences.maxInlineTextChildLength && !this.hasChildren; if (!this.expanded && (!showInlineText && (this.treeOutline.isXMLMimeType || !WebInspector.ElementsTreeElement.ForbiddenClosingTagElements[tagName]))) { if (this.hasChildren) { var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node bogus"); textNodeElement.textContent = "\u2026"; info.titleDOM.appendChild(document.createTextNode("\u200B")); } this._buildTagDOM(info.titleDOM, tagName, true, false); } if (showInlineText) { var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node"); textNodeElement.textContent = this._convertWhitespaceToEntities(textChild.nodeValue()); info.titleDOM.appendChild(document.createTextNode("\u200B")); this._buildTagDOM(info.titleDOM, tagName, true, false); info.hasChildren = false; } break; case Node.TEXT_NODE: if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "script") { var newNode = info.titleDOM.createChild("span", "webkit-html-text-node webkit-html-js-node"); newNode.textContent = node.nodeValue(); var javascriptSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/javascript", true); javascriptSyntaxHighlighter.syntaxHighlightNode(newNode); } else if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "style") { var newNode = info.titleDOM.createChild("span", "webkit-html-text-node webkit-html-css-node"); newNode.textContent = node.nodeValue(); var cssSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/css", true); cssSyntaxHighlighter.syntaxHighlightNode(newNode); } else { info.titleDOM.appendChild(document.createTextNode("\"")); var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node"); textNodeElement.textContent = this._convertWhitespaceToEntities(node.nodeValue()); info.titleDOM.appendChild(document.createTextNode("\"")); } break; case Node.COMMENT_NODE: var commentElement = info.titleDOM.createChild("span", "webkit-html-comment"); commentElement.appendChild(document.createTextNode("<!--" + node.nodeValue() + "-->")); break; case Node.DOCUMENT_TYPE_NODE: var docTypeElement = info.titleDOM.createChild("span", "webkit-html-doctype"); docTypeElement.appendChild(document.createTextNode("<!DOCTYPE " + node.nodeName())); if (node.publicId) { docTypeElement.appendChild(document.createTextNode(" PUBLIC \"" + node.publicId + "\"")); if (node.systemId) docTypeElement.appendChild(document.createTextNode(" \"" + node.systemId + "\"")); } else if (node.systemId) docTypeElement.appendChild(document.createTextNode(" SYSTEM \"" + node.systemId + "\"")); if (node.internalSubset) docTypeElement.appendChild(document.createTextNode(" [" + node.internalSubset + "]")); docTypeElement.appendChild(document.createTextNode(">")); break; case Node.CDATA_SECTION_NODE: var cdataElement = info.titleDOM.createChild("span", "webkit-html-text-node"); cdataElement.appendChild(document.createTextNode("<![CDATA[" + node.nodeValue() + "]]>")); break; case Node.DOCUMENT_FRAGMENT_NODE: var fragmentElement = info.titleDOM.createChild("span", "webkit-html-fragment"); fragmentElement.textContent = node.nodeNameInCorrectCase().collapseWhitespace(); if (node.isInShadowTree()) fragmentElement.addStyleClass("shadow"); break; default: info.titleDOM.appendChild(document.createTextNode(node.nodeNameInCorrectCase().collapseWhitespace())); } return info; }, _singleTextChild: function(node) { if (!node) return null; var firstChild = node.firstChild; if (!firstChild || firstChild.nodeType() !== Node.TEXT_NODE) return null; if (node.hasShadowRoots()) return null; var sibling = firstChild.nextSibling; return sibling ? null : firstChild; }, _showInlineText: function(node) { if (node.nodeType() === Node.ELEMENT_NODE) { var textChild = this._singleTextChild(node); if (textChild && textChild.nodeValue().length < Preferences.maxInlineTextChildLength) return true; } return false; }, remove: function() { var parentElement = this.parent; if (!parentElement) return; var self = this; function removeNodeCallback(error, removedNodeId) { if (error) return; parentElement.removeChild(self); parentElement.adjustCollapsedRange(); } if (!this.representedObject.parentNode || this.representedObject.parentNode.nodeType() === Node.DOCUMENT_NODE) return; this.representedObject.removeNode(removeNodeCallback); }, _editAsHTML: function() { var treeOutline = this.treeOutline; var node = this.representedObject; var parentNode = node.parentNode; var index = node.index; var wasExpanded = this.expanded; function selectNode(error, nodeId) { if (error) return; treeOutline._updateModifiedNodes(); var newNode = parentNode ? parentNode.children[index] || parentNode : null; if (!newNode) return; treeOutline.selectDOMNode(newNode, true); if (wasExpanded) { var newTreeItem = treeOutline.findTreeElement(newNode); if (newTreeItem) newTreeItem.expand(); } } function commitChange(initialValue, value) { if (initialValue !== value) node.setOuterHTML(value, selectNode); else return; } node.getOuterHTML(this._startEditingAsHTML.bind(this, commitChange)); }, _copyHTML: function() { this.representedObject.copyNode(); }, _copyXPath: function() { this.representedObject.copyXPath(true); }, _highlightSearchResults: function() { if (!this._searchQuery || !this._searchHighlightsVisible) return; if (this._highlightResult) { this._updateSearchHighlight(true); return; } var text = this.listItemElement.textContent; var regexObject = createPlainTextSearchRegex(this._searchQuery, "gi"); var offset = 0; var match = regexObject.exec(text); var matchRanges = []; while (match) { matchRanges.push({ offset: match.index, length: match[0].length }); match = regexObject.exec(text); } if (!matchRanges.length) matchRanges.push({ offset: 0, length: text.length }); this._highlightResult = []; WebInspector.highlightSearchResults(this.listItemElement, matchRanges, this._highlightResult); }, _scrollIntoView: function() { function scrollIntoViewCallback(object) { function scrollIntoView() { this.scrollIntoViewIfNeeded(true); } if (object) object.callFunction(scrollIntoView); } var node = (this.representedObject); WebInspector.RemoteObject.resolveNode(node, "", scrollIntoViewCallback); }, __proto__: TreeElement.prototype } WebInspector.ElementsTreeUpdater = function(treeOutline) { WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.NodeInserted, this._nodeInserted, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.NodeRemoved, this._nodeRemoved, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrModified, this._attributesUpdated, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrRemoved, this._attributesUpdated, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.CharacterDataModified, this._characterDataModified, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, this._documentUpdated, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this); this._treeOutline = treeOutline; this._recentlyModifiedNodes = new Map(); } WebInspector.ElementsTreeUpdater.prototype = { _nodeModified: function(node, isUpdated, parentNode) { if (this._treeOutline._visible) this._updateModifiedNodesSoon(); var entry = (this._recentlyModifiedNodes.get(node)); if (!entry) { entry = new WebInspector.ElementsTreeUpdater.UpdateEntry(isUpdated, parentNode); this._recentlyModifiedNodes.put(node, entry); return; } entry.isUpdated |= isUpdated; if (parentNode) entry.parent = parentNode; }, _documentUpdated: function(event) { var inspectedRootDocument = event.data; this._reset(); if (!inspectedRootDocument) return; this._treeOutline.rootDOMNode = inspectedRootDocument; }, _attributesUpdated: function(event) { this._nodeModified(event.data.node, true); }, _characterDataModified: function(event) { this._nodeModified(event.data, true); }, _nodeInserted: function(event) { this._nodeModified(event.data, false, event.data.parentNode); }, _nodeRemoved: function(event) { this._nodeModified(event.data.node, false, event.data.parent); }, _childNodeCountUpdated: function(event) { var treeElement = this._treeOutline.findTreeElement(event.data); if (treeElement) treeElement.hasChildren = event.data.hasChildNodes(); }, _updateModifiedNodesSoon: function() { if (this._updateModifiedNodesTimeout) return; this._updateModifiedNodesTimeout = setTimeout(this._updateModifiedNodes.bind(this), 50); }, _updateModifiedNodes: function() { if (this._updateModifiedNodesTimeout) { clearTimeout(this._updateModifiedNodesTimeout); delete this._updateModifiedNodesTimeout; } var updatedParentTreeElements = []; var hidePanelWhileUpdating = this._recentlyModifiedNodes.size() > 10; if (hidePanelWhileUpdating) { var treeOutlineContainerElement = this._treeOutline.element.parentNode; this._treeOutline.element.addStyleClass("hidden"); var originalScrollTop = treeOutlineContainerElement ? treeOutlineContainerElement.scrollTop : 0; } var keys = this._recentlyModifiedNodes.keys(); for (var i = 0, size = keys.length; i < size; ++i) { var node = keys[i]; var entry = this._recentlyModifiedNodes.get(node); var parent = entry.parent; if (parent === this._treeOutline._rootDOMNode) { this._treeOutline.update(); this._treeOutline.element.removeStyleClass("hidden"); return; } if (entry.isUpdated) { var nodeItem = this._treeOutline.findTreeElement(node); if (nodeItem) nodeItem.updateTitle(); } if (!parent) continue; var parentNodeItem = this._treeOutline.findTreeElement(parent); if (parentNodeItem && !parentNodeItem.alreadyUpdatedChildren) { parentNodeItem.updateChildren(); parentNodeItem.alreadyUpdatedChildren = true; updatedParentTreeElements.push(parentNodeItem); } } for (var i = 0; i < updatedParentTreeElements.length; ++i) delete updatedParentTreeElements[i].alreadyUpdatedChildren; if (hidePanelWhileUpdating) { this._treeOutline.element.removeStyleClass("hidden"); if (originalScrollTop) treeOutlineContainerElement.scrollTop = originalScrollTop; this._treeOutline.updateSelection(); } this._recentlyModifiedNodes.clear(); }, _reset: function() { this._treeOutline.rootDOMNode = null; this._treeOutline.selectDOMNode(null, false); WebInspector.domAgent.hideDOMNodeHighlight(); this._recentlyModifiedNodes.clear(); } } WebInspector.ElementsTreeUpdater.UpdateEntry = function(isUpdated, parent) { this.isUpdated = isUpdated; if (parent) this.parent = parent; } WebInspector.DOMPresentationUtils = {} WebInspector.DOMPresentationUtils.decorateNodeLabel = function(node, parentElement) { var title = node.nodeNameInCorrectCase(); var nameElement = document.createElement("span"); nameElement.textContent = title; parentElement.appendChild(nameElement); var idAttribute = node.getAttribute("id"); if (idAttribute) { var idElement = document.createElement("span"); parentElement.appendChild(idElement); var part = "#" + idAttribute; title += part; idElement.appendChild(document.createTextNode(part)); nameElement.className = "extra"; } var classAttribute = node.getAttribute("class"); if (classAttribute) { var classes = classAttribute.split(/\s+/); var foundClasses = {}; if (classes.length) { var classesElement = document.createElement("span"); classesElement.className = "extra"; parentElement.appendChild(classesElement); for (var i = 0; i < classes.length; ++i) { var className = classes[i]; if (className && !(className in foundClasses)) { var part = "." + className; title += part; classesElement.appendChild(document.createTextNode(part)); foundClasses[className] = true; } } } } parentElement.title = title; } WebInspector.DOMPresentationUtils.createSpansForNodeTitle = function(container, nodeTitle) { var match = nodeTitle.match(/([^#.]+)(#[^.]+)?(\..*)?/); container.createChild("span", "webkit-html-tag-name").textContent = match[1]; if (match[2]) container.createChild("span", "webkit-html-attribute-value").textContent = match[2]; if (match[3]) container.createChild("span", "webkit-html-attribute-name").textContent = match[3]; } WebInspector.DOMPresentationUtils.linkifyNodeReference = function(node) { var link = document.createElement("span"); link.className = "node-link"; WebInspector.DOMPresentationUtils.decorateNodeLabel(node, link); link.addEventListener("click", WebInspector.domAgent.inspectElement.bind(WebInspector.domAgent, node.id), false); link.addEventListener("mouseover", WebInspector.domAgent.highlightDOMNode.bind(WebInspector.domAgent, node.id, "", undefined), false); link.addEventListener("mouseout", WebInspector.domAgent.hideDOMNodeHighlight.bind(WebInspector.domAgent), false); return link; } WebInspector.DOMPresentationUtils.linkifyNodeById = function(nodeId) { var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) return document.createTextNode(WebInspector.UIString("<node>")); return WebInspector.DOMPresentationUtils.linkifyNodeReference(node); } WebInspector.DOMPresentationUtils.buildImagePreviewContents = function(imageURL, showDimensions, userCallback, precomputedDimensions) { var resource = WebInspector.resourceTreeModel.resourceForURL(imageURL); if (!resource) { userCallback(); return; } var imageElement = document.createElement("img"); imageElement.addEventListener("load", buildContent, false); imageElement.addEventListener("error", errorCallback, false); resource.populateImageSource(imageElement); function errorCallback() { userCallback(); } function buildContent() { var container = document.createElement("table"); container.className = "image-preview-container"; var naturalWidth = precomputedDimensions ? precomputedDimensions.naturalWidth : imageElement.naturalWidth; var naturalHeight = precomputedDimensions ? precomputedDimensions.naturalHeight : imageElement.naturalHeight; var offsetWidth = precomputedDimensions ? precomputedDimensions.offsetWidth : naturalWidth; var offsetHeight = precomputedDimensions ? precomputedDimensions.offsetHeight : naturalHeight; var description; if (showDimensions) { if (offsetHeight === naturalHeight && offsetWidth === naturalWidth) description = WebInspector.UIString("%d \xd7 %d pixels", offsetWidth, offsetHeight); else description = WebInspector.UIString("%d \xd7 %d pixels (Natural: %d \xd7 %d pixels)", offsetWidth, offsetHeight, naturalWidth, naturalHeight); } container.createChild("tr").createChild("td", "image-container").appendChild(imageElement); if (description) container.createChild("tr").createChild("td").createChild("span", "description").textContent = description; userCallback(container); } } WebInspector.SidebarSectionTreeElement = function(title, representedObject, hasChildren) { TreeElement.call(this, title.escapeHTML(), representedObject || {}, hasChildren); this.expand(); } WebInspector.SidebarSectionTreeElement.prototype = { selectable: false, collapse: function() { }, get smallChildren() { return this._smallChildren; }, set smallChildren(x) { if (this._smallChildren === x) return; this._smallChildren = x; if (this._smallChildren) this._childrenListNode.addStyleClass("small"); else this._childrenListNode.removeStyleClass("small"); }, onattach: function() { this._listItemNode.addStyleClass("sidebar-tree-section"); }, onreveal: function() { if (this.listItemElement) this.listItemElement.scrollIntoViewIfNeeded(false); }, __proto__: TreeElement.prototype } WebInspector.SidebarTreeElement = function(className, title, subtitle, representedObject, hasChildren) { TreeElement.call(this, "", representedObject, hasChildren); if (hasChildren) { this.disclosureButton = document.createElement("button"); this.disclosureButton.className = "disclosure-button"; } if (!this.iconElement) { this.iconElement = document.createElement("img"); this.iconElement.className = "icon"; } this.statusElement = document.createElement("div"); this.statusElement.className = "status"; this.titlesElement = document.createElement("div"); this.titlesElement.className = "titles"; this.titleElement = document.createElement("span"); this.titleElement.className = "title"; this.titlesElement.appendChild(this.titleElement); this.subtitleElement = document.createElement("span"); this.subtitleElement.className = "subtitle"; this.titlesElement.appendChild(this.subtitleElement); this.className = className; this.mainTitle = title; this.subtitle = subtitle; } WebInspector.SidebarTreeElement.prototype = { get small() { return this._small; }, set small(x) { this._small = x; if (this._listItemNode) { if (this._small) this._listItemNode.addStyleClass("small"); else this._listItemNode.removeStyleClass("small"); } }, get mainTitle() { return this._mainTitle; }, set mainTitle(x) { this._mainTitle = x; this.refreshTitles(); }, get subtitle() { return this._subtitle; }, set subtitle(x) { this._subtitle = x; this.refreshTitles(); }, get bubbleText() { return this._bubbleText; }, set bubbleText(x) { if (!this.bubbleElement) { this.bubbleElement = document.createElement("div"); this.bubbleElement.className = "bubble"; this.statusElement.appendChild(this.bubbleElement); } this._bubbleText = x; this.bubbleElement.textContent = x; }, set wait(x) { if (x) this._listItemNode.addStyleClass("wait"); else this._listItemNode.removeStyleClass("wait"); }, refreshTitles: function() { var mainTitle = this.mainTitle; if (this.titleElement.textContent !== mainTitle) this.titleElement.textContent = mainTitle; var subtitle = this.subtitle; if (subtitle) { if (this.subtitleElement.textContent !== subtitle) this.subtitleElement.textContent = subtitle; this.titlesElement.removeStyleClass("no-subtitle"); } else { this.subtitleElement.textContent = ""; this.titlesElement.addStyleClass("no-subtitle"); } }, isEventWithinDisclosureTriangle: function(event) { return event.target === this.disclosureButton; }, onattach: function() { this._listItemNode.addStyleClass("sidebar-tree-item"); if (this.className) this._listItemNode.addStyleClass(this.className); if (this.small) this._listItemNode.addStyleClass("small"); if (this.hasChildren && this.disclosureButton) this._listItemNode.appendChild(this.disclosureButton); this._listItemNode.appendChild(this.iconElement); this._listItemNode.appendChild(this.statusElement); this._listItemNode.appendChild(this.titlesElement); }, onreveal: function() { if (this._listItemNode) this._listItemNode.scrollIntoViewIfNeeded(false); }, __proto__: TreeElement.prototype } WebInspector.Section = function(title, subtitle) { this.element = document.createElement("div"); this.element.className = "section"; this.element._section = this; this.headerElement = document.createElement("div"); this.headerElement.className = "header"; this.titleElement = document.createElement("div"); this.titleElement.className = "title"; this.subtitleElement = document.createElement("div"); this.subtitleElement.className = "subtitle"; this.headerElement.appendChild(this.subtitleElement); this.headerElement.appendChild(this.titleElement); this.headerElement.addEventListener("click", this.handleClick.bind(this), false); this.element.appendChild(this.headerElement); this.title = title; this.subtitle = subtitle; this._expanded = false; } WebInspector.Section.prototype = { get title() { return this._title; }, set title(x) { if (this._title === x) return; this._title = x; if (x instanceof Node) { this.titleElement.removeChildren(); this.titleElement.appendChild(x); } else this.titleElement.textContent = x; }, get subtitle() { return this._subtitle; }, set subtitle(x) { if (this._subtitle === x) return; this._subtitle = x; this.subtitleElement.textContent = x; }, get subtitleAsTextForTest() { var result = this.subtitleElement.textContent; var child = this.subtitleElement.querySelector("[data-uncopyable]"); if (child) { var linkData = child.getAttribute("data-uncopyable"); if (linkData) result += linkData; } return result; }, get expanded() { return this._expanded; }, set expanded(x) { if (x) this.expand(); else this.collapse(); }, get populated() { return this._populated; }, set populated(x) { this._populated = x; if (!x && this._expanded) { this.onpopulate(); this._populated = true; } }, onpopulate: function() { }, get firstSibling() { var parent = this.element.parentElement; if (!parent) return null; var childElement = parent.firstChild; while (childElement) { if (childElement._section) return childElement._section; childElement = childElement.nextSibling; } return null; }, get lastSibling() { var parent = this.element.parentElement; if (!parent) return null; var childElement = parent.lastChild; while (childElement) { if (childElement._section) return childElement._section; childElement = childElement.previousSibling; } return null; }, get nextSibling() { var curElement = this.element; do { curElement = curElement.nextSibling; } while (curElement && !curElement._section); return curElement ? curElement._section : null; }, get previousSibling() { var curElement = this.element; do { curElement = curElement.previousSibling; } while (curElement && !curElement._section); return curElement ? curElement._section : null; }, expand: function() { if (this._expanded) return; this._expanded = true; this.element.addStyleClass("expanded"); if (!this._populated) { this.onpopulate(); this._populated = true; } }, collapse: function() { if (!this._expanded) return; this._expanded = false; this.element.removeStyleClass("expanded"); }, toggleExpanded: function() { this.expanded = !this.expanded; }, handleClick: function(event) { this.toggleExpanded(); event.consume(); } } WebInspector.PropertiesSection = function(title, subtitle) { WebInspector.Section.call(this, title, subtitle); this.headerElement.addStyleClass("monospace"); this.propertiesElement = document.createElement("ol"); this.propertiesElement.className = "properties properties-tree monospace"; this.propertiesTreeOutline = new TreeOutline(this.propertiesElement, true); this.propertiesTreeOutline.setFocusable(false); this.propertiesTreeOutline.section = this; this.element.appendChild(this.propertiesElement); } WebInspector.PropertiesSection.prototype = { __proto__: WebInspector.Section.prototype } WebInspector.RemoteObject = function(objectId, type, subtype, value, description, preview) { this._type = type; this._subtype = subtype; if (objectId) { this._objectId = objectId; this._description = description; this._hasChildren = true; this._preview = preview; } else { console.assert(type !== "object" || value === null); this._description = description || (value + ""); this._hasChildren = false; this.value = value; } } WebInspector.RemoteObject.fromPrimitiveValue = function(value) { return new WebInspector.RemoteObject(undefined, typeof value, undefined, value); } WebInspector.RemoteObject.fromLocalObject = function(value) { return new WebInspector.LocalJSONObject(value); } WebInspector.RemoteObject.resolveNode = function(node, objectGroup, callback) { function mycallback(error, object) { if (!callback) return; if (error || !object) callback(null); else callback(WebInspector.RemoteObject.fromPayload(object)); } DOMAgent.resolveNode(node.id, objectGroup, mycallback); } WebInspector.RemoteObject.fromPayload = function(payload) { console.assert(typeof payload === "object", "Remote object payload should only be an object"); return new WebInspector.RemoteObject(payload.objectId, payload.type, payload.subtype, payload.value, payload.description, payload.preview); } WebInspector.RemoteObject.type = function(remoteObject) { if (remoteObject === null) return "null"; var type = typeof remoteObject; if (type !== "object" && type !== "function") return type; return remoteObject.type; } WebInspector.RemoteObject.prototype = { get objectId() { return this._objectId; }, get type() { return this._type; }, get subtype() { return this._subtype; }, get description() { return this._description; }, get hasChildren() { return this._hasChildren; }, get preview() { return this._preview; }, getOwnProperties: function(callback) { this._getProperties(true, callback); }, getAllProperties: function(callback) { this._getProperties(false, callback); }, _getProperties: function(ownProperties, callback) { if (!this._objectId) { callback([]); return; } function remoteObjectBinder(error, properties, internalProperties) { if (error) { callback(null); return; } var result = []; for (var i = 0; properties && i < properties.length; ++i) { var property = properties[i]; if (property.get || property.set) { if (property.get) result.push(new WebInspector.RemoteObjectProperty("get " + property.name, WebInspector.RemoteObject.fromPayload(property.get), property)); if (property.set) result.push(new WebInspector.RemoteObjectProperty("set " + property.name, WebInspector.RemoteObject.fromPayload(property.set), property)); } else result.push(new WebInspector.RemoteObjectProperty(property.name, WebInspector.RemoteObject.fromPayload(property.value), property)); } var internalPropertiesResult; if (internalProperties) { internalPropertiesResult = []; for (var i = 0; i < internalProperties.length; i++) { var property = internalProperties[i]; internalPropertiesResult.push(new WebInspector.RemoteObjectProperty(property.name, WebInspector.RemoteObject.fromPayload(property.value))); } } callback(result, internalPropertiesResult); } RuntimeAgent.getProperties(this._objectId, ownProperties, remoteObjectBinder); }, setPropertyValue: function(name, value, callback) { if (!this._objectId) { callback("Can't set a property of non-object."); return; } RuntimeAgent.evaluate.invoke({expression:value, doNotPauseOnExceptionsAndMuteConsole:true}, evaluatedCallback.bind(this)); function evaluatedCallback(error, result, wasThrown) { if (error || wasThrown) { callback(error || result.description); return; } var setPropertyValueFunction = "function(a, b) { this[a] = b; }"; if (result.type === "number" && typeof result.value !== "number") setPropertyValueFunction = "function(a) { this[a] = " + result.description + "; }"; delete result.description; RuntimeAgent.callFunctionOn(this._objectId, setPropertyValueFunction, [{ value:name }, result], true, undefined, undefined, propertySetCallback.bind(this)); if (result._objectId) RuntimeAgent.releaseObject(result._objectId); } function propertySetCallback(error, result, wasThrown) { if (error || wasThrown) { callback(error || result.description); return; } callback(); } }, pushNodeToFrontend: function(callback) { if (this._objectId) WebInspector.domAgent.pushNodeToFrontend(this._objectId, callback); else callback(0); }, highlightAsDOMNode: function() { WebInspector.domAgent.highlightDOMNode(undefined, undefined, this._objectId); }, hideDOMNodeHighlight: function() { WebInspector.domAgent.hideDOMNodeHighlight(); }, callFunction: function(functionDeclaration, args, callback) { function mycallback(error, result, wasThrown) { if (!callback) return; callback((error || wasThrown) ? null : WebInspector.RemoteObject.fromPayload(result)); } RuntimeAgent.callFunctionOn(this._objectId, functionDeclaration.toString(), args, true, undefined, undefined, mycallback); }, callFunctionJSON: function(functionDeclaration, args, callback) { function mycallback(error, result, wasThrown) { callback((error || wasThrown) ? null : result.value); } RuntimeAgent.callFunctionOn(this._objectId, functionDeclaration.toString(), args, true, true, false, mycallback); }, release: function() { if (!this._objectId) return; RuntimeAgent.releaseObject(this._objectId); }, arrayLength: function() { if (this.subtype !== "array") return 0; var matches = this._description.match(/\[([0-9]+)\]/); if (!matches) return 0; return parseInt(matches[1], 10); } } WebInspector.RemoteObjectProperty = function(name, value, descriptor) { this.name = name; this.value = value; this.enumerable = descriptor ? !!descriptor.enumerable : true; this.writable = descriptor ? !!descriptor.writable : true; if (descriptor && descriptor.wasThrown) this.wasThrown = true; } WebInspector.RemoteObjectProperty.fromPrimitiveValue = function(name, value) { return new WebInspector.RemoteObjectProperty(name, WebInspector.RemoteObject.fromPrimitiveValue(value)); } WebInspector.RemoteObjectProperty.fromScopeValue = function(name, value) { var result = new WebInspector.RemoteObjectProperty(name, value); result.writable = false; return result; } WebInspector.LocalJSONObject = function(value) { this._value = value; } WebInspector.LocalJSONObject.prototype = { get description() { if (this._cachedDescription) return this._cachedDescription; if (this.type === "object") { switch (this.subtype) { case "array": function formatArrayItem(property) { return property.value.description; } this._cachedDescription = this._concatenate("[", "]", formatArrayItem); break; case "date": this._cachedDescription = "" + this._value; break; case "null": this._cachedDescription = "null"; break; default: function formatObjectItem(property) { return property.name + ":" + property.value.description; } this._cachedDescription = this._concatenate("{", "}", formatObjectItem); } } else this._cachedDescription = String(this._value); return this._cachedDescription; }, _concatenate: function(prefix, suffix, formatProperty) { const previewChars = 100; var buffer = prefix; var children = this._children(); for (var i = 0; i < children.length; ++i) { var itemDescription = formatProperty(children[i]); if (buffer.length + itemDescription.length > previewChars) { buffer += ",\u2026"; break; } if (i) buffer += ", "; buffer += itemDescription; } buffer += suffix; return buffer; }, get type() { return typeof this._value; }, get subtype() { if (this._value === null) return "null"; if (this._value instanceof Array) return "array"; if (this._value instanceof Date) return "date"; return undefined; }, get hasChildren() { return typeof this._value === "object" && this._value !== null && !!Object.keys(this._value).length; }, getOwnProperties: function(callback) { callback(this._children()); }, getAllProperties: function(callback) { callback(this._children()); }, _children: function() { if (!this.hasChildren) return []; function buildProperty(propName) { return new WebInspector.RemoteObjectProperty(propName, new WebInspector.LocalJSONObject(this._value[propName])); } if (!this._cachedChildren) this._cachedChildren = Object.keys(this._value || {}).map(buildProperty.bind(this)); return this._cachedChildren; }, isError: function() { return false; }, arrayLength: function() { return this._value instanceof Array ? this._value.length : 0; } } WebInspector.ObjectPropertiesSection = function(object, title, subtitle, emptyPlaceholder, ignoreHasOwnProperty, extraProperties, treeElementConstructor) { this.emptyPlaceholder = (emptyPlaceholder || WebInspector.UIString("No Properties")); this.object = object; this.ignoreHasOwnProperty = ignoreHasOwnProperty; this.extraProperties = extraProperties; this.treeElementConstructor = treeElementConstructor || WebInspector.ObjectPropertyTreeElement; this.editable = true; this.skipProto = false; WebInspector.PropertiesSection.call(this, title || "", subtitle); } WebInspector.ObjectPropertiesSection._arrayLoadThreshold = 100; WebInspector.ObjectPropertiesSection.prototype = { enableContextMenu: function() { this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), false); }, _contextMenuEventFired: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendApplicableItems(this.object); contextMenu.show(); }, onpopulate: function() { this.update(); }, update: function() { if (this.object.arrayLength() > WebInspector.ObjectPropertiesSection._arrayLoadThreshold) { this.propertiesTreeOutline.removeChildren(); WebInspector.ArrayGroupingTreeElement._populateArray(this.propertiesTreeOutline, this.object, 0, this.object.arrayLength() - 1); return; } function callback(properties, internalProperties) { if (!properties) return; this.updateProperties(properties); } if (this.ignoreHasOwnProperty) this.object.getAllProperties(callback.bind(this)); else this.object.getOwnProperties(callback.bind(this)); }, updateProperties: function(properties, rootTreeElementConstructor, rootPropertyComparer) { if (!rootTreeElementConstructor) rootTreeElementConstructor = this.treeElementConstructor; if (!rootPropertyComparer) rootPropertyComparer = WebInspector.ObjectPropertiesSection.CompareProperties; if (this.extraProperties) for (var i = 0; i < this.extraProperties.length; ++i) properties.push(this.extraProperties[i]); properties.sort(rootPropertyComparer); this.propertiesTreeOutline.removeChildren(); for (var i = 0; i < properties.length; ++i) { if (this.skipProto && properties[i].name === "__proto__") continue; properties[i].parentObject = this.object; } this.propertiesForTest = properties; for (var i = 0; i < properties.length; ++i) this.propertiesTreeOutline.appendChild(new rootTreeElementConstructor(properties[i])); if (!this.propertiesTreeOutline.children.length) { var title = document.createElement("div"); title.className = "info"; title.textContent = this.emptyPlaceholder; var infoElement = new TreeElement(title, null, false); this.propertiesTreeOutline.appendChild(infoElement); } }, __proto__: WebInspector.PropertiesSection.prototype } WebInspector.ObjectPropertiesSection.CompareProperties = function(propertyA, propertyB) { var a = propertyA.name; var b = propertyB.name; if (a === "__proto__") return 1; if (b === "__proto__") return -1; var diff = 0; var chunk = /^\d+|^\D+/; var chunka, chunkb, anum, bnum; while (diff === 0) { if (!a && b) return -1; if (!b && a) return 1; chunka = a.match(chunk)[0]; chunkb = b.match(chunk)[0]; anum = !isNaN(chunka); bnum = !isNaN(chunkb); if (anum && !bnum) return -1; if (bnum && !anum) return 1; if (anum && bnum) { diff = chunka - chunkb; if (diff === 0 && chunka.length !== chunkb.length) { if (!+chunka && !+chunkb) return chunka.length - chunkb.length; else return chunkb.length - chunka.length; } } else if (chunka !== chunkb) return (chunka < chunkb) ? -1 : 1; a = a.substring(chunka.length); b = b.substring(chunkb.length); } return diff; } WebInspector.ObjectPropertyTreeElement = function(property) { this.property = property; TreeElement.call(this, "", null, false); this.toggleOnClick = true; this.selectable = false; } WebInspector.ObjectPropertyTreeElement.prototype = { onpopulate: function() { return WebInspector.ObjectPropertyTreeElement.populate(this, this.property.value); }, ondblclick: function(event) { if (this.property.writable) this.startEditing(event); }, onattach: function() { this.update(); }, update: function() { this.nameElement = document.createElement("span"); this.nameElement.className = "name"; this.nameElement.textContent = this.property.name; if (!this.property.enumerable) this.nameElement.addStyleClass("dimmed"); var separatorElement = document.createElement("span"); separatorElement.className = "separator"; separatorElement.textContent = ": "; this.valueElement = document.createElement("span"); this.valueElement.className = "value"; var description = this.property.value.description; if (this.property.wasThrown) this.valueElement.textContent = "[Exception: " + description + "]"; else if (this.property.value.type === "string" && typeof description === "string") { this.valueElement.textContent = "\"" + description.replace(/\n/g, "\u21B5") + "\""; this.valueElement._originalTextContent = "\"" + description + "\""; } else if (this.property.value.type === "function" && typeof description === "string") { this.valueElement.textContent = /.*/.exec(description)[0].replace(/ +$/g, ""); this.valueElement._originalTextContent = description; } else if (this.property.value.type !== "object" || this.property.value.subtype !== "node") this.valueElement.textContent = description; if (this.property.wasThrown) this.valueElement.addStyleClass("error"); if (this.property.value.subtype) this.valueElement.addStyleClass("console-formatted-" + this.property.value.subtype); else if (this.property.value.type) this.valueElement.addStyleClass("console-formatted-" + this.property.value.type); this.valueElement.addEventListener("contextmenu", this._contextMenuFired.bind(this, this.property.value), false); if (this.property.value.type === "object" && this.property.value.subtype === "node" && this.property.value.description) { WebInspector.DOMPresentationUtils.createSpansForNodeTitle(this.valueElement, this.property.value.description); this.valueElement.addEventListener("mousemove", this._mouseMove.bind(this, this.property.value), false); this.valueElement.addEventListener("mouseout", this._mouseOut.bind(this, this.property.value), false); } else this.valueElement.title = description || ""; this.listItemElement.removeChildren(); this.listItemElement.appendChild(this.nameElement); this.listItemElement.appendChild(separatorElement); this.listItemElement.appendChild(this.valueElement); this.hasChildren = this.property.value.hasChildren && !this.property.wasThrown; }, _contextMenuFired: function(value, event) { var contextMenu = new WebInspector.ContextMenu(event); this.populateContextMenu(contextMenu); contextMenu.appendApplicableItems(value); contextMenu.show(); }, populateContextMenu: function(contextMenu) { }, _mouseMove: function(event) { this.property.value.highlightAsDOMNode(); }, _mouseOut: function(event) { this.property.value.hideDOMNodeHighlight(); }, updateSiblings: function() { if (this.parent.root) this.treeOutline.section.update(); else this.parent.shouldRefreshChildren = true; }, renderPromptAsBlock: function() { return false; }, elementAndValueToEdit: function(event) { return [this.valueElement, (typeof this.valueElement._originalTextContent === "string") ? this.valueElement._originalTextContent : undefined]; }, startEditing: function(event) { var elementAndValueToEdit = this.elementAndValueToEdit(event); var elementToEdit = elementAndValueToEdit[0]; var valueToEdit = elementAndValueToEdit[1]; if (WebInspector.isBeingEdited(elementToEdit) || !this.treeOutline.section.editable || this._readOnly) return; if (typeof valueToEdit !== "undefined") elementToEdit.textContent = valueToEdit; var context = { expanded: this.expanded, elementToEdit: elementToEdit, previousContent: elementToEdit.textContent }; this.hasChildren = false; this.listItemElement.addStyleClass("editing-sub-part"); this._prompt = new WebInspector.ObjectPropertyPrompt(this.editingCommitted.bind(this, null, elementToEdit.textContent, context.previousContent, context), this.editingCancelled.bind(this, null, context), this.renderPromptAsBlock()); function blurListener() { this.editingCommitted(null, elementToEdit.textContent, context.previousContent, context); } var proxyElement = this._prompt.attachAndStartEditing(elementToEdit, blurListener.bind(this)); window.getSelection().setBaseAndExtent(elementToEdit, 0, elementToEdit, 1); proxyElement.addEventListener("keydown", this._promptKeyDown.bind(this, context), false); }, isEditing: function() { return !!this._prompt; }, editingEnded: function(context) { this._prompt.detach(); delete this._prompt; this.listItemElement.scrollLeft = 0; this.listItemElement.removeStyleClass("editing-sub-part"); if (context.expanded) this.expand(); }, editingCancelled: function(element, context) { this.editingEnded(context); this.update(); }, editingCommitted: function(element, userInput, previousContent, context) { if (userInput === previousContent) return this.editingCancelled(element, context); this.editingEnded(context); this.applyExpression(userInput, true); }, _promptKeyDown: function(context, event) { if (isEnterKey(event)) { event.consume(true); return this.editingCommitted(null, context.elementToEdit.textContent, context.previousContent, context); } if (event.keyIdentifier === "U+001B") { event.consume(); return this.editingCancelled(null, context); } }, applyExpression: function(expression, updateInterface) { expression = expression.trim(); var expressionLength = expression.length; function callback(error) { if (!updateInterface) return; if (error) this.update(); if (!expressionLength) { this.parent.removeChild(this); } else { this.updateSiblings(); } }; this.property.parentObject.setPropertyValue(this.property.name, expression.trim(), callback.bind(this)); }, propertyPath: function() { if ("_cachedPropertyPath" in this) return this._cachedPropertyPath; var current = this; var result; do { if (current.property) { if (result) result = current.property.name + "." + result; else result = current.property.name; } current = current.parent; } while (current && !current.root); this._cachedPropertyPath = result; return result; }, __proto__: TreeElement.prototype } WebInspector.ObjectPropertyTreeElement.populate = function(treeElement, value) { if (treeElement.children.length && !treeElement.shouldRefreshChildren) return; if (value.arrayLength() > WebInspector.ObjectPropertiesSection._arrayLoadThreshold) { treeElement.removeChildren(); WebInspector.ArrayGroupingTreeElement._populateArray(treeElement, value, 0, value.arrayLength() - 1); return; } function callback(properties, internalProperties) { treeElement.removeChildren(); if (!properties) return; properties.sort(WebInspector.ObjectPropertiesSection.CompareProperties); for (var i = 0; i < properties.length; ++i) { if (treeElement.treeOutline.section.skipProto && properties[i].name === "__proto__") continue; properties[i].parentObject = value; treeElement.appendChild(new treeElement.treeOutline.section.treeElementConstructor(properties[i])); } if (value.type === "function") { var hasTargetFunction = false; if (internalProperties) { for (var i = 0; i < internalProperties.length; i++) { if (internalProperties[i].name == "[[TargetFunction]]") { hasTargetFunction = true; break; } } } if (!hasTargetFunction) treeElement.appendChild(new WebInspector.FunctionScopeMainTreeElement(value)); } if (internalProperties) { for (var i = 0; i < internalProperties.length; i++) { internalProperties[i].parentObject = value; treeElement.appendChild(new treeElement.treeOutline.section.treeElementConstructor(internalProperties[i])); } } } value.getOwnProperties(callback); } WebInspector.FunctionScopeMainTreeElement = function(remoteObject) { TreeElement.call(this, "<function scope>", null, false); this.toggleOnClick = true; this.selectable = false; this._remoteObject = remoteObject; this.hasChildren = true; } WebInspector.FunctionScopeMainTreeElement.prototype = { onpopulate: function() { if (this.children.length && !this.shouldRefreshChildren) return; function didGetDetails(error, response) { if (error) { console.error(error); return; } this.removeChildren(); var scopeChain = response.scopeChain; if (!scopeChain) return; for (var i = 0; i < scopeChain.length; ++i) { var scope = scopeChain[i]; var title = null; var isTrueObject; switch (scope.type) { case "local": title = WebInspector.UIString("Local"); isTrueObject = false; break; case "closure": title = WebInspector.UIString("Closure"); isTrueObject = false; break; case "catch": title = WebInspector.UIString("Catch"); isTrueObject = false; break; case "with": title = WebInspector.UIString("With Block"); isTrueObject = true; break; case "global": title = WebInspector.UIString("Global"); isTrueObject = true; break; } var remoteObject = WebInspector.RemoteObject.fromPayload(scope.object); if (isTrueObject) { var property = WebInspector.RemoteObjectProperty.fromScopeValue(title, remoteObject); property.parentObject = null; this.appendChild(new this.treeOutline.section.treeElementConstructor(property)); } else { var scopeTreeElement = new WebInspector.ScopeTreeElement(title, null, remoteObject); this.appendChild(scopeTreeElement); } } } DebuggerAgent.getFunctionDetails(this._remoteObject.objectId, didGetDetails.bind(this)); }, __proto__: TreeElement.prototype } WebInspector.ScopeTreeElement = function(title, subtitle, remoteObject) { TreeElement.call(this, title, null, false); this.toggleOnClick = true; this.selectable = false; this._remoteObject = remoteObject; this.hasChildren = true; } WebInspector.ScopeTreeElement.prototype = { onpopulate: function() { return WebInspector.ObjectPropertyTreeElement.populate(this, this._remoteObject); }, __proto__: TreeElement.prototype } WebInspector.ArrayGroupingTreeElement = function(object, fromIndex, toIndex, propertyCount) { TreeElement.call(this, String.sprintf("[%d \u2026 %d]", fromIndex, toIndex), undefined, true); this._fromIndex = fromIndex; this._toIndex = toIndex; this._object = object; this._readOnly = true; this._propertyCount = propertyCount; this._populated = false; } WebInspector.ArrayGroupingTreeElement._bucketThreshold = 100; WebInspector.ArrayGroupingTreeElement._populateArray = function(treeElement, object, fromIndex, toIndex) { WebInspector.ArrayGroupingTreeElement._populateRanges(treeElement, object, fromIndex, toIndex, true); } WebInspector.ArrayGroupingTreeElement._populateRanges = function(treeElement, object, fromIndex, toIndex, topLevel) { object.callFunctionJSON(packRanges, [{value: fromIndex}, {value: toIndex}, {value: WebInspector.ArrayGroupingTreeElement._bucketThreshold}], callback.bind(this)); function packRanges(fromIndex, toIndex, bucketThreshold) { var count = 0; for (var i = fromIndex; i <= toIndex; ++i) { if (i in this) ++count; } var bucketSize = count; if (count <= bucketThreshold) bucketSize = count; else bucketSize = Math.pow(bucketThreshold, Math.ceil(Math.log(count) / Math.log(bucketThreshold)) - 1); var ranges = []; count = 0; var groupStart = -1; var groupEnd = 0; for (var i = fromIndex; i <= toIndex; ++i) { if (!(i in this)) continue; if (groupStart === -1) groupStart = i; groupEnd = i; if (++count === bucketSize) { ranges.push([groupStart, groupEnd, count]); count = 0; groupStart = -1; } } if (count > 0) ranges.push([groupStart, groupEnd, count]); return ranges; } function callback(ranges) { if (ranges.length == 1) WebInspector.ArrayGroupingTreeElement._populateAsFragment(treeElement, object, ranges[0][0], ranges[0][1]); else { for (var i = 0; i < ranges.length; ++i) { var fromIndex = ranges[i][0]; var toIndex = ranges[i][1]; var count = ranges[i][2]; if (fromIndex == toIndex) WebInspector.ArrayGroupingTreeElement._populateAsFragment(treeElement, object, fromIndex, toIndex); else treeElement.appendChild(new WebInspector.ArrayGroupingTreeElement(object, fromIndex, toIndex, count)); } } if (topLevel) WebInspector.ArrayGroupingTreeElement._populateNonIndexProperties(treeElement, object); } } WebInspector.ArrayGroupingTreeElement._populateAsFragment = function(treeElement, object, fromIndex, toIndex) { object.callFunction(buildArrayFragment, [{value: fromIndex}, {value: toIndex}], processArrayFragment.bind(this)); function buildArrayFragment(fromIndex, toIndex) { var result = Object.create(null); for (var i = fromIndex; i <= toIndex; ++i) { if (i in this) result[i] = this[i]; } return result; } function processArrayFragment(arrayFragment) { arrayFragment.getAllProperties(processProperties.bind(this)); } function processProperties(properties, internalProperties) { if (!properties) return; properties.sort(WebInspector.ObjectPropertiesSection.CompareProperties); for (var i = 0; i < properties.length; ++i) { properties[i].parentObject = this._object; var childTreeElement = new treeElement.treeOutline.section.treeElementConstructor(properties[i]); childTreeElement._readOnly = true; treeElement.appendChild(childTreeElement); } } } WebInspector.ArrayGroupingTreeElement._populateNonIndexProperties = function(treeElement, object) { object.callFunction(buildObjectFragment, undefined, processObjectFragment.bind(this)); function buildObjectFragment() { var result = Object.create(this.__proto__); var names = Object.getOwnPropertyNames(this); for (var i = 0; i < names.length; ++i) { var name = names[i]; if (!isNaN(name)) continue; var descriptor = Object.getOwnPropertyDescriptor(this, name); if (descriptor) Object.defineProperty(result, name, descriptor); } return result; } function processObjectFragment(arrayFragment) { arrayFragment.getOwnProperties(processProperties.bind(this)); } function processProperties(properties, internalProperties) { if (!properties) return; properties.sort(WebInspector.ObjectPropertiesSection.CompareProperties); for (var i = 0; i < properties.length; ++i) { properties[i].parentObject = this._object; var childTreeElement = new treeElement.treeOutline.section.treeElementConstructor(properties[i]); childTreeElement._readOnly = true; treeElement.appendChild(childTreeElement); } } } WebInspector.ArrayGroupingTreeElement.prototype = { onpopulate: function() { if (this._populated) return; this._populated = true; if (this._propertyCount >= WebInspector.ArrayGroupingTreeElement._bucketThreshold) { WebInspector.ArrayGroupingTreeElement._populateRanges(this, this._object, this._fromIndex, this._toIndex, false); return; } WebInspector.ArrayGroupingTreeElement._populateAsFragment(this, this._object, this._fromIndex, this._toIndex); }, onattach: function() { this.listItemElement.addStyleClass("name"); }, __proto__: TreeElement.prototype } WebInspector.ObjectPropertyPrompt = function(commitHandler, cancelHandler, renderAsBlock) { WebInspector.TextPrompt.call(this, WebInspector.runtimeModel.completionsForTextPrompt.bind(WebInspector.runtimeModel)); this.setSuggestBoxEnabled("generic-suggest"); if (renderAsBlock) this.renderAsBlock(); } WebInspector.ObjectPropertyPrompt.prototype = { __proto__: WebInspector.TextPrompt.prototype } WebInspector.ObjectPopoverHelper = function(panelElement, getAnchor, queryObject, onHide, disableOnClick) { WebInspector.PopoverHelper.call(this, panelElement, getAnchor, this._showObjectPopover.bind(this), this._onHideObjectPopover.bind(this), disableOnClick); this._queryObject = queryObject; this._onHideCallback = onHide; this._popoverObjectGroup = "popover"; panelElement.addEventListener("scroll", this.hidePopover.bind(this), true); }; WebInspector.ObjectPopoverHelper.prototype = { _showObjectPopover: function(element, popover) { function showObjectPopover(result, wasThrown, anchorOverride) { if (popover.disposed) return; if (wasThrown) { this.hidePopover(); return; } var anchorElement = anchorOverride || element; var popoverContentElement = null; if (result.type !== "object") { popoverContentElement = document.createElement("span"); popoverContentElement.className = "monospace console-formatted-" + result.type; popoverContentElement.style.whiteSpace = "pre"; popoverContentElement.textContent = result.description; if (result.type === "function") { function didGetDetails(error, response) { if (error) { console.error(error); return; } var container = document.createElement("div"); container.style.display = "inline-block"; var title = container.createChild("div", "function-popover-title source-code"); var functionName = title.createChild("span", "function-name"); functionName.textContent = response.name || response.inferredName || response.displayName || WebInspector.UIString("(anonymous function)"); this._linkifier = new WebInspector.Linkifier(); var rawLocation = (response.location); var link = this._linkifier.linkifyRawLocation(rawLocation, "function-location-link"); if (link) title.appendChild(link); container.appendChild(popoverContentElement); popover.show(container, anchorElement); } DebuggerAgent.getFunctionDetails(result.objectId, didGetDetails.bind(this)); return; } if (result.type === "string") popoverContentElement.textContent = "\"" + popoverContentElement.textContent + "\""; popover.show(popoverContentElement, anchorElement); } else { popoverContentElement = document.createElement("div"); this._titleElement = document.createElement("div"); this._titleElement.className = "source-frame-popover-title monospace"; this._titleElement.textContent = result.description; popoverContentElement.appendChild(this._titleElement); var section = new WebInspector.ObjectPropertiesSection(result); if (result.description.substr(0, 4) === "HTML") { this._sectionUpdateProperties = section.updateProperties.bind(section); section.updateProperties = this._updateHTMLId.bind(this); } section.expanded = true; section.element.addStyleClass("source-frame-popover-tree"); section.headerElement.addStyleClass("hidden"); popoverContentElement.appendChild(section.element); const popoverWidth = 300; const popoverHeight = 250; popover.show(popoverContentElement, anchorElement, popoverWidth, popoverHeight); } } this._queryObject(element, showObjectPopover.bind(this), this._popoverObjectGroup); }, _onHideObjectPopover: function() { if (this._linkifier) { this._linkifier.reset(); delete this._linkifier; } if (this._onHideCallback) this._onHideCallback(); RuntimeAgent.releaseObjectGroup(this._popoverObjectGroup); }, _updateHTMLId: function(properties, rootTreeElementConstructor, rootPropertyComparer) { for (var i = 0; i < properties.length; ++i) { if (properties[i].name === "id") { if (properties[i].value.description) this._titleElement.textContent += "#" + properties[i].value.description; break; } } this._sectionUpdateProperties(properties, rootTreeElementConstructor, rootPropertyComparer); }, __proto__: WebInspector.PopoverHelper.prototype } WebInspector.NativeBreakpointsSidebarPane = function(title) { WebInspector.SidebarPane.call(this, title); this.listElement = document.createElement("ol"); this.listElement.className = "breakpoint-list"; this.emptyElement = document.createElement("div"); this.emptyElement.className = "info"; this.emptyElement.textContent = WebInspector.UIString("No Breakpoints"); this.bodyElement.appendChild(this.emptyElement); } WebInspector.NativeBreakpointsSidebarPane.prototype = { _addListElement: function(element, beforeElement) { if (beforeElement) this.listElement.insertBefore(element, beforeElement); else { if (!this.listElement.firstChild) { this.bodyElement.removeChild(this.emptyElement); this.bodyElement.appendChild(this.listElement); } this.listElement.appendChild(element); } }, _removeListElement: function(element) { this.listElement.removeChild(element); if (!this.listElement.firstChild) { this.bodyElement.removeChild(this.listElement); this.bodyElement.appendChild(this.emptyElement); } }, _reset: function() { this.listElement.removeChildren(); if (this.listElement.parentElement) { this.bodyElement.removeChild(this.listElement); this.bodyElement.appendChild(this.emptyElement); } }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.DOMBreakpointsSidebarPane = function() { WebInspector.NativeBreakpointsSidebarPane.call(this, WebInspector.UIString("DOM Breakpoints")); this._breakpointElements = {}; this._breakpointTypes = { SubtreeModified: "subtree-modified", AttributeModified: "attribute-modified", NodeRemoved: "node-removed" }; this._breakpointTypeLabels = {}; this._breakpointTypeLabels[this._breakpointTypes.SubtreeModified] = WebInspector.UIString("Subtree Modified"); this._breakpointTypeLabels[this._breakpointTypes.AttributeModified] = WebInspector.UIString("Attribute Modified"); this._breakpointTypeLabels[this._breakpointTypes.NodeRemoved] = WebInspector.UIString("Node Removed"); this._contextMenuLabels = {}; this._contextMenuLabels[this._breakpointTypes.SubtreeModified] = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Subtree modifications" : "Subtree Modifications"); this._contextMenuLabels[this._breakpointTypes.AttributeModified] = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Attributes modifications" : "Attributes Modifications"); this._contextMenuLabels[this._breakpointTypes.NodeRemoved] = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Node removal" : "Node Removal"); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._inspectedURLChanged, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.NodeRemoved, this._nodeRemoved, this); } WebInspector.DOMBreakpointsSidebarPane.prototype = { _inspectedURLChanged: function(event) { this._breakpointElements = {}; this._reset(); var url = event.data; this._inspectedURL = url.removeURLFragment(); }, populateNodeContextMenu: function(node, contextMenu) { var nodeBreakpoints = {}; for (var id in this._breakpointElements) { var element = this._breakpointElements[id]; if (element._node === node) nodeBreakpoints[element._type] = true; } function toggleBreakpoint(type) { if (!nodeBreakpoints[type]) this._setBreakpoint(node, type, true); else this._removeBreakpoint(node, type); this._saveBreakpoints(); } var breakPointSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString("Break on...")); for (var key in this._breakpointTypes) { var type = this._breakpointTypes[key]; var label = this._contextMenuLabels[type]; breakPointSubMenu.appendCheckboxItem(label, toggleBreakpoint.bind(this, type), nodeBreakpoints[type]); } }, createBreakpointHitStatusMessage: function(auxData, callback) { if (auxData.type === this._breakpointTypes.SubtreeModified) { var targetNodeObject = WebInspector.RemoteObject.fromPayload(auxData["targetNode"]); function didPushNodeToFrontend(targetNodeId) { if (targetNodeId) targetNodeObject.release(); this._doCreateBreakpointHitStatusMessage(auxData, targetNodeId, callback); } targetNodeObject.pushNodeToFrontend(didPushNodeToFrontend.bind(this)); } else this._doCreateBreakpointHitStatusMessage(auxData, null, callback); }, _doCreateBreakpointHitStatusMessage: function (auxData, targetNodeId, callback) { var message; var typeLabel = this._breakpointTypeLabels[auxData.type]; var linkifiedNode = WebInspector.DOMPresentationUtils.linkifyNodeById(auxData.nodeId); var substitutions = [typeLabel, linkifiedNode]; var targetNode = ""; if (targetNodeId) targetNode = WebInspector.DOMPresentationUtils.linkifyNodeById(targetNodeId); if (auxData.type === this._breakpointTypes.SubtreeModified) { if (auxData.insertion) { if (targetNodeId !== auxData.nodeId) { message = "Paused on a \"%s\" breakpoint set on %s, because a new child was added to its descendant %s."; substitutions.push(targetNode); } else message = "Paused on a \"%s\" breakpoint set on %s, because a new child was added to that node."; } else { message = "Paused on a \"%s\" breakpoint set on %s, because its descendant %s was removed."; substitutions.push(targetNode); } } else message = "Paused on a \"%s\" breakpoint set on %s."; var element = document.createElement("span"); var formatters = { s: function(substitution) { return substitution; } }; function append(a, b) { if (typeof b === "string") b = document.createTextNode(b); element.appendChild(b); } WebInspector.formatLocalized(message, substitutions, formatters, "", append); callback(element); }, _nodeRemoved: function(event) { var node = event.data.node; this._removeBreakpointsForNode(event.data.node); if (!node.children) return; for (var i = 0; i < node.children.length; ++i) this._removeBreakpointsForNode(node.children[i]); this._saveBreakpoints(); }, _removeBreakpointsForNode: function(node) { for (var id in this._breakpointElements) { var element = this._breakpointElements[id]; if (element._node === node) this._removeBreakpoint(element._node, element._type); } }, _setBreakpoint: function(node, type, enabled) { var breakpointId = this._createBreakpointId(node.id, type); if (breakpointId in this._breakpointElements) return; var element = document.createElement("li"); element._node = node; element._type = type; element.addEventListener("contextmenu", this._contextMenu.bind(this, node, type), true); var checkboxElement = document.createElement("input"); checkboxElement.className = "checkbox-elem"; checkboxElement.type = "checkbox"; checkboxElement.checked = enabled; checkboxElement.addEventListener("click", this._checkboxClicked.bind(this, node, type), false); element._checkboxElement = checkboxElement; element.appendChild(checkboxElement); var labelElement = document.createElement("span"); element.appendChild(labelElement); var linkifiedNode = WebInspector.DOMPresentationUtils.linkifyNodeById(node.id); linkifiedNode.addStyleClass("monospace"); labelElement.appendChild(linkifiedNode); var description = document.createElement("div"); description.className = "source-text"; description.textContent = this._breakpointTypeLabels[type]; labelElement.appendChild(description); var currentElement = this.listElement.firstChild; while (currentElement) { if (currentElement._type && currentElement._type < element._type) break; currentElement = currentElement.nextSibling; } this._addListElement(element, currentElement); this._breakpointElements[breakpointId] = element; if (enabled) DOMDebuggerAgent.setDOMBreakpoint(node.id, type); }, _removeAllBreakpoints: function() { for (var id in this._breakpointElements) { var element = this._breakpointElements[id]; this._removeBreakpoint(element._node, element._type); } this._saveBreakpoints(); }, _removeBreakpoint: function(node, type) { var breakpointId = this._createBreakpointId(node.id, type); var element = this._breakpointElements[breakpointId]; if (!element) return; this._removeListElement(element); delete this._breakpointElements[breakpointId]; if (element._checkboxElement.checked) DOMDebuggerAgent.removeDOMBreakpoint(node.id, type); }, _contextMenu: function(node, type, event) { var contextMenu = new WebInspector.ContextMenu(event); function removeBreakpoint() { this._removeBreakpoint(node, type); this._saveBreakpoints(); } contextMenu.appendItem(WebInspector.UIString("Remove Breakpoint"), removeBreakpoint.bind(this)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Remove all DOM breakpoints" : "Remove All DOM Breakpoints"), this._removeAllBreakpoints.bind(this)); contextMenu.show(); }, _checkboxClicked: function(node, type, event) { if (event.target.checked) DOMDebuggerAgent.setDOMBreakpoint(node.id, type); else DOMDebuggerAgent.removeDOMBreakpoint(node.id, type); this._saveBreakpoints(); }, highlightBreakpoint: function(auxData) { var breakpointId = this._createBreakpointId(auxData.nodeId, auxData.type); var element = this._breakpointElements[breakpointId]; if (!element) return; this.expanded = true; element.addStyleClass("breakpoint-hit"); this._highlightedElement = element; }, clearBreakpointHighlight: function() { if (this._highlightedElement) { this._highlightedElement.removeStyleClass("breakpoint-hit"); delete this._highlightedElement; } }, _createBreakpointId: function(nodeId, type) { return nodeId + ":" + type; }, _saveBreakpoints: function() { var breakpoints = []; var storedBreakpoints = WebInspector.settings.domBreakpoints.get(); for (var i = 0; i < storedBreakpoints.length; ++i) { var breakpoint = storedBreakpoints[i]; if (breakpoint.url !== this._inspectedURL) breakpoints.push(breakpoint); } for (var id in this._breakpointElements) { var element = this._breakpointElements[id]; breakpoints.push({ url: this._inspectedURL, path: element._node.path(), type: element._type, enabled: element._checkboxElement.checked }); } WebInspector.settings.domBreakpoints.set(breakpoints); }, restoreBreakpoints: function() { var pathToBreakpoints = {}; function didPushNodeByPathToFrontend(path, nodeId) { var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) return; var breakpoints = pathToBreakpoints[path]; for (var i = 0; i < breakpoints.length; ++i) this._setBreakpoint(node, breakpoints[i].type, breakpoints[i].enabled); } var breakpoints = WebInspector.settings.domBreakpoints.get(); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; if (breakpoint.url !== this._inspectedURL) continue; var path = breakpoint.path; if (!pathToBreakpoints[path]) { pathToBreakpoints[path] = []; WebInspector.domAgent.pushNodeByPathToFrontend(path, didPushNodeByPathToFrontend.bind(this, path)); } pathToBreakpoints[path].push(breakpoint); } }, __proto__: WebInspector.NativeBreakpointsSidebarPane.prototype } WebInspector.domBreakpointsSidebarPane = null; WebInspector.Color = function(str) { this.value = str; this._parse(); } WebInspector.Color.fromRGBA = function(r, g, b, a) { return new WebInspector.Color("rgba(" + r + "," + g + "," + b + "," + (typeof a === "undefined" ? 1 : a) + ")"); } WebInspector.Color.fromRGB = function(r, g, b) { return new WebInspector.Color("rgb(" + r + "," + g + "," + b + ")"); } WebInspector.Color.prototype = { get shorthex() { if ("_short" in this) return this._short; if (!this.simple) return ""; var hex = this.hex; if (hex.charAt(0) === hex.charAt(1) && hex.charAt(2) === hex.charAt(3) && hex.charAt(4) === hex.charAt(5)) this._short = hex.charAt(0) + hex.charAt(2) + hex.charAt(4); else this._short = hex; return this._short; }, get hex() { if (!this.simple) return ""; return this._hex; }, set hex(x) { this._hex = x; }, get rgb() { if (this._rgb) return this._rgb; if (this.simple) this._rgb = this._hexToRGB(this.hex); else { var rgba = this.rgba; this._rgb = [rgba[0], rgba[1], rgba[2]]; } return this._rgb; }, set rgb(x) { this._rgb = x; }, get hsl() { if (this._hsl) return this._hsl; this._hsl = this._rgbToHSL(this.rgb); return this._hsl; }, set hsl(x) { this._hsl = x; }, get nickname() { if (typeof this._nickname !== "undefined") return this._nickname; else return ""; }, set nickname(x) { this._nickname = x; }, get rgba() { return this._rgba; }, set rgba(x) { this._rgba = x; }, get hsla() { return this._hsla; }, set hsla(x) { this._hsla = x; }, hasShortHex: function() { var shorthex = this.shorthex; return (!!shorthex && shorthex.length === 3); }, toString: function(format) { if (!format) format = this.format; switch (format) { case "original": return this.value; case "rgb": return "rgb(" + this.rgb.join(", ") + ")"; case "rgba": return "rgba(" + this.rgba.join(", ") + ")"; case "hsl": var hsl = this.hsl; return "hsl(" + hsl[0] + ", " + hsl[1] + "%, " + hsl[2] + "%)"; case "hsla": var hsla = this.hsla; return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; case "hex": return "#" + this.hex; case "shorthex": return "#" + this.shorthex; case "nickname": return this.nickname; } throw "invalid color format"; }, toProtocolRGBA: function() { if (this._protocolRGBA) return this._protocolRGBA; var components = this.rgba; if (components) this._protocolRGBA = { r: Number(components[0]), g: Number(components[1]), b: Number(components[2]), a: Number(components[3]) }; else { components = this.rgb; this._protocolRGBA = { r: Number(components[0]), g: Number(components[1]), b: Number(components[2]) }; } return this._protocolRGBA; }, _clamp: function(value, min, max) { if (value < min) return min; if (value > max) return max; return value; }, _individualRGBValueToFloatValue: function(rgbValue) { if (typeof rgbValue === "number") return this._clamp(rgbValue, 0, 255); if (rgbValue.indexOf("%") === -1) { var intValue = parseInt(rgbValue, 10); return this._clamp(intValue, 0, 255); } var percentValue = parseFloat(rgbValue); return this._clamp(percentValue, 0, 100) * 2.55; }, _individualRGBValueToHexValue: function(rgbValue) { var floatValue = this._individualRGBValueToFloatValue(rgbValue); var hex = Math.round(floatValue).toString(16); if (hex.length === 1) hex = "0" + hex; return hex; }, _rgbStringsToHex: function(rgb) { var r = this._individualRGBValueToHexValue(rgb[0]); var g = this._individualRGBValueToHexValue(rgb[1]); var b = this._individualRGBValueToHexValue(rgb[2]); return (r + g + b).toUpperCase(); }, _rgbToHex: function(rgb) { var r = this._individualRGBValueToHexValue(rgb[0]); var g = this._individualRGBValueToHexValue(rgb[1]); var b = this._individualRGBValueToHexValue(rgb[2]); return (r + g + b).toUpperCase(); }, _hexToRGB: function(hex) { var r = parseInt(hex.substring(0,2), 16); var g = parseInt(hex.substring(2,4), 16); var b = parseInt(hex.substring(4,6), 16); return [r, g, b]; }, _rgbToHSL: function(rgb) { var r = this._individualRGBValueToFloatValue(rgb[0]) / 255; var g = this._individualRGBValueToFloatValue(rgb[1]) / 255; var b = this._individualRGBValueToFloatValue(rgb[2]) / 255; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var diff = max - min; var add = max + min; if (min === max) var h = 0; else if (r === max) var h = ((60 * (g - b) / diff) + 360) % 360; else if (g === max) var h = (60 * (b - r) / diff) + 120; else var h = (60 * (r - g) / diff) + 240; var l = 0.5 * add; if (l === 0) var s = 0; else if (l === 1) var s = 1; else if (l <= 0.5) var s = diff / add; else var s = diff / (2 - add); h = Math.round(h); s = Math.round(s*100); l = Math.round(l*100); return [h, s, l]; }, _hslToRGB: function(hsl) { var h = parseFloat(hsl[0]) / 360; var s = parseFloat(hsl[1]) / 100; var l = parseFloat(hsl[2]) / 100; if (s < 0) s = 0; if (l <= 0.5) var q = l * (1 + s); else var q = l + s - (l * s); var p = 2 * l - q; var tr = h + (1 / 3); var tg = h; var tb = h - (1 / 3); var r = Math.round(hueToRGB(p, q, tr) * 255); var g = Math.round(hueToRGB(p, q, tg) * 255); var b = Math.round(hueToRGB(p, q, tb) * 255); return [r, g, b]; function hueToRGB(p, q, h) { if (h < 0) h += 1; else if (h > 1) h -= 1; if ((h * 6) < 1) return p + (q - p) * h * 6; else if ((h * 2) < 1) return q; else if ((h * 3) < 2) return p + (q - p) * ((2 / 3) - h) * 6; else return p; } }, _rgbaToHSLA: function(rgba, alpha) { var hsl = this._rgbToHSL(rgba) hsl.push(alpha); return hsl; }, _hslaToRGBA: function(hsla, alpha) { var rgb = this._hslToRGB(hsla); rgb.push(alpha); return rgb; }, _parse: function() { var value = this.value.toLowerCase().replace(/%|\s+/g, ""); if (value in WebInspector.Color.AdvancedNickNames) { this.format = "nickname"; var set = WebInspector.Color.AdvancedNickNames[value]; this.simple = false; this.rgba = set[0]; this.hsla = set[1]; this.nickname = set[2]; this.alpha = set[0][3]; return; } var simple = /^(?:#([0-9a-f]{3,6})|rgb\(([^)]+)\)|(\w+)|hsl\(([^)]+)\))$/i; var match = this.value.match(simple); if (match) { this.simple = true; if (match[1]) { var hex = match[1].toUpperCase(); if (hex.length === 3) { this.format = "shorthex"; this.hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) + hex.charAt(2) + hex.charAt(2); } else { this.format = "hex"; this.hex = hex; } } else if (match[2]) { this.format = "rgb"; var rgb = match[2].split(/\s*,\s*/); this.rgb = rgb; this.hex = this._rgbStringsToHex(rgb); } else if (match[3]) { var nickname = match[3].toLowerCase(); if (nickname in WebInspector.Color.Nicknames) { this.format = "nickname"; this.hex = WebInspector.Color.Nicknames[nickname]; } else throw "unknown color name"; } else if (match[4]) { this.format = "hsl"; var hsl = match[4].replace(/%/g, "").split(/\s*,\s*/); this.hsl = hsl; this.rgb = this._hslToRGB(hsl); this.hex = this._rgbToHex(this.rgb); } var hex = this.hex; if (hex && hex in WebInspector.Color.HexTable) { var set = WebInspector.Color.HexTable[hex]; this.rgb = set[0]; this.hsl = set[1]; this.nickname = set[2]; } return; } var advanced = /^(?:rgba\(([^)]+)\)|hsla\(([^)]+)\))$/; match = this.value.match(advanced); if (match) { this.simple = false; if (match[1]) { this.format = "rgba"; this.rgba = match[1].split(/\s*,\s*/); this.rgba[3] = this.alpha = this._clamp(this.rgba[3], 0, 1); this.hsla = this._rgbaToHSLA(this.rgba, this.alpha); } else if (match[2]) { this.format = "hsla"; this.hsla = match[2].replace(/%/g, "").split(/\s*,\s*/); this.hsla[3] = this.alpha = this._clamp(this.hsla[3], 0, 1); this.rgba = this._hslaToRGBA(this.hsla, this.alpha); } return; } throw "could not parse color"; } } WebInspector.Color.HexTable = { "000000": [[0, 0, 0], [0, 0, 0], "black"], "000080": [[0, 0, 128], [240, 100, 25], "navy"], "00008B": [[0, 0, 139], [240, 100, 27], "darkBlue"], "0000CD": [[0, 0, 205], [240, 100, 40], "mediumBlue"], "0000FF": [[0, 0, 255], [240, 100, 50], "blue"], "006400": [[0, 100, 0], [120, 100, 20], "darkGreen"], "008000": [[0, 128, 0], [120, 100, 25], "green"], "008080": [[0, 128, 128], [180, 100, 25], "teal"], "008B8B": [[0, 139, 139], [180, 100, 27], "darkCyan"], "00BFFF": [[0, 191, 255], [195, 100, 50], "deepSkyBlue"], "00CED1": [[0, 206, 209], [181, 100, 41], "darkTurquoise"], "00FA9A": [[0, 250, 154], [157, 100, 49], "mediumSpringGreen"], "00FF00": [[0, 255, 0], [120, 100, 50], "lime"], "00FF7F": [[0, 255, 127], [150, 100, 50], "springGreen"], "00FFFF": [[0, 255, 255], [180, 100, 50], "cyan"], "191970": [[25, 25, 112], [240, 64, 27], "midnightBlue"], "1E90FF": [[30, 144, 255], [210, 100, 56], "dodgerBlue"], "20B2AA": [[32, 178, 170], [177, 70, 41], "lightSeaGreen"], "228B22": [[34, 139, 34], [120, 61, 34], "forestGreen"], "2E8B57": [[46, 139, 87], [146, 50, 36], "seaGreen"], "2F4F4F": [[47, 79, 79], [180, 25, 25], "darkSlateGray"], "32CD32": [[50, 205, 50], [120, 61, 50], "limeGreen"], "3CB371": [[60, 179, 113], [147, 50, 47], "mediumSeaGreen"], "40E0D0": [[64, 224, 208], [174, 72, 56], "turquoise"], "4169E1": [[65, 105, 225], [225, 73, 57], "royalBlue"], "4682B4": [[70, 130, 180], [207, 44, 49], "steelBlue"], "483D8B": [[72, 61, 139], [248, 39, 39], "darkSlateBlue"], "48D1CC": [[72, 209, 204], [178, 60, 55], "mediumTurquoise"], "4B0082": [[75, 0, 130], [275, 100, 25], "indigo"], "556B2F": [[85, 107, 47], [82, 39, 30], "darkOliveGreen"], "5F9EA0": [[95, 158, 160], [182, 25, 50], "cadetBlue"], "6495ED": [[100, 149, 237], [219, 79, 66], "cornflowerBlue"], "66CDAA": [[102, 205, 170], [160, 51, 60], "mediumAquaMarine"], "696969": [[105, 105, 105], [0, 0, 41], "dimGray"], "6A5ACD": [[106, 90, 205], [248, 53, 58], "slateBlue"], "6B8E23": [[107, 142, 35], [80, 60, 35], "oliveDrab"], "708090": [[112, 128, 144], [210, 13, 50], "slateGray"], "778899": [[119, 136, 153], [210, 14, 53], "lightSlateGray"], "7B68EE": [[123, 104, 238], [249, 80, 67], "mediumSlateBlue"], "7CFC00": [[124, 252, 0], [90, 100, 49], "lawnGreen"], "7FFF00": [[127, 255, 0], [90, 100, 50], "chartreuse"], "7FFFD4": [[127, 255, 212], [160, 100, 75], "aquamarine"], "800000": [[128, 0, 0], [0, 100, 25], "maroon"], "800080": [[128, 0, 128], [300, 100, 25], "purple"], "808000": [[128, 128, 0], [60, 100, 25], "olive"], "808080": [[128, 128, 128], [0, 0, 50], "gray"], "87CEEB": [[135, 206, 235], [197, 71, 73], "skyBlue"], "87CEFA": [[135, 206, 250], [203, 92, 75], "lightSkyBlue"], "8A2BE2": [[138, 43, 226], [271, 76, 53], "blueViolet"], "8B0000": [[139, 0, 0], [0, 100, 27], "darkRed"], "8B008B": [[139, 0, 139], [300, 100, 27], "darkMagenta"], "8B4513": [[139, 69, 19], [25, 76, 31], "saddleBrown"], "8FBC8F": [[143, 188, 143], [120, 25, 65], "darkSeaGreen"], "90EE90": [[144, 238, 144], [120, 73, 75], "lightGreen"], "9370D8": [[147, 112, 219], [260, 60, 65], "mediumPurple"], "9400D3": [[148, 0, 211], [282, 100, 41], "darkViolet"], "98FB98": [[152, 251, 152], [120, 93, 79], "paleGreen"], "9932CC": [[153, 50, 204], [280, 61, 50], "darkOrchid"], "9ACD32": [[154, 205, 50], [80, 61, 50], "yellowGreen"], "A0522D": [[160, 82, 45], [19, 56, 40], "sienna"], "A52A2A": [[165, 42, 42], [0, 59, 41], "brown"], "A9A9A9": [[169, 169, 169], [0, 0, 66], "darkGray"], "ADD8E6": [[173, 216, 230], [195, 53, 79], "lightBlue"], "ADFF2F": [[173, 255, 47], [84, 100, 59], "greenYellow"], "AFEEEE": [[175, 238, 238], [180, 65, 81], "paleTurquoise"], "B0C4DE": [[176, 196, 222], [214, 41, 78], "lightSteelBlue"], "B0E0E6": [[176, 224, 230], [187, 52, 80], "powderBlue"], "B22222": [[178, 34, 34], [0, 68, 42], "fireBrick"], "B8860B": [[184, 134, 11], [43, 89, 38], "darkGoldenrod"], "BA55D3": [[186, 85, 211], [288, 59, 58], "mediumOrchid"], "BC8F8F": [[188, 143, 143], [0, 25, 65], "rosyBrown"], "BDB76B": [[189, 183, 107], [56, 38, 58], "darkKhaki"], "C0C0C0": [[192, 192, 192], [0, 0, 75], "silver"], "C71585": [[199, 21, 133], [322, 81, 43], "mediumVioletRed"], "CD5C5C": [[205, 92, 92], [0, 53, 58], "indianRed"], "CD853F": [[205, 133, 63], [30, 59, 53], "peru"], "D2691E": [[210, 105, 30], [25, 75, 47], "chocolate"], "D2B48C": [[210, 180, 140], [34, 44, 69], "tan"], "D3D3D3": [[211, 211, 211], [0, 0, 83], "lightGrey"], "D87093": [[219, 112, 147], [340, 60, 65], "paleVioletRed"], "D8BFD8": [[216, 191, 216], [300, 24, 80], "thistle"], "DA70D6": [[218, 112, 214], [302, 59, 65], "orchid"], "DAA520": [[218, 165, 32], [43, 74, 49], "goldenrod"], "DC143C": [[237, 164, 61], [35, 83, 58], "crimson"], "DCDCDC": [[220, 220, 220], [0, 0, 86], "gainsboro"], "DDA0DD": [[221, 160, 221], [300, 47, 75], "plum"], "DEB887": [[222, 184, 135], [34, 57, 70], "burlyWood"], "E0FFFF": [[224, 255, 255], [180, 100, 94], "lightCyan"], "E6E6FA": [[230, 230, 250], [240, 67, 94], "lavender"], "E9967A": [[233, 150, 122], [15, 72, 70], "darkSalmon"], "EE82EE": [[238, 130, 238], [300, 76, 72], "violet"], "EEE8AA": [[238, 232, 170], [55, 67, 80], "paleGoldenrod"], "F08080": [[240, 128, 128], [0, 79, 72], "lightCoral"], "F0E68C": [[240, 230, 140], [54, 77, 75], "khaki"], "F0F8FF": [[240, 248, 255], [208, 100, 97], "aliceBlue"], "F0FFF0": [[240, 255, 240], [120, 100, 97], "honeyDew"], "F0FFFF": [[240, 255, 255], [180, 100, 97], "azure"], "F4A460": [[244, 164, 96], [28, 87, 67], "sandyBrown"], "F5DEB3": [[245, 222, 179], [39, 77, 83], "wheat"], "F5F5DC": [[245, 245, 220], [60, 56, 91], "beige"], "F5F5F5": [[245, 245, 245], [0, 0, 96], "whiteSmoke"], "F5FFFA": [[245, 255, 250], [150, 100, 98], "mintCream"], "F8F8FF": [[248, 248, 255], [240, 100, 99], "ghostWhite"], "FA8072": [[250, 128, 114], [6, 93, 71], "salmon"], "FAEBD7": [[250, 235, 215], [34, 78, 91], "antiqueWhite"], "FAF0E6": [[250, 240, 230], [30, 67, 94], "linen"], "FAFAD2": [[250, 250, 210], [60, 80, 90], "lightGoldenrodYellow"], "FDF5E6": [[253, 245, 230], [39, 85, 95], "oldLace"], "FF0000": [[255, 0, 0], [0, 100, 50], "red"], "FF00FF": [[255, 0, 255], [300, 100, 50], "magenta"], "FF1493": [[255, 20, 147], [328, 100, 54], "deepPink"], "FF4500": [[255, 69, 0], [16, 100, 50], "orangeRed"], "FF6347": [[255, 99, 71], [9, 100, 64], "tomato"], "FF69B4": [[255, 105, 180], [330, 100, 71], "hotPink"], "FF7F50": [[255, 127, 80], [16, 100, 66], "coral"], "FF8C00": [[255, 140, 0], [33, 100, 50], "darkOrange"], "FFA07A": [[255, 160, 122], [17, 100, 74], "lightSalmon"], "FFA500": [[255, 165, 0], [39, 100, 50], "orange"], "FFB6C1": [[255, 182, 193], [351, 100, 86], "lightPink"], "FFC0CB": [[255, 192, 203], [350, 100, 88], "pink"], "FFD700": [[255, 215, 0], [51, 100, 50], "gold"], "FFDAB9": [[255, 218, 185], [28, 100, 86], "peachPuff"], "FFDEAD": [[255, 222, 173], [36, 100, 84], "navajoWhite"], "FFE4B5": [[255, 228, 181], [38, 100, 85], "moccasin"], "FFE4C4": [[255, 228, 196], [33, 100, 88], "bisque"], "FFE4E1": [[255, 228, 225], [6, 100, 94], "mistyRose"], "FFEBCD": [[255, 235, 205], [36, 100, 90], "blanchedAlmond"], "FFEFD5": [[255, 239, 213], [37, 100, 92], "papayaWhip"], "FFF0F5": [[255, 240, 245], [340, 100, 97], "lavenderBlush"], "FFF5EE": [[255, 245, 238], [25, 100, 97], "seaShell"], "FFF8DC": [[255, 248, 220], [48, 100, 93], "cornsilk"], "FFFACD": [[255, 250, 205], [54, 100, 90], "lemonChiffon"], "FFFAF0": [[255, 250, 240], [40, 100, 97], "floralWhite"], "FFFAFA": [[255, 250, 250], [0, 100, 99], "snow"], "FFFF00": [[255, 255, 0], [60, 100, 50], "yellow"], "FFFFE0": [[255, 255, 224], [60, 100, 94], "lightYellow"], "FFFFF0": [[255, 255, 240], [60, 100, 97], "ivory"], "FFFFFF": [[255, 255, 255], [0, 100, 100], "white"] }; WebInspector.Color.Nicknames = { "aliceblue": "F0F8FF", "antiquewhite": "FAEBD7", "aqua": "00FFFF", "aquamarine": "7FFFD4", "azure": "F0FFFF", "beige": "F5F5DC", "bisque": "FFE4C4", "black": "000000", "blanchedalmond": "FFEBCD", "blue": "0000FF", "blueviolet": "8A2BE2", "brown": "A52A2A", "burlywood": "DEB887", "cadetblue": "5F9EA0", "chartreuse": "7FFF00", "chocolate": "D2691E", "coral": "FF7F50", "cornflowerblue": "6495ED", "cornsilk": "FFF8DC", "crimson": "DC143C", "cyan": "00FFFF", "darkblue": "00008B", "darkcyan": "008B8B", "darkgoldenrod": "B8860B", "darkgray": "A9A9A9", "darkgreen": "006400", "darkkhaki": "BDB76B", "darkmagenta": "8B008B", "darkolivegreen": "556B2F", "darkorange": "FF8C00", "darkorchid": "9932CC", "darkred": "8B0000", "darksalmon": "E9967A", "darkseagreen": "8FBC8F", "darkslateblue": "483D8B", "darkslategray": "2F4F4F", "darkturquoise": "00CED1", "darkviolet": "9400D3", "deeppink": "FF1493", "deepskyblue": "00BFFF", "dimgray": "696969", "dodgerblue": "1E90FF", "firebrick": "B22222", "floralwhite": "FFFAF0", "forestgreen": "228B22", "fuchsia": "FF00FF", "gainsboro": "DCDCDC", "ghostwhite": "F8F8FF", "gold": "FFD700", "goldenrod": "DAA520", "gray": "808080", "green": "008000", "greenyellow": "ADFF2F", "honeydew": "F0FFF0", "hotpink": "FF69B4", "indianred": "CD5C5C", "indigo": "4B0082", "ivory": "FFFFF0", "khaki": "F0E68C", "lavender": "E6E6FA", "lavenderblush": "FFF0F5", "lawngreen": "7CFC00", "lemonchiffon": "FFFACD", "lightblue": "ADD8E6", "lightcoral": "F08080", "lightcyan": "E0FFFF", "lightgoldenrodyellow": "FAFAD2", "lightgreen": "90EE90", "lightgrey": "D3D3D3", "lightpink": "FFB6C1", "lightsalmon": "FFA07A", "lightseagreen": "20B2AA", "lightskyblue": "87CEFA", "lightslategray": "778899", "lightsteelblue": "B0C4DE", "lightyellow": "FFFFE0", "lime": "00FF00", "limegreen": "32CD32", "linen": "FAF0E6", "magenta": "FF00FF", "maroon": "800000", "mediumaquamarine": "66CDAA", "mediumblue": "0000CD", "mediumorchid": "BA55D3", "mediumpurple": "9370DB", "mediumseagreen": "3CB371", "mediumslateblue": "7B68EE", "mediumspringgreen": "00FA9A", "mediumturquoise": "48D1CC", "mediumvioletred": "C71585", "midnightblue": "191970", "mintcream": "F5FFFA", "mistyrose": "FFE4E1", "moccasin": "FFE4B5", "navajowhite": "FFDEAD", "navy": "000080", "oldlace": "FDF5E6", "olive": "808000", "olivedrab": "6B8E23", "orange": "FFA500", "orangered": "FF4500", "orchid": "DA70D6", "palegoldenrod": "EEE8AA", "palegreen": "98FB98", "paleturquoise": "AFEEEE", "palevioletred": "DB7093", "papayawhip": "FFEFD5", "peachpuff": "FFDAB9", "peru": "CD853F", "pink": "FFC0CB", "plum": "DDA0DD", "powderblue": "B0E0E6", "purple": "800080", "red": "FF0000", "rosybrown": "BC8F8F", "royalblue": "4169E1", "saddlebrown": "8B4513", "salmon": "FA8072", "sandybrown": "F4A460", "seagreen": "2E8B57", "seashell": "FFF5EE", "sienna": "A0522D", "silver": "C0C0C0", "skyblue": "87CEEB", "slateblue": "6A5ACD", "slategray": "708090", "snow": "FFFAFA", "springgreen": "00FF7F", "steelblue": "4682B4", "tan": "D2B48C", "teal": "008080", "thistle": "D8BFD8", "tomato": "FF6347", "turquoise": "40E0D0", "violet": "EE82EE", "wheat": "F5DEB3", "white": "FFFFFF", "whitesmoke": "F5F5F5", "yellow": "FFFF00", "yellowgreen": "9ACD32" }; WebInspector.Color.AdvancedNickNames = { "transparent": [[0, 0, 0, 0], [0, 0, 0, 0], "transparent"], "rgba(0,0,0,0)": [[0, 0, 0, 0], [0, 0, 0, 0], "transparent"], "hsla(0,0,0,0)": [[0, 0, 0, 0], [0, 0, 0, 0], "transparent"], }; WebInspector.Color.PageHighlight = { Content: WebInspector.Color.fromRGBA(111, 168, 220, .66), ContentLight: WebInspector.Color.fromRGBA(111, 168, 220, .5), ContentOutline: WebInspector.Color.fromRGBA(9, 83, 148), Padding: WebInspector.Color.fromRGBA(147, 196, 125, .55), PaddingLight: WebInspector.Color.fromRGBA(147, 196, 125, .4), Border: WebInspector.Color.fromRGBA(255, 229, 153, .66), BorderLight: WebInspector.Color.fromRGBA(255, 229, 153, .5), Margin: WebInspector.Color.fromRGBA(246, 178, 107, .66), MarginLight: WebInspector.Color.fromRGBA(246, 178, 107, .5) } WebInspector.Color.Format = { Original: "original", Nickname: "nickname", HEX: "hex", ShortHEX: "shorthex", RGB: "rgb", RGBA: "rgba", HSL: "hsl", HSLA: "hsla" } WebInspector.CSSMetadata = function(properties) { this._values = []; this._longhands = {}; this._shorthands = {}; for (var i = 0; i < properties.length; ++i) { var property = properties[i]; if (typeof property === "string") { this._values.push(property); continue; } var propertyName = property.name; this._values.push(propertyName); var longhands = properties[i].longhands; if (longhands) { this._longhands[propertyName] = longhands; for (var j = 0; j < longhands.length; ++j) { var longhandName = longhands[j]; var shorthands = this._shorthands[longhandName]; if (!shorthands) { shorthands = []; this._shorthands[longhandName] = shorthands; } shorthands.push(propertyName); } } } this._values.sort(); } WebInspector.CSSMetadata.cssPropertiesMetainfo = null; WebInspector.CSSMetadata.isColorAwareProperty = function(propertyName) { return WebInspector.CSSMetadata._colorAwareProperties[propertyName] === true; } WebInspector.CSSMetadata.colors = function() { if (!WebInspector.CSSMetadata._colorsKeySet) WebInspector.CSSMetadata._colorsKeySet = WebInspector.CSSMetadata._colors.keySet(); return WebInspector.CSSMetadata._colorsKeySet; } WebInspector.CSSMetadata.InheritedProperties = [ "azimuth", "border-collapse", "border-spacing", "caption-side", "color", "cursor", "direction", "elevation", "empty-cells", "font-family", "font-size", "font-style", "font-variant", "font-weight", "font", "letter-spacing", "line-height", "list-style-image", "list-style-position", "list-style-type", "list-style", "orphans", "pitch-range", "pitch", "quotes", "resize", "richness", "speak-header", "speak-numeral", "speak-punctuation", "speak", "speech-rate", "stress", "text-align", "text-indent", "text-transform", "text-shadow", "visibility", "voice-family", "volume", "white-space", "widows", "word-spacing", "zoom" ].keySet(); WebInspector.CSSMetadata._colors = [ "aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow", "transparent", "currentcolor", "grey", "aliceblue", "antiquewhite", "aquamarine", "azure", "beige", "bisque", "blanchedalmond", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "gainsboro", "ghostwhite", "gold", "goldenrod", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "limegreen", "linen", "magenta", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "oldlace", "olivedrab", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "thistle", "tomato", "turquoise", "violet", "wheat", "whitesmoke", "yellowgreen" ]; WebInspector.CSSMetadata._colorAwareProperties = [ "background", "background-color", "background-image", "border", "border-color", "border-top", "border-right", "border-bottom", "border-left", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "box-shadow", "color", "fill", "outline", "outline-color", "stroke", "text-line-through", "text-line-through-color", "text-overline", "text-overline-color", "text-shadow", "text-underline", "text-underline-color", "-webkit-box-shadow", "-webkit-column-rule-color", "-webkit-text-decoration-color", "-webkit-text-emphasis", "-webkit-text-emphasis-color" ].keySet(); WebInspector.CSSMetadata._propertyDataMap = { "table-layout": { values: [ "auto", "fixed" ] }, "visibility": { values: [ "hidden", "visible", "collapse" ] }, "background-repeat": { values: [ "repeat", "repeat-x", "repeat-y", "no-repeat", "space", "round" ] }, "text-underline": { values: [ "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" ] }, "content": { values: [ "list-item", "close-quote", "no-close-quote", "no-open-quote", "open-quote" ] }, "list-style-image": { values: [ "none" ] }, "clear": { values: [ "none", "left", "right", "both" ] }, "text-underline-mode": { values: [ "continuous", "skip-white-space" ] }, "overflow-x": { values: [ "hidden", "auto", "visible", "overlay", "scroll" ] }, "stroke-linejoin": { values: [ "round", "miter", "bevel" ] }, "baseline-shift": { values: [ "baseline", "sub", "super" ] }, "border-bottom-width": { values: [ "medium", "thick", "thin" ] }, "marquee-speed": { values: [ "normal", "slow", "fast" ] }, "margin-top-collapse": { values: [ "collapse", "separate", "discard" ] }, "max-height": { values: [ "none" ] }, "box-orient": { values: [ "horizontal", "vertical", "inline-axis", "block-axis" ], }, "font-stretch": { values: [ "normal", "wider", "narrower", "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded" ] }, "-webkit-color-correction": { values: [ "default", "srgb" ] }, "text-underline-style": { values: [ "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" ] }, "text-overline-mode": { values: [ "continuous", "skip-white-space" ] }, "-webkit-background-composite": { values: [ "highlight", "clear", "copy", "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "xor", "plus-darker", "plus-lighter" ] }, "border-left-width": { values: [ "medium", "thick", "thin" ] }, "-webkit-writing-mode": { values: [ "lr", "rl", "tb", "lr-tb", "rl-tb", "tb-rl", "horizontal-tb", "vertical-rl", "vertical-lr", "horizontal-bt" ] }, "text-line-through-mode": { values: [ "continuous", "skip-white-space" ] }, "border-collapse": { values: [ "collapse", "separate" ] }, "page-break-inside": { values: [ "auto", "avoid" ] }, "border-top-width": { values: [ "medium", "thick", "thin" ] }, "outline-color": { values: [ "invert" ] }, "text-line-through-style": { values: [ "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" ] }, "outline-style": { values: [ "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" ] }, "cursor": { values: [ "none", "copy", "auto", "crosshair", "default", "pointer", "move", "vertical-text", "cell", "context-menu", "alias", "progress", "no-drop", "not-allowed", "-webkit-zoom-in", "-webkit-zoom-out", "e-resize", "ne-resize", "nw-resize", "n-resize", "se-resize", "sw-resize", "s-resize", "w-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "col-resize", "row-resize", "text", "wait", "help", "all-scroll", "-webkit-grab", "-webkit-grabbing" ] }, "border-width": { values: [ "medium", "thick", "thin" ] }, "size": { values: [ "a3", "a4", "a5", "b4", "b5", "landscape", "ledger", "legal", "letter", "portrait" ] }, "background-size": { values: [ "contain", "cover" ] }, "direction": { values: [ "ltr", "rtl" ] }, "marquee-direction": { values: [ "left", "right", "auto", "reverse", "forwards", "backwards", "ahead", "up", "down" ] }, "enable-background": { values: [ "accumulate", "new" ] }, "float": { values: [ "none", "left", "right" ] }, "overflow-y": { values: [ "hidden", "auto", "visible", "overlay", "scroll" ] }, "margin-bottom-collapse": { values: [ "collapse", "separate", "discard" ] }, "box-reflect": { values: [ "left", "right", "above", "below" ] }, "overflow": { values: [ "hidden", "auto", "visible", "overlay", "scroll" ] }, "text-rendering": { values: [ "auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision" ] }, "text-align": { values: [ "-webkit-auto", "start", "end", "left", "right", "center", "justify", "-webkit-left", "-webkit-right", "-webkit-center" ] }, "list-style-position": { values: [ "outside", "inside", "hanging" ] }, "margin-bottom": { values: [ "auto" ] }, "color-interpolation": { values: [ "linearrgb" ] }, "background-origin": { values: [ "border-box", "content-box", "padding-box" ] }, "word-wrap": { values: [ "normal", "break-word" ] }, "font-weight": { values: [ "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" ] }, "margin-before-collapse": { values: [ "collapse", "separate", "discard" ] }, "text-overline-width": { values: [ "normal", "medium", "auto", "thick", "thin" ] }, "text-transform": { values: [ "none", "capitalize", "uppercase", "lowercase" ] }, "border-right-style": { values: [ "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" ] }, "border-left-style": { values: [ "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" ] }, "-webkit-text-emphasis": { values: [ "circle", "filled", "open", "dot", "double-circle", "triangle", "sesame" ] }, "font-style": { values: [ "italic", "oblique", "normal" ] }, "speak": { values: [ "none", "normal", "spell-out", "digits", "literal-punctuation", "no-punctuation" ] }, "text-line-through": { values: [ "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave", "continuous", "skip-white-space" ] }, "color-rendering": { values: [ "auto", "optimizeSpeed", "optimizeQuality" ] }, "list-style-type": { values: [ "none", "inline", "disc", "circle", "square", "decimal", "decimal-leading-zero", "arabic-indic", "binary", "bengali", "cambodian", "khmer", "devanagari", "gujarati", "gurmukhi", "kannada", "lower-hexadecimal", "lao", "malayalam", "mongolian", "myanmar", "octal", "oriya", "persian", "urdu", "telugu", "tibetan", "thai", "upper-hexadecimal", "lower-roman", "upper-roman", "lower-greek", "lower-alpha", "lower-latin", "upper-alpha", "upper-latin", "afar", "ethiopic-halehame-aa-et", "ethiopic-halehame-aa-er", "amharic", "ethiopic-halehame-am-et", "amharic-abegede", "ethiopic-abegede-am-et", "cjk-earthly-branch", "cjk-heavenly-stem", "ethiopic", "ethiopic-halehame-gez", "ethiopic-abegede", "ethiopic-abegede-gez", "hangul-consonant", "hangul", "lower-norwegian", "oromo", "ethiopic-halehame-om-et", "sidama", "ethiopic-halehame-sid-et", "somali", "ethiopic-halehame-so-et", "tigre", "ethiopic-halehame-tig", "tigrinya-er", "ethiopic-halehame-ti-er", "tigrinya-er-abegede", "ethiopic-abegede-ti-er", "tigrinya-et", "ethiopic-halehame-ti-et", "tigrinya-et-abegede", "ethiopic-abegede-ti-et", "upper-greek", "upper-norwegian", "asterisks", "footnotes", "hebrew", "armenian", "lower-armenian", "upper-armenian", "georgian", "cjk-ideographic", "hiragana", "katakana", "hiragana-iroha", "katakana-iroha" ] }, "-webkit-text-combine": { values: [ "none", "horizontal" ] }, "outline": { values: [ "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" ] }, "font": { values: [ "caption", "icon", "menu", "message-box", "small-caption", "-webkit-mini-control", "-webkit-small-control", "-webkit-control", "status-bar", "italic", "oblique", "small-caps", "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900", "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "-webkit-xxx-large", "smaller", "larger", "serif", "sans-serif", "cursive", "fantasy", "monospace", "-webkit-body", "-webkit-pictograph" ] }, "dominant-baseline": { values: [ "middle", "auto", "central", "text-before-edge", "text-after-edge", "ideographic", "alphabetic", "hanging", "mathematical", "use-script", "no-change", "reset-size" ] }, "display": { values: [ "none", "inline", "block", "list-item", "run-in", "compact", "inline-block", "table", "inline-table", "table-row-group", "table-header-group", "table-footer-group", "table-row", "table-column-group", "table-column", "table-cell", "table-caption", "-webkit-box", "-webkit-inline-box", "-wap-marquee" ] }, "-webkit-text-emphasis-position": { values: [ "over", "under" ] }, "image-rendering": { values: [ "auto", "optimizeSpeed", "optimizeQuality" ] }, "alignment-baseline": { values: [ "baseline", "middle", "auto", "before-edge", "after-edge", "central", "text-before-edge", "text-after-edge", "ideographic", "alphabetic", "hanging", "mathematical" ] }, "outline-width": { values: [ "medium", "thick", "thin" ] }, "text-line-through-width": { values: [ "normal", "medium", "auto", "thick", "thin" ] }, "box-align": { values: [ "baseline", "center", "stretch", "start", "end" ] }, "border-right-width": { values: [ "medium", "thick", "thin" ] }, "border-top-style": { values: [ "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" ] }, "line-height": { values: [ "normal" ] }, "text-overflow": { values: [ "clip", "ellipsis" ] }, "overflow-wrap": { values: [ "normal", "break-word" ] }, "box-direction": { values: [ "normal", "reverse" ] }, "margin-after-collapse": { values: [ "collapse", "separate", "discard" ] }, "page-break-before": { values: [ "left", "right", "auto", "always", "avoid" ] }, "-webkit-hyphens": { values: [ "none", "auto", "manual" ] }, "border-image": { values: [ "repeat", "stretch" ] }, "text-decoration": { values: [ "blink", "line-through", "overline", "underline" ] }, "position": { values: [ "absolute", "fixed", "relative", "static" ] }, "font-family": { values: [ "serif", "sans-serif", "cursive", "fantasy", "monospace", "-webkit-body", "-webkit-pictograph" ] }, "text-overflow-mode": { values: [ "clip", "ellipsis" ] }, "border-bottom-style": { values: [ "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" ] }, "unicode-bidi": { values: [ "normal", "bidi-override", "embed" ] }, "clip-rule": { values: [ "nonzero", "evenodd" ] }, "margin-left": { values: [ "auto" ] }, "margin-top": { values: [ "auto" ] }, "zoom": { values: [ "normal", "document", "reset" ] }, "text-overline-style": { values: [ "none", "dotted", "dashed", "solid", "double", "dot-dash", "dot-dot-dash", "wave" ] }, "max-width": { values: [ "none" ] }, "caption-side": { values: [ "top", "bottom" ] }, "empty-cells": { values: [ "hide", "show" ] }, "pointer-events": { values: [ "none", "all", "auto", "visible", "visiblepainted", "visiblefill", "visiblestroke", "painted", "fill", "stroke" ] }, "letter-spacing": { values: [ "normal" ] }, "background-clip": { values: [ "border-box", "content-box", "padding-box" ] }, "-webkit-font-smoothing": { values: [ "none", "auto", "antialiased", "subpixel-antialiased" ] }, "border": { values: [ "none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double" ] }, "font-size": { values: [ "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "-webkit-xxx-large", "smaller", "larger" ] }, "font-variant": { values: [ "small-caps", "normal" ] }, "vertical-align": { values: [ "baseline", "middle", "sub", "super", "text-top", "text-bottom", "top", "bottom", "-webkit-baseline-middle" ] }, "marquee-style": { values: [ "none", "scroll", "slide", "alternate" ] }, "white-space": { values: [ "normal", "nowrap", "pre", "pre-line", "pre-wrap" ] }, "text-underline-width": { values: [ "normal", "medium", "auto", "thick", "thin" ] }, "box-lines": { values: [ "single", "multiple" ] }, "page-break-after": { values: [ "left", "right", "auto", "always", "avoid" ] }, "clip-path": { values: [ "none" ] }, "margin": { values: [ "auto" ] }, "marquee-repetition": { values: [ "infinite" ] }, "margin-right": { values: [ "auto" ] }, "word-break": { values: [ "normal", "break-all", "break-word" ] }, "word-spacing": { values: [ "normal" ] }, "-webkit-text-emphasis-style": { values: [ "circle", "filled", "open", "dot", "double-circle", "triangle", "sesame" ] }, "-webkit-transform": { values: [ "scale", "scaleX", "scaleY", "scale3d", "rotate", "rotateX", "rotateY", "rotateZ", "rotate3d", "skew", "skewX", "skewY", "translate", "translateX", "translateY", "translateZ", "translate3d", "matrix", "matrix3d", "perspective" ] }, "image-resolution": { values: [ "from-image", "snap" ] }, "box-sizing": { values: [ "content-box", "padding-box", "border-box" ] }, "clip": { values: [ "auto" ] }, "resize": { values: [ "none", "both", "horizontal", "vertical" ] }, "-webkit-align-content": { values: [ "flex-start", "flex-end", "center", "space-between", "space-around", "stretch" ] }, "-webkit-align-items": { values: [ "flex-start", "flex-end", "center", "baseline", "stretch" ] }, "-webkit-align-self": { values: [ "auto", "flex-start", "flex-end", "center", "baseline", "stretch" ] }, "-webkit-flex-direction": { values: [ "row", "row-reverse", "column", "column-reverse" ] }, "-webkit-justify-content": { values: [ "flex-start", "flex-end", "center", "space-between", "space-around" ] }, "-webkit-flex-wrap": { values: [ "nowrap", "wrap", "wrap-reverse" ] }, "-webkit-animation-timing-function": { values: [ "ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps", "cubic-bezier" ] }, "-webkit-animation-direction": { values: [ "normal", "reverse", "alternate", "alternate-reverse" ] }, "-webkit-animation-play-state": { values: [ "running", "paused" ] }, "-webkit-animation-fill-mode": { values: [ "none", "forwards", "backwards", "both" ] }, "-webkit-backface-visibility": { values: [ "visible", "hidden" ] }, "-webkit-box-decoration-break": { values: [ "slice", "clone" ] }, "-webkit-column-break-after": { values: [ "auto", "always", "avoid", "left", "right", "page", "column", "avoid-page", "avoid-column" ] }, "-webkit-column-break-before": { values: [ "auto", "always", "avoid", "left", "right", "page", "column", "avoid-page", "avoid-column" ] }, "-webkit-column-break-inside": { values: [ "auto", "avoid", "avoid-page", "avoid-column" ] }, "-webkit-column-span": { values: [ "none", "all" ] }, "-webkit-column-count": { values: [ "auto" ] }, "-webkit-column-gap": { values: [ "normal" ] }, "-webkit-line-break": { values: [ "auto", "loose", "normal", "strict" ] }, "-webkit-perspective": { values: [ "none" ] }, "-webkit-perspective-origin": { values: [ "left", "center", "right", "top", "bottom" ] }, "-webkit-text-align-last": { values: [ "auto", "start", "end", "left", "right", "center", "justify" ] }, "-webkit-text-decoration-line": { values: [ "none", "underline", "overline", "line-through", "blink" ] }, "-webkit-text-decoration-style": { values: [ "solid", "double", "dotted", "dashed", "wavy" ] }, "-webkit-text-decoration-skip": { values: [ "none", "objects", "spaces", "ink", "edges", "box-decoration" ] }, "-webkit-transform-origin": { values: [ "left", "center", "right", "top", "bottom" ] }, "-webkit-transform-style": { values: [ "flat", "preserve-3d" ] }, "-webkit-transition-timing-function": { values: [ "ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps", "cubic-bezier" ] }, "-webkit-flex": { m: "flexbox" }, "-webkit-flex-basis": { m: "flexbox" }, "-webkit-flex-flow": { m: "flexbox" }, "-webkit-flex-grow": { m: "flexbox" }, "-webkit-flex-shrink": { m: "flexbox" }, "-webkit-animation": { m: "animations" }, "-webkit-animation-delay": { m: "animations" }, "-webkit-animation-duration": { m: "animations" }, "-webkit-animation-iteration-count": { m: "animations" }, "-webkit-animation-name": { m: "animations" }, "-webkit-column-rule": { m: "multicol" }, "-webkit-column-rule-color": { m: "multicol", a: "crc" }, "-webkit-column-rule-style": { m: "multicol", a: "crs" }, "-webkit-column-rule-width": { m: "multicol", a: "crw" }, "-webkit-column-width": { m: "multicol", a: "cw" }, "-webkit-columns": { m: "multicol" }, "-webkit-grid-columns": { m: "grid" }, "-webkit-grid-rows": { m: "grid" }, "-webkit-order": { m: "flexbox" }, "-webkit-text-decoration-color": { m: "text-decor" }, "-webkit-text-emphasis-color": { m: "text-decor" }, "-webkit-transition": { m: "transitions" }, "-webkit-transition-delay": { m: "transitions" }, "-webkit-transition-duration": { m: "transitions" }, "-webkit-transition-property": { m: "transitions" }, "background": { m: "background" }, "background-attachment": { m: "background" }, "background-color": { m: "background" }, "background-image": { m: "background" }, "background-position": { m: "background" }, "background-position-x": { m: "background" }, "background-position-y": { m: "background" }, "background-repeat-x": { m: "background" }, "background-repeat-y": { m: "background" }, "border-top": { m: "background" }, "border-right": { m: "background" }, "border-bottom": { m: "background" }, "border-left": { m: "background" }, "border-radius": { m: "background" }, "bottom": { m: "visuren" }, "box-shadow": { m: "background" }, "color": { m: "color", a: "foreground" }, "counter-increment": { m: "generate" }, "counter-reset": { m: "generate" }, "height": { m: "box" }, "image-orientation": { m: "images" }, "left": { m: "visuren" }, "list-style": { m: "lists" }, "min-height": { m: "box" }, "min-width": { m: "box" }, "opacity": { m: "color", a: "transparency" }, "orphans": { m: "page" }, "outline-offset": { m: "ui" }, "padding": { m: "box", a: "padding1" }, "padding-bottom": { m: "box" }, "padding-left": { m: "box" }, "padding-right": { m: "box" }, "padding-top": { m: "box" }, "page": { m: "page" }, "quotes": { m: "generate" }, "right": { m: "visuren" }, "tab-size": { m: "text" }, "text-indent": { m: "text" }, "text-shadow": { m: "text-decor" }, "top": { m: "visuren" }, "unicode-range": { m: "fonts", a: "descdef-unicode-range" }, "widows": { m: "page" }, "width": { m: "box" }, "z-index": { m: "visuren" } } WebInspector.CSSMetadata.keywordsForProperty = function(propertyName) { var acceptedKeywords = ["initial"]; var descriptor = WebInspector.CSSMetadata.descriptor(propertyName); if (descriptor && descriptor.values) acceptedKeywords.push.apply(acceptedKeywords, descriptor.values); if (propertyName in WebInspector.CSSMetadata._colorAwareProperties) acceptedKeywords.push.apply(acceptedKeywords, WebInspector.CSSMetadata._colors); if (propertyName in WebInspector.CSSMetadata.InheritedProperties) acceptedKeywords.push("inherit"); return new WebInspector.CSSMetadata(acceptedKeywords); } WebInspector.CSSMetadata.descriptor = function(propertyName) { if (!propertyName) return null; var unprefixedName = propertyName.replace(/^-webkit-/, ""); var entry = WebInspector.CSSMetadata._propertyDataMap[propertyName]; if (!entry && unprefixedName !== propertyName) entry = WebInspector.CSSMetadata._propertyDataMap[unprefixedName]; return entry || null; } WebInspector.CSSMetadata.requestCSSShorthandData = function() { function propertyNamesCallback(error, properties) { if (!error) WebInspector.CSSMetadata.cssPropertiesMetainfo = new WebInspector.CSSMetadata(properties); } CSSAgent.getSupportedCSSProperties(propertyNamesCallback); } WebInspector.CSSMetadata.cssPropertiesMetainfoKeySet = function() { if (!WebInspector.CSSMetadata._cssPropertiesMetainfoKeySet) WebInspector.CSSMetadata._cssPropertiesMetainfoKeySet = WebInspector.CSSMetadata.cssPropertiesMetainfo.keySet(); return WebInspector.CSSMetadata._cssPropertiesMetainfoKeySet; } WebInspector.CSSMetadata.Weight = { "-webkit-animation": 1, "-webkit-animation-duration": 1, "-webkit-animation-iteration-count": 1, "-webkit-animation-name": 1, "-webkit-animation-timing-function": 1, "-webkit-appearance": 1, "-webkit-background-clip": 2, "-webkit-border-horizontal-spacing": 1, "-webkit-border-vertical-spacing": 1, "-webkit-box-shadow": 24, "-webkit-font-smoothing": 2, "-webkit-transform": 1, "-webkit-transition": 8, "-webkit-transition-delay": 7, "-webkit-transition-duration": 7, "-webkit-transition-property": 7, "-webkit-transition-timing-function": 6, "-webkit-user-select": 1, "background": 222, "background-attachment": 144, "background-clip": 143, "background-color": 222, "background-image": 201, "background-origin": 142, "background-size": 25, "border": 121, "border-bottom": 121, "border-bottom-color": 121, "border-bottom-left-radius": 50, "border-bottom-right-radius": 50, "border-bottom-style": 114, "border-bottom-width": 120, "border-collapse": 3, "border-left": 95, "border-left-color": 95, "border-left-style": 89, "border-left-width": 94, "border-radius": 50, "border-right": 93, "border-right-color": 93, "border-right-style": 88, "border-right-width": 93, "border-top": 111, "border-top-color": 111, "border-top-left-radius": 49, "border-top-right-radius": 49, "border-top-style": 104, "border-top-width": 109, "bottom": 16, "box-shadow": 25, "box-sizing": 2, "clear": 23, "color": 237, "cursor": 34, "direction": 4, "display": 210, "fill": 2, "filter": 1, "float": 105, "font": 174, "font-family": 25, "font-size": 174, "font-style": 9, "font-weight": 89, "height": 161, "left": 54, "letter-spacing": 3, "line-height": 75, "list-style": 17, "list-style-image": 8, "list-style-position": 8, "list-style-type": 17, "margin": 241, "margin-bottom": 226, "margin-left": 225, "margin-right": 213, "margin-top": 241, "max-height": 5, "max-width": 11, "min-height": 9, "min-width": 6, "opacity": 24, "outline": 10, "outline-color": 10, "outline-style": 10, "outline-width": 10, "overflow": 57, "overflow-x": 56, "overflow-y": 57, "padding": 216, "padding-bottom": 208, "padding-left": 216, "padding-right": 206, "padding-top": 216, "position": 136, "resize": 1, "right": 29, "stroke": 1, "stroke-width": 1, "table-layout": 1, "text-align": 66, "text-decoration": 53, "text-indent": 9, "text-overflow": 8, "text-shadow": 19, "text-transform": 5, "top": 71, "unicode-bidi": 1, "vertical-align": 37, "visibility": 11, "white-space": 24, "width": 255, "word-wrap": 6, "z-index": 32, "zoom": 10 }; WebInspector.CSSMetadata.prototype = { startsWith: function(prefix) { var firstIndex = this._firstIndexOfPrefix(prefix); if (firstIndex === -1) return []; var results = []; while (firstIndex < this._values.length && this._values[firstIndex].startsWith(prefix)) results.push(this._values[firstIndex++]); return results; }, mostUsedOf: function(properties) { var maxWeight = 0; var index = 0; for (var i = 0; i < properties.length; i++) { var weight = WebInspector.CSSMetadata.Weight[properties[i]]; if (weight > maxWeight) { maxWeight = weight; index = i; } } return index; }, _firstIndexOfPrefix: function(prefix) { if (!this._values.length) return -1; if (!prefix) return 0; var maxIndex = this._values.length - 1; var minIndex = 0; var foundIndex; do { var middleIndex = (maxIndex + minIndex) >> 1; if (this._values[middleIndex].startsWith(prefix)) { foundIndex = middleIndex; break; } if (this._values[middleIndex] < prefix) minIndex = middleIndex + 1; else maxIndex = middleIndex - 1; } while (minIndex <= maxIndex); if (foundIndex === undefined) return -1; while (foundIndex && this._values[foundIndex - 1].startsWith(prefix)) foundIndex--; return foundIndex; }, keySet: function() { if (!this._keySet) this._keySet = this._values.keySet(); return this._keySet; }, next: function(str, prefix) { return this._closest(str, prefix, 1); }, previous: function(str, prefix) { return this._closest(str, prefix, -1); }, _closest: function(str, prefix, shift) { if (!str) return ""; var index = this._values.indexOf(str); if (index === -1) return ""; if (!prefix) { index = (index + this._values.length + shift) % this._values.length; return this._values[index]; } var propertiesWithPrefix = this.startsWith(prefix); var j = propertiesWithPrefix.indexOf(str); j = (j + propertiesWithPrefix.length + shift) % propertiesWithPrefix.length; return propertiesWithPrefix[j]; }, longhands: function(shorthand) { return this._longhands[shorthand]; }, shorthands: function(longhand) { return this._shorthands[longhand]; } } WebInspector.PanelEnablerView = function(identifier, headingText, disclaimerText, buttonTitle) { WebInspector.View.call(this); this.registerRequiredCSS("panelEnablerView.css"); this.element.addStyleClass("panel-enabler-view"); this.element.addStyleClass(identifier); this.contentElement = document.createElement("div"); this.contentElement.className = "panel-enabler-view-content"; this.element.appendChild(this.contentElement); this.imageElement = document.createElement("img"); this.contentElement.appendChild(this.imageElement); this.choicesForm = document.createElement("form"); this.contentElement.appendChild(this.choicesForm); this.headerElement = document.createElement("h1"); this.headerElement.textContent = headingText; this.choicesForm.appendChild(this.headerElement); var self = this; function enableOption(text, checked) { var label = document.createElement("label"); var option = document.createElement("input"); option.type = "radio"; option.name = "enable-option"; if (checked) option.checked = true; label.appendChild(option); label.appendChild(document.createTextNode(text)); self.choicesForm.appendChild(label); return option; }; this.enabledForSession = enableOption(WebInspector.UIString("Only enable for this session"), true); this.enabledAlways = enableOption(WebInspector.UIString("Always enable"), false); this.disclaimerElement = document.createElement("div"); this.disclaimerElement.className = "panel-enabler-disclaimer"; this.disclaimerElement.textContent = disclaimerText; this.choicesForm.appendChild(this.disclaimerElement); this.enableButton = document.createElement("button"); this.enableButton.setAttribute("type", "button"); this.enableButton.textContent = buttonTitle; this.enableButton.addEventListener("click", this._enableButtonCicked.bind(this), false); this.choicesForm.appendChild(this.enableButton); } WebInspector.PanelEnablerView.prototype = { _enableButtonCicked: function() { this.dispatchEventToListeners("enable clicked"); }, onResize: function() { this.imageElement.removeStyleClass("hidden"); if (this.element.offsetWidth < (this.choicesForm.offsetWidth + this.imageElement.offsetWidth)) this.imageElement.addStyleClass("hidden"); }, get alwaysEnabled() { return this.enabledAlways.checked; }, __proto__: WebInspector.View.prototype } WebInspector.StatusBarItem = function(element) { this.element = element; this._enabled = true; } WebInspector.StatusBarItem.prototype = { setEnabled: function(value) { if (this._enabled === value) return; this._enabled = value; this._applyEnabledState(); }, _applyEnabledState: function() { this.element.disabled = !this._enabled; }, __proto__: WebInspector.Object.prototype } WebInspector.StatusBarButton = function(title, className, states) { WebInspector.StatusBarItem.call(this, document.createElement("button")); this.element.className = className + " status-bar-item"; this.element.addEventListener("click", this._clicked.bind(this), false); this.glyph = document.createElement("div"); this.glyph.className = "glyph"; this.element.appendChild(this.glyph); this.glyphShadow = document.createElement("div"); this.glyphShadow.className = "glyph shadow"; this.element.appendChild(this.glyphShadow); this.states = states; if (!states) this.states = 2; if (states == 2) this._state = false; else this._state = 0; this.title = title; this.className = className; this._visible = true; } WebInspector.StatusBarButton.prototype = { _clicked: function() { this.dispatchEventToListeners("click"); if (this._showOptionsTimer) clearTimeout(this._showOptionsTimer); }, enabled: function() { return this._enabled; }, get title() { return this._title; }, set title(x) { if (this._title === x) return; this._title = x; this.element.title = x; }, get state() { return this._state; }, set state(x) { if (this._state === x) return; if (this.states === 2) { if (x) this.element.addStyleClass("toggled-on"); else this.element.removeStyleClass("toggled-on"); } else { if (x !== 0) { this.element.removeStyleClass("toggled-" + this._state); this.element.addStyleClass("toggled-" + x); } else this.element.removeStyleClass("toggled-" + this._state); } this._state = x; }, get toggled() { if (this.states !== 2) throw("Only used toggled when there are 2 states, otherwise, use state"); return this.state; }, set toggled(x) { if (this.states !== 2) throw("Only used toggled when there are 2 states, otherwise, use state"); this.state = x; }, get visible() { return this._visible; }, set visible(x) { if (this._visible === x) return; if (x) this.element.removeStyleClass("hidden"); else this.element.addStyleClass("hidden"); this._visible = x; }, makeLongClickEnabled: function(buttonsProvider) { this.longClickGlyph = document.createElement("div"); this.longClickGlyph.className = "fill long-click-glyph"; this.element.appendChild(this.longClickGlyph); this.longClickGlyphShadow = document.createElement("div"); this.longClickGlyphShadow.className = "fill long-click-glyph shadow"; this.element.appendChild(this.longClickGlyphShadow); this.element.addEventListener("mousedown", mouseDown.bind(this), false); this.element.addEventListener("mouseout", mouseUp.bind(this), false); this.element.addEventListener("mouseup", mouseUp.bind(this), false); function mouseDown(e) { if (e.which !== 1) return; this._showOptionsTimer = setTimeout(this._showOptions.bind(this, buttonsProvider), 200); } function mouseUp(e) { if (e.which !== 1) return; if (this._showOptionsTimer) clearTimeout(this._showOptionsTimer); } }, _showOptions: function(buttonsProvider) { var buttons = buttonsProvider(); var mainButtonClone = new WebInspector.StatusBarButton(this.title, this.className, this.states); mainButtonClone.addEventListener("click", this._clicked, this); mainButtonClone.state = this.state; buttons.push(mainButtonClone); var mouseUpListener = mouseUp.bind(this); document.documentElement.addEventListener("mouseup", mouseUpListener, false); var optionsGlassPane = new WebInspector.GlassPane(); var optionsBarElement = optionsGlassPane.element.createChild("div", "alternate-status-bar-buttons-bar"); const buttonHeight = 24; optionsBarElement.style.height = (buttonHeight * buttons.length) + "px"; optionsBarElement.style.left = (this.element.offsetLeft + 1) + "px"; var boundMouseOver = mouseOver.bind(this); var boundMouseOut = mouseOut.bind(this); for (var i = 0; i < buttons.length; ++i) { buttons[i].element.addEventListener("mousemove", boundMouseOver, false); buttons[i].element.addEventListener("mouseout", boundMouseOut, false); optionsBarElement.appendChild(buttons[i].element); } buttons[buttons.length - 1].element.addStyleClass("emulate-active"); function mouseOver(e) { if (e.which !== 1) return; var buttonElement = e.target.enclosingNodeOrSelfWithClass("status-bar-item"); buttonElement.addStyleClass("emulate-active"); } function mouseOut(e) { if (e.which !== 1) return; var buttonElement = e.target.enclosingNodeOrSelfWithClass("status-bar-item"); buttonElement.removeStyleClass("emulate-active"); } function mouseUp(e) { if (e.which !== 1) return; optionsGlassPane.dispose(); document.documentElement.removeEventListener("mouseup", mouseUpListener, false); for (var i = 0; i < buttons.length; ++i) { if (buttons[i].element.hasStyleClass("emulate-active")) buttons[i]._clicked(); } } }, __proto__: WebInspector.StatusBarItem.prototype } WebInspector.StatusBarComboBox = function(changeHandler, className) { WebInspector.StatusBarItem.call(this, document.createElement("span")); this.element.className = "status-bar-select-container"; this._selectElement = this.element.createChild("select", "status-bar-item"); if (changeHandler) this._selectElement.addEventListener("change", changeHandler, false); if (className) this._selectElement.addStyleClass(className); } WebInspector.StatusBarComboBox.prototype = { addOption: function(option) { this._selectElement.appendChild(option); }, _applyEnabledState: function() { this._selectElement.disabled = !this._enabled; }, removeOption: function(option) { this._selectElement.removeChild(option); }, removeOptions: function() { this._selectElement.removeChildren(); }, selectedOption: function() { if (this._selectElement.selectedIndex >= 0) return this._selectElement[this._selectElement.selectedIndex]; return null; }, select: function(option) { this._selectElement.selectedIndex = Array.prototype.indexOf.call(this._selectElement, option); }, __proto__: WebInspector.StatusBarItem.prototype } WebInspector.TextEditor = function() { }; WebInspector.TextEditor.Events = { GutterClick: "gutterClick" }; WebInspector.TextEditor.prototype = { set mimeType(mimeType) { }, setReadOnly: function(readOnly) { }, readOnly: function() { }, defaultFocusedElement: function() { }, revealLine: function(lineNumber) { }, addBreakpoint: function(lineNumber, disabled, conditional) { }, removeBreakpoint: function(lineNumber) { }, setExecutionLine: function(lineNumber) { }, clearExecutionLine: function() { }, addDecoration: function(lineNumber, element) { }, removeDecoration: function(lineNumber, element) { }, markAndRevealRange: function(range) { }, highlightLine: function(lineNumber) { }, clearLineHighlight: function() { }, elementsToRestoreScrollPositionsFor: function() { }, inheritScrollPositions: function(textEditor) { }, beginUpdates: function() { }, endUpdates: function() { }, onResize: function() { }, editRange: function(range, text) { }, scrollToLine: function(lineNumber) { }, selection: function(textRange) { }, lastSelection: function() { }, setSelection: function(textRange) { }, setText: function(text) { }, text: function() { }, range: function() { }, line: function(lineNumber) { }, get linesCount() { }, setAttribute: function(line, name, value) { }, getAttribute: function(line, name) { }, removeAttribute: function(line, name) { }, wasShown: function() { }, willHide: function() { } } WebInspector.TextEditorDelegate = function() { } WebInspector.TextEditorDelegate.prototype = { onTextChanged: function(oldRange, newRange) { }, selectionChanged: function(textRange) { }, scrollChanged: function(lineNumber) { }, populateLineGutterContextMenu: function(contextMenu, lineNumber) { }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { }, createLink: function(hrefValue, isExternal) { } } WebInspector.DefaultTextEditor = function(url, delegate) { WebInspector.View.call(this); this._delegate = delegate; this._url = url; this.registerRequiredCSS("textEditor.css"); this.element.className = "text-editor monospace"; this.element.addEventListener("mouseup", preventDefaultOnMouseUp.bind(this), false); function preventDefaultOnMouseUp(event) { if (event.button === 1) event.consume(true); } this._textModel = new WebInspector.TextEditorModel(); this._textModel.addEventListener(WebInspector.TextEditorModel.Events.TextChanged, this._textChanged, this); var syncScrollListener = this._syncScroll.bind(this); var syncDecorationsForLineListener = this._syncDecorationsForLine.bind(this); var syncLineHeightListener = this._syncLineHeight.bind(this); this._mainPanel = new WebInspector.TextEditorMainPanel(this._delegate, this._textModel, url, syncScrollListener, syncDecorationsForLineListener); this._gutterPanel = new WebInspector.TextEditorGutterPanel(this._textModel, syncDecorationsForLineListener, syncLineHeightListener); this._mainPanel.element.addEventListener("scroll", this._handleScrollChanged.bind(this), false); this._mainPanel._container.addEventListener("focus", this._handleFocused.bind(this), false); this._gutterPanel.element.addEventListener("mousedown", this._onMouseDown.bind(this), true); this._mainPanel.element.addEventListener("mouseup", consumeMouseUp.bind(this), false); function consumeMouseUp(event) { if (event.button === 1) event.consume(false); } this.element.appendChild(this._mainPanel.element); this.element.appendChild(this._gutterPanel.element); function forwardWheelEvent(event) { var clone = document.createEvent("WheelEvent"); clone.initWebKitWheelEvent(event.wheelDeltaX, event.wheelDeltaY, event.view, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey); this._mainPanel.element.dispatchEvent(clone); } this._gutterPanel.element.addEventListener("mousewheel", forwardWheelEvent.bind(this), false); this.element.addEventListener("keydown", this._handleKeyDown.bind(this), false); this.element.addEventListener("cut", this._handleCut.bind(this), false); this.element.addEventListener("textInput", this._handleTextInput.bind(this), false); this.element.addEventListener("contextmenu", this._contextMenu.bind(this), true); this._registerShortcuts(); } WebInspector.DefaultTextEditor.EditInfo = function(range, text) { this.range = range; this.text = text; } WebInspector.DefaultTextEditor.prototype = { set mimeType(mimeType) { this._mainPanel.mimeType = mimeType; }, setReadOnly: function(readOnly) { if (this._mainPanel.readOnly() === readOnly) return; this._mainPanel.setReadOnly(readOnly, this.isShowing()); WebInspector.markBeingEdited(this.element, !readOnly); }, readOnly: function() { return this._mainPanel.readOnly(); }, defaultFocusedElement: function() { return this._mainPanel.defaultFocusedElement(); }, revealLine: function(lineNumber) { this._mainPanel.revealLine(lineNumber); }, _onMouseDown: function(event) { var target = event.target.enclosingNodeOrSelfWithClass("webkit-line-number"); if (!target) return; this.dispatchEventToListeners(WebInspector.TextEditor.Events.GutterClick, { lineNumber: target.lineNumber, event: event }); }, addBreakpoint: function(lineNumber, disabled, conditional) { this.beginUpdates(); this._gutterPanel.addDecoration(lineNumber, "webkit-breakpoint"); if (disabled) this._gutterPanel.addDecoration(lineNumber, "webkit-breakpoint-disabled"); else this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-disabled"); if (conditional) this._gutterPanel.addDecoration(lineNumber, "webkit-breakpoint-conditional"); else this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-conditional"); this.endUpdates(); }, removeBreakpoint: function(lineNumber) { this.beginUpdates(); this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint"); this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-disabled"); this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-conditional"); this.endUpdates(); }, setExecutionLine: function(lineNumber) { this._executionLineNumber = lineNumber; this._mainPanel.addDecoration(lineNumber, "webkit-execution-line"); this._gutterPanel.addDecoration(lineNumber, "webkit-execution-line"); }, clearExecutionLine: function() { if (typeof this._executionLineNumber === "number") { this._mainPanel.removeDecoration(this._executionLineNumber, "webkit-execution-line"); this._gutterPanel.removeDecoration(this._executionLineNumber, "webkit-execution-line"); } delete this._executionLineNumber; }, addDecoration: function(lineNumber, element) { this._mainPanel.addDecoration(lineNumber, element); this._gutterPanel.addDecoration(lineNumber, element); this._syncDecorationsForLine(lineNumber); }, removeDecoration: function(lineNumber, element) { this._mainPanel.removeDecoration(lineNumber, element); this._gutterPanel.removeDecoration(lineNumber, element); this._syncDecorationsForLine(lineNumber); }, markAndRevealRange: function(range) { if (range) this.setSelection(range); this._mainPanel.markAndRevealRange(range); }, highlightLine: function(lineNumber) { if (typeof lineNumber !== "number" || lineNumber < 0) return; lineNumber = Math.min(lineNumber, this._textModel.linesCount - 1); this._mainPanel.highlightLine(lineNumber); }, clearLineHighlight: function() { this._mainPanel.clearLineHighlight(); }, _freeCachedElements: function() { this._mainPanel._freeCachedElements(); this._gutterPanel._freeCachedElements(); }, elementsToRestoreScrollPositionsFor: function() { return [this._mainPanel.element]; }, inheritScrollPositions: function(textEditor) { this._mainPanel.element._scrollTop = textEditor._mainPanel.element.scrollTop; this._mainPanel.element._scrollLeft = textEditor._mainPanel.element.scrollLeft; }, beginUpdates: function() { this._mainPanel.beginUpdates(); this._gutterPanel.beginUpdates(); }, endUpdates: function() { this._mainPanel.endUpdates(); this._gutterPanel.endUpdates(); this._updatePanelOffsets(); }, onResize: function() { this._mainPanel.resize(); this._gutterPanel.resize(); this._updatePanelOffsets(); }, _textChanged: function(event) { this._mainPanel.textChanged(event.data.oldRange, event.data.newRange); this._gutterPanel.textChanged(event.data.oldRange, event.data.newRange); this._updatePanelOffsets(); if (event.data.editRange) this._delegate.onTextChanged(event.data.oldRange, event.data.newRange); }, editRange: function(range, text) { return this._textModel.editRange(range, text); }, _updatePanelOffsets: function() { var lineNumbersWidth = this._gutterPanel.element.offsetWidth; if (lineNumbersWidth) this._mainPanel.element.style.setProperty("left", (lineNumbersWidth + 2) + "px"); else this._mainPanel.element.style.removeProperty("left"); }, _syncScroll: function() { var mainElement = this._mainPanel.element; var gutterElement = this._gutterPanel.element; this._gutterPanel.syncClientHeight(mainElement.clientHeight); gutterElement.scrollTop = mainElement.scrollTop; }, _syncDecorationsForLine: function(lineNumber) { if (lineNumber >= this._textModel.linesCount) return; var mainChunk = this._mainPanel.chunkForLine(lineNumber); if (mainChunk.linesCount === 1 && mainChunk.isDecorated()) { var gutterChunk = this._gutterPanel.makeLineAChunk(lineNumber); var height = mainChunk.height; if (height) gutterChunk.element.style.setProperty("height", height + "px"); else gutterChunk.element.style.removeProperty("height"); } else { var gutterChunk = this._gutterPanel.chunkForLine(lineNumber); if (gutterChunk.linesCount === 1) gutterChunk.element.style.removeProperty("height"); } }, _syncLineHeight: function(gutterRow) { if (this._lineHeightSynced) return; if (gutterRow && gutterRow.offsetHeight) { this.element.style.setProperty("line-height", gutterRow.offsetHeight + "px"); this._lineHeightSynced = true; } }, _registerShortcuts: function() { var keys = WebInspector.KeyboardShortcut.Keys; var modifiers = WebInspector.KeyboardShortcut.Modifiers; this._shortcuts = {}; var handleEnterKey = this._mainPanel.handleEnterKey.bind(this._mainPanel); this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Enter.code, WebInspector.KeyboardShortcut.Modifiers.None)] = handleEnterKey; this._shortcuts[WebInspector.KeyboardShortcut.makeKey("z", modifiers.CtrlOrMeta)] = this._mainPanel.handleUndoRedo.bind(this._mainPanel, false); this._shortcuts[WebInspector.KeyboardShortcut.SelectAll] = this._handleSelectAll.bind(this); var handleRedo = this._mainPanel.handleUndoRedo.bind(this._mainPanel, true); this._shortcuts[WebInspector.KeyboardShortcut.makeKey("z", modifiers.Shift | modifiers.CtrlOrMeta)] = handleRedo; if (!WebInspector.isMac()) this._shortcuts[WebInspector.KeyboardShortcut.makeKey("y", modifiers.CtrlOrMeta)] = handleRedo; var handleTabKey = this._mainPanel.handleTabKeyPress.bind(this._mainPanel, false); var handleShiftTabKey = this._mainPanel.handleTabKeyPress.bind(this._mainPanel, true); this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Tab.code)] = handleTabKey; this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Tab.code, modifiers.Shift)] = handleShiftTabKey; }, _handleSelectAll: function() { this.setSelection(this._textModel.range()); return true; }, _handleTextInput: function(e) { this._mainPanel._textInputData = e.data; }, _handleKeyDown: function(e) { if (e.target.enclosingNodeOrSelfWithClass("webkit-line-decorations")) return; var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent(e); var handler = this._shortcuts[shortcutKey]; if (handler && handler()) { e.consume(true); return; } this._mainPanel._keyDownCode = e.keyCode; }, _handleCut: function(e) { this._mainPanel._keyDownCode = WebInspector.KeyboardShortcut.Keys.Delete.code; }, _contextMenu: function(event) { var anchor = event.target.enclosingNodeOrSelfWithNodeName("a"); if (anchor) return; var contextMenu = new WebInspector.ContextMenu(event); var target = event.target.enclosingNodeOrSelfWithClass("webkit-line-number"); if (target) this._delegate.populateLineGutterContextMenu(contextMenu, target.lineNumber); else { target = this._mainPanel._enclosingLineRowOrSelf(event.target); this._delegate.populateTextAreaContextMenu(contextMenu, target && target.lineNumber); } contextMenu.show(); }, _handleScrollChanged: function(event) { var visibleFrom = this._mainPanel._scrollTop(); var firstVisibleLineNumber = this._mainPanel._findFirstVisibleLineNumber(visibleFrom); this._delegate.scrollChanged(firstVisibleLineNumber); }, scrollToLine: function(lineNumber) { this._mainPanel.scrollToLine(lineNumber); }, selection: function(textRange) { return this._mainPanel._getSelection(); }, lastSelection: function() { return this._mainPanel._lastSelection; }, setSelection: function(textRange) { this._mainPanel._lastSelection = textRange; if (this.element.isAncestor(document.activeElement)) this._mainPanel._restoreSelection(textRange); }, setText: function(text) { this._textModel.setText(text); }, text: function() { return this._textModel.text(); }, range: function() { return this._textModel.range(); }, line: function(lineNumber) { return this._textModel.line(lineNumber); }, get linesCount() { return this._textModel.linesCount; }, setAttribute: function(line, name, value) { this._textModel.setAttribute(line, name, value); }, getAttribute: function(line, name) { return this._textModel.getAttribute(line, name); }, removeAttribute: function(line, name) { this._textModel.removeAttribute(line, name); }, wasShown: function() { if (!this.readOnly()) WebInspector.markBeingEdited(this.element, true); this._boundSelectionChangeListener = this._mainPanel._handleSelectionChange.bind(this._mainPanel); document.addEventListener("selectionchange", this._boundSelectionChangeListener, false); this._mainPanel._wasShown(); }, _handleFocused: function() { if (this._mainPanel._lastSelection) this.setSelection(this._mainPanel._lastSelection); }, willHide: function() { this._mainPanel._willHide(); document.removeEventListener("selectionchange", this._boundSelectionChangeListener, false); delete this._boundSelectionChangeListener; if (!this.readOnly()) WebInspector.markBeingEdited(this.element, false); this._freeCachedElements(); }, highlightRangesWithStyleClass: function(element, resultRanges, styleClass, changes) { this._mainPanel.beginDomUpdates(); WebInspector.highlightRangesWithStyleClass(element, resultRanges, styleClass, changes); this._mainPanel.endDomUpdates(); }, highlightExpression: function(element, skipClasses, skipTokens) { var tokens = [ element ]; var token = element.previousSibling; while (token && (skipClasses[token.className] || skipTokens[token.textContent.trim()])) { tokens.push(token); token = token.previousSibling; } tokens.reverse(); this._mainPanel.beginDomUpdates(); var parentElement = element.parentElement; var nextElement = element.nextSibling; var container = document.createElement("span"); for (var i = 0; i < tokens.length; ++i) container.appendChild(tokens[i]); parentElement.insertBefore(container, nextElement); this._mainPanel.endDomUpdates(); return container; }, hideHighlightedExpression: function(highlightElement) { this._mainPanel.beginDomUpdates(); var parentElement = highlightElement.parentElement; if (parentElement) { var child = highlightElement.firstChild; while (child) { var nextSibling = child.nextSibling; parentElement.insertBefore(child, highlightElement); child = nextSibling; } parentElement.removeChild(highlightElement); } this._mainPanel.endDomUpdates(); }, overrideViewportForTest: function(scrollTop, clientHeight, chunkSize) { this._mainPanel._scrollTopOverrideForTest = scrollTop; this._mainPanel._clientHeightOverrideForTest = clientHeight; this._mainPanel._defaultChunkSize = chunkSize; }, __proto__: WebInspector.View.prototype } WebInspector.TextEditorChunkedPanel = function(textModel) { this._textModel = textModel; this._defaultChunkSize = 50; this._paintCoalescingLevel = 0; this._domUpdateCoalescingLevel = 0; } WebInspector.TextEditorChunkedPanel.prototype = { scrollToLine: function(lineNumber) { if (lineNumber >= this._textModel.linesCount) return; var chunk = this.makeLineAChunk(lineNumber); this.element.scrollTop = chunk.offsetTop; }, revealLine: function(lineNumber) { if (lineNumber >= this._textModel.linesCount) return; var chunk = this.makeLineAChunk(lineNumber); chunk.element.scrollIntoViewIfNeeded(); }, addDecoration: function(lineNumber, decoration) { if (lineNumber >= this._textModel.linesCount) return; var chunk = this.makeLineAChunk(lineNumber); chunk.addDecoration(decoration); }, removeDecoration: function(lineNumber, decoration) { if (lineNumber >= this._textModel.linesCount) return; var chunk = this.chunkForLine(lineNumber); chunk.removeDecoration(decoration); }, _buildChunks: function() { this.beginDomUpdates(); this._container.removeChildren(); this._textChunks = []; for (var i = 0; i < this._textModel.linesCount; i += this._defaultChunkSize) { var chunk = this._createNewChunk(i, i + this._defaultChunkSize); this._textChunks.push(chunk); this._container.appendChild(chunk.element); } this._repaintAll(); this.endDomUpdates(); }, makeLineAChunk: function(lineNumber) { var chunkNumber = this._chunkNumberForLine(lineNumber); var oldChunk = this._textChunks[chunkNumber]; if (!oldChunk) { console.error("No chunk for line number: " + lineNumber); return; } if (oldChunk.linesCount === 1) return oldChunk; return this._splitChunkOnALine(lineNumber, chunkNumber, true); }, _splitChunkOnALine: function(lineNumber, chunkNumber, createSuffixChunk) { this.beginDomUpdates(); var oldChunk = this._textChunks[chunkNumber]; var wasExpanded = oldChunk.expanded(); oldChunk.collapse(); var insertIndex = chunkNumber + 1; if (lineNumber > oldChunk.startLine) { var prefixChunk = this._createNewChunk(oldChunk.startLine, lineNumber); this._textChunks.splice(insertIndex++, 0, prefixChunk); this._container.insertBefore(prefixChunk.element, oldChunk.element); } var endLine = createSuffixChunk ? lineNumber + 1 : oldChunk.startLine + oldChunk.linesCount; var lineChunk = this._createNewChunk(lineNumber, endLine); this._textChunks.splice(insertIndex++, 0, lineChunk); this._container.insertBefore(lineChunk.element, oldChunk.element); if (oldChunk.startLine + oldChunk.linesCount > endLine) { var suffixChunk = this._createNewChunk(endLine, oldChunk.startLine + oldChunk.linesCount); this._textChunks.splice(insertIndex, 0, suffixChunk); this._container.insertBefore(suffixChunk.element, oldChunk.element); } this._textChunks.splice(chunkNumber, 1); this._container.removeChild(oldChunk.element); if (wasExpanded) { if (prefixChunk) prefixChunk.expand(); lineChunk.expand(); if (suffixChunk) suffixChunk.expand(); this._repaintAll(); } this.endDomUpdates(); return lineChunk; }, _scroll: function() { this._scheduleRepaintAll(); if (this._syncScrollListener) this._syncScrollListener(); }, _scheduleRepaintAll: function() { if (this._repaintAllTimer) clearTimeout(this._repaintAllTimer); this._repaintAllTimer = setTimeout(this._repaintAll.bind(this), 50); }, beginUpdates: function() { this._paintCoalescingLevel++; }, endUpdates: function() { this._paintCoalescingLevel--; if (!this._paintCoalescingLevel) this._repaintAll(); }, beginDomUpdates: function() { this._domUpdateCoalescingLevel++; }, endDomUpdates: function() { this._domUpdateCoalescingLevel--; }, _chunkNumberForLine: function(lineNumber) { function compareLineNumbers(value, chunk) { return value < chunk.startLine ? -1 : 1; } var insertBefore = insertionIndexForObjectInListSortedByFunction(lineNumber, this._textChunks, compareLineNumbers); return insertBefore - 1; }, chunkForLine: function(lineNumber) { return this._textChunks[this._chunkNumberForLine(lineNumber)]; }, _findFirstVisibleChunkNumber: function(visibleFrom) { function compareOffsetTops(value, chunk) { return value < chunk.offsetTop ? -1 : 1; } var insertBefore = insertionIndexForObjectInListSortedByFunction(visibleFrom, this._textChunks, compareOffsetTops); return insertBefore - 1; }, _findVisibleChunks: function(visibleFrom, visibleTo) { var from = this._findFirstVisibleChunkNumber(visibleFrom); for (var to = from + 1; to < this._textChunks.length; ++to) { if (this._textChunks[to].offsetTop >= visibleTo) break; } return { start: from, end: to }; }, _findFirstVisibleLineNumber: function(visibleFrom) { var chunk = this._textChunks[this._findFirstVisibleChunkNumber(visibleFrom)]; if (!chunk.expanded()) return chunk.startLine; var lineNumbers = []; for (var i = 0; i < chunk.linesCount; ++i) { lineNumbers.push(chunk.startLine + i); } function compareLineRowOffsetTops(value, lineNumber) { var lineRow = chunk.expandedLineRow(lineNumber); return value < lineRow.offsetTop ? -1 : 1; } var insertBefore = insertionIndexForObjectInListSortedByFunction(visibleFrom, lineNumbers, compareLineRowOffsetTops); return lineNumbers[insertBefore - 1]; }, _repaintAll: function() { delete this._repaintAllTimer; if (this._paintCoalescingLevel) return false; var visibleFrom = this._scrollTop(); var visibleTo = visibleFrom + this._clientHeight(); if (visibleTo) { var result = this._findVisibleChunks(visibleFrom, visibleTo); this._expandChunks(result.start, result.end); } return true; }, _scrollTop: function() { return typeof this._scrollTopOverrideForTest === "number" ? this._scrollTopOverrideForTest : this.element.scrollTop; }, _clientHeight: function() { return typeof this._clientHeightOverrideForTest === "number" ? this._clientHeightOverrideForTest : this.element.clientHeight; }, _expandChunks: function(fromIndex, toIndex) { for (var i = 0; i < fromIndex; ++i) this._textChunks[i].collapse(); for (var i = toIndex; i < this._textChunks.length; ++i) this._textChunks[i].collapse(); for (var i = fromIndex; i < toIndex; ++i) this._textChunks[i].expand(); }, _totalHeight: function(firstElement, lastElement) { lastElement = (lastElement || firstElement).nextElementSibling; if (lastElement) return lastElement.offsetTop - firstElement.offsetTop; var offsetParent = firstElement.offsetParent; if (offsetParent && offsetParent.scrollHeight > offsetParent.clientHeight) return offsetParent.scrollHeight - firstElement.offsetTop; var total = 0; while (firstElement && firstElement !== lastElement) { total += firstElement.offsetHeight; firstElement = firstElement.nextElementSibling; } return total; }, resize: function() { this._repaintAll(); } } WebInspector.TextEditorGutterPanel = function(textModel, syncDecorationsForLineListener, syncLineHeightListener) { WebInspector.TextEditorChunkedPanel.call(this, textModel); this._syncDecorationsForLineListener = syncDecorationsForLineListener; this._syncLineHeightListener = syncLineHeightListener; this.element = document.createElement("div"); this.element.className = "text-editor-lines"; this._container = document.createElement("div"); this._container.className = "inner-container"; this.element.appendChild(this._container); this.element.addEventListener("scroll", this._scroll.bind(this), false); this._freeCachedElements(); this._buildChunks(); this._decorations = {}; } WebInspector.TextEditorGutterPanel.prototype = { _freeCachedElements: function() { this._cachedRows = []; }, _createNewChunk: function(startLine, endLine) { return new WebInspector.TextEditorGutterChunk(this, startLine, endLine); }, textChanged: function(oldRange, newRange) { this.beginDomUpdates(); var linesDiff = newRange.linesCount - oldRange.linesCount; if (linesDiff) { for (var chunkNumber = this._textChunks.length - 1; chunkNumber >= 0 ; --chunkNumber) { var chunk = this._textChunks[chunkNumber]; if (chunk.startLine + chunk.linesCount <= this._textModel.linesCount) break; chunk.collapse(); this._container.removeChild(chunk.element); } this._textChunks.length = chunkNumber + 1; var totalLines = 0; if (this._textChunks.length) { var lastChunk = this._textChunks[this._textChunks.length - 1]; totalLines = lastChunk.startLine + lastChunk.linesCount; } for (var i = totalLines; i < this._textModel.linesCount; i += this._defaultChunkSize) { var chunk = this._createNewChunk(i, i + this._defaultChunkSize); this._textChunks.push(chunk); this._container.appendChild(chunk.element); } for (var lineNumber in this._decorations) { lineNumber = parseInt(lineNumber, 10); if (lineNumber < oldRange.startLine) continue; if (lineNumber === oldRange.startLine && oldRange.startColumn) continue; var lineDecorationsCopy = this._decorations[lineNumber].slice(); for (var i = 0; i < lineDecorationsCopy.length; ++i) { var decoration = lineDecorationsCopy[i]; this.removeDecoration(lineNumber, decoration); if (lineNumber < oldRange.endLine) continue; this.addDecoration(lineNumber + linesDiff, decoration); } } this._repaintAll(); } else { var chunkNumber = this._chunkNumberForLine(newRange.startLine); var chunk = this._textChunks[chunkNumber]; while (chunk && chunk.startLine <= newRange.endLine) { if (chunk.linesCount === 1) this._syncDecorationsForLineListener(chunk.startLine); chunk = this._textChunks[++chunkNumber]; } } this.endDomUpdates(); }, syncClientHeight: function(clientHeight) { if (this.element.offsetHeight > clientHeight) this._container.style.setProperty("padding-bottom", (this.element.offsetHeight - clientHeight) + "px"); else this._container.style.removeProperty("padding-bottom"); }, addDecoration: function(lineNumber, decoration) { WebInspector.TextEditorChunkedPanel.prototype.addDecoration.call(this, lineNumber, decoration); var decorations = this._decorations[lineNumber]; if (!decorations) { decorations = []; this._decorations[lineNumber] = decorations; } decorations.push(decoration); }, removeDecoration: function(lineNumber, decoration) { WebInspector.TextEditorChunkedPanel.prototype.removeDecoration.call(this, lineNumber, decoration); var decorations = this._decorations[lineNumber]; if (decorations) { decorations.remove(decoration); if (!decorations.length) delete this._decorations[lineNumber]; } }, __proto__: WebInspector.TextEditorChunkedPanel.prototype } WebInspector.TextEditorGutterChunk = function(textEditor, startLine, endLine) { this._textEditor = textEditor; this._textModel = textEditor._textModel; this.startLine = startLine; endLine = Math.min(this._textModel.linesCount, endLine); this.linesCount = endLine - startLine; this._expanded = false; this.element = document.createElement("div"); this.element.lineNumber = startLine; this.element.className = "webkit-line-number"; if (this.linesCount === 1) { var innerSpan = document.createElement("span"); innerSpan.className = "webkit-line-number-inner"; innerSpan.textContent = startLine + 1; var outerSpan = document.createElement("div"); outerSpan.className = "webkit-line-number-outer"; outerSpan.appendChild(innerSpan); this.element.appendChild(outerSpan); } else { var lineNumbers = []; for (var i = startLine; i < endLine; ++i) lineNumbers.push(i + 1); this.element.textContent = lineNumbers.join("\n"); } } WebInspector.TextEditorGutterChunk.prototype = { addDecoration: function(decoration) { this._textEditor.beginDomUpdates(); if (typeof decoration === "string") this.element.addStyleClass(decoration); this._textEditor.endDomUpdates(); }, removeDecoration: function(decoration) { this._textEditor.beginDomUpdates(); if (typeof decoration === "string") this.element.removeStyleClass(decoration); this._textEditor.endDomUpdates(); }, expanded: function() { return this._expanded; }, expand: function() { if (this.linesCount === 1) this._textEditor._syncDecorationsForLineListener(this.startLine); if (this._expanded) return; this._expanded = true; if (this.linesCount === 1) return; this._textEditor.beginDomUpdates(); this._expandedLineRows = []; var parentElement = this.element.parentElement; for (var i = this.startLine; i < this.startLine + this.linesCount; ++i) { var lineRow = this._createRow(i); parentElement.insertBefore(lineRow, this.element); this._expandedLineRows.push(lineRow); } parentElement.removeChild(this.element); this._textEditor._syncLineHeightListener(this._expandedLineRows[0]); this._textEditor.endDomUpdates(); }, collapse: function() { if (this.linesCount === 1) this._textEditor._syncDecorationsForLineListener(this.startLine); if (!this._expanded) return; this._expanded = false; if (this.linesCount === 1) return; this._textEditor.beginDomUpdates(); var elementInserted = false; for (var i = 0; i < this._expandedLineRows.length; ++i) { var lineRow = this._expandedLineRows[i]; var parentElement = lineRow.parentElement; if (parentElement) { if (!elementInserted) { elementInserted = true; parentElement.insertBefore(this.element, lineRow); } parentElement.removeChild(lineRow); } this._textEditor._cachedRows.push(lineRow); } delete this._expandedLineRows; this._textEditor.endDomUpdates(); }, get height() { if (!this._expandedLineRows) return this._textEditor._totalHeight(this.element); return this._textEditor._totalHeight(this._expandedLineRows[0], this._expandedLineRows[this._expandedLineRows.length - 1]); }, get offsetTop() { return (this._expandedLineRows && this._expandedLineRows.length) ? this._expandedLineRows[0].offsetTop : this.element.offsetTop; }, _createRow: function(lineNumber) { var lineRow = this._textEditor._cachedRows.pop() || document.createElement("div"); lineRow.lineNumber = lineNumber; lineRow.className = "webkit-line-number"; lineRow.textContent = lineNumber + 1; return lineRow; } } WebInspector.TextEditorMainPanel = function(delegate, textModel, url, syncScrollListener, syncDecorationsForLineListener) { WebInspector.TextEditorChunkedPanel.call(this, textModel); this._delegate = delegate; this._syncScrollListener = syncScrollListener; this._syncDecorationsForLineListener = syncDecorationsForLineListener; this._url = url; this._highlighter = new WebInspector.TextEditorHighlighter(textModel, this._highlightDataReady.bind(this)); this._readOnly = true; this.element = document.createElement("div"); this.element.className = "text-editor-contents"; this.element.tabIndex = 0; this._container = document.createElement("div"); this._container.className = "inner-container"; this._container.tabIndex = 0; this.element.appendChild(this._container); this.element.addEventListener("scroll", this._scroll.bind(this), false); this.element.addEventListener("focus", this._handleElementFocus.bind(this), false); this._freeCachedElements(); this._buildChunks(); } WebInspector.TextEditorMainPanel.prototype = { _wasShown: function() { this._isShowing = true; this._attachMutationObserver(); }, _willHide: function() { this._detachMutationObserver(); this._isShowing = false; }, _repaintAll: function() { if (!WebInspector.TextEditorChunkedPanel.prototype._repaintAll.call(this)) return false; var visibleFrom = this._scrollTop(); var visibleTo = visibleFrom + this._clientHeight(); if (visibleTo) { var result = this._findVisibleChunks(visibleFrom, visibleTo); for(var i = result.start; i < result.end; i++) { var chunk = this._textChunks[i]; this._paintLines(chunk.startLine, chunk.startLine + chunk.linesCount, true); } } return true; }, _attachMutationObserver: function() { if (!this._isShowing) return; if (this._mutationObserver) this._mutationObserver.disconnect(); this._mutationObserver = new NonLeakingMutationObserver(this._handleMutations.bind(this)); this._mutationObserver.observe(this._container, { subtree: true, childList: true, characterData: true }); }, _detachMutationObserver: function() { if (!this._isShowing) return; if (this._mutationObserver) { this._mutationObserver.disconnect(); delete this._mutationObserver; } }, set mimeType(mimeType) { this._highlighter.mimeType = mimeType; }, setReadOnly: function(readOnly, requestFocus) { if (this._readOnly === readOnly) return; this.beginDomUpdates(); this._readOnly = readOnly; if (this._readOnly) this._container.removeStyleClass("text-editor-editable"); else { this._container.addStyleClass("text-editor-editable"); if (requestFocus) this._updateSelectionOnStartEditing(); } this.endDomUpdates(); }, readOnly: function() { return this._readOnly; }, _handleElementFocus: function() { if (!this._readOnly) this._container.focus(); }, defaultFocusedElement: function() { if (this._readOnly) return this.element; return this._container; }, _updateSelectionOnStartEditing: function() { this._container.focus(); var selection = window.getSelection(); if (selection.rangeCount) { var commonAncestorContainer = selection.getRangeAt(0).commonAncestorContainer; if (this._container.isSelfOrAncestor(commonAncestorContainer)) return; } selection.removeAllRanges(); var range = document.createRange(); range.setStart(this._container, 0); range.setEnd(this._container, 0); selection.addRange(range); }, markAndRevealRange: function(range) { if (this._rangeToMark) { var markedLine = this._rangeToMark.startLine; delete this._rangeToMark; this.beginDomUpdates(); var chunk = this.chunkForLine(markedLine); var wasExpanded = chunk.expanded(); chunk.collapse(); chunk.updateCollapsedLineRow(); if (wasExpanded) chunk.expand(); this.endDomUpdates(); } if (range) { this._rangeToMark = range; this.revealLine(range.startLine); var chunk = this.makeLineAChunk(range.startLine); this._paintLine(chunk.element); if (this._markedRangeElement) this._markedRangeElement.scrollIntoViewIfNeeded(); } delete this._markedRangeElement; }, highlightLine: function(lineNumber) { this.clearLineHighlight(); this._highlightedLine = lineNumber; this.revealLine(lineNumber); if (!this._readOnly) this._restoreSelection(WebInspector.TextRange.createFromLocation(lineNumber, 0), false); this.addDecoration(lineNumber, "webkit-highlighted-line"); }, clearLineHighlight: function() { if (typeof this._highlightedLine === "number") { this.removeDecoration(this._highlightedLine, "webkit-highlighted-line"); delete this._highlightedLine; } }, _freeCachedElements: function() { this._cachedSpans = []; this._cachedTextNodes = []; this._cachedRows = []; }, handleUndoRedo: function(redo) { if (this.readOnly()) return false; this.beginUpdates(); var range = redo ? this._textModel.redo() : this._textModel.undo(); this.endUpdates(); if (range) this._restoreSelection(range, true); return true; }, handleTabKeyPress: function(shiftKey) { if (this.readOnly()) return false; var selection = this._getSelection(); if (!selection) return false; var range = selection.normalize(); this.beginUpdates(); var newRange; var rangeWasEmpty = range.isEmpty(); if (shiftKey) newRange = this._textModel.unindentLines(range); else { if (rangeWasEmpty) newRange = this._textModel.editRange(range, WebInspector.settings.textEditorIndent.get()); else newRange = this._textModel.indentLines(range); } this.endUpdates(); if (rangeWasEmpty) newRange.startColumn = newRange.endColumn; this._restoreSelection(newRange, true); return true; }, handleEnterKey: function() { if (this.readOnly()) return false; var range = this._getSelection(); if (!range) return false; range = range.normalize(); if (range.endColumn === 0) return false; var line = this._textModel.line(range.startLine); var linePrefix = line.substring(0, range.startColumn); var indentMatch = linePrefix.match(/^\s+/); var currentIndent = indentMatch ? indentMatch[0] : ""; var textEditorIndent = WebInspector.settings.textEditorIndent.get(); var indent = WebInspector.TextEditorModel.endsWithBracketRegex.test(linePrefix) ? currentIndent + textEditorIndent : currentIndent; if (!indent) return false; this.beginDomUpdates(); var lineBreak = this._textModel.lineBreak; var newRange; if (range.isEmpty() && line.substr(range.endColumn - 1, 2) === '{}') { newRange = this._textModel.editRange(range, lineBreak + indent + lineBreak + currentIndent); newRange.endLine--; newRange.endColumn += textEditorIndent.length; } else newRange = this._textModel.editRange(range, lineBreak + indent); this.endDomUpdates(); this._restoreSelection(newRange.collapseToEnd(), true); return true; }, _splitChunkOnALine: function(lineNumber, chunkNumber, createSuffixChunk) { var selection = this._getSelection(); var chunk = WebInspector.TextEditorChunkedPanel.prototype._splitChunkOnALine.call(this, lineNumber, chunkNumber, createSuffixChunk); this._restoreSelection(selection); return chunk; }, beginDomUpdates: function() { if (!this._domUpdateCoalescingLevel) this._detachMutationObserver(); WebInspector.TextEditorChunkedPanel.prototype.beginDomUpdates.call(this); }, endDomUpdates: function() { WebInspector.TextEditorChunkedPanel.prototype.endDomUpdates.call(this); if (!this._domUpdateCoalescingLevel) this._attachMutationObserver(); }, _buildChunks: function() { for (var i = 0; i < this._textModel.linesCount; ++i) this._textModel.removeAttribute(i, "highlight"); WebInspector.TextEditorChunkedPanel.prototype._buildChunks.call(this); }, _createNewChunk: function(startLine, endLine) { return new WebInspector.TextEditorMainChunk(this, startLine, endLine); }, _expandChunks: function(fromIndex, toIndex) { var lastChunk = this._textChunks[toIndex - 1]; var lastVisibleLine = lastChunk.startLine + lastChunk.linesCount; var selection = this._getSelection(); this._muteHighlightListener = true; this._highlighter.highlight(lastVisibleLine); delete this._muteHighlightListener; this._restorePaintLinesOperationsCredit(); WebInspector.TextEditorChunkedPanel.prototype._expandChunks.call(this, fromIndex, toIndex); this._adjustPaintLinesOperationsRefreshValue(); this._restoreSelection(selection); }, _highlightDataReady: function(fromLine, toLine) { if (this._muteHighlightListener) return; this._restorePaintLinesOperationsCredit(); this._paintLines(fromLine, toLine, true ); }, _schedulePaintLines: function(startLine, endLine) { if (startLine >= endLine) return; if (!this._scheduledPaintLines) { this._scheduledPaintLines = [ { startLine: startLine, endLine: endLine } ]; this._paintScheduledLinesTimer = setTimeout(this._paintScheduledLines.bind(this), 0); } else { for (var i = 0; i < this._scheduledPaintLines.length; ++i) { var chunk = this._scheduledPaintLines[i]; if (chunk.startLine <= endLine && chunk.endLine >= startLine) { chunk.startLine = Math.min(chunk.startLine, startLine); chunk.endLine = Math.max(chunk.endLine, endLine); return; } if (chunk.startLine > endLine) { this._scheduledPaintLines.splice(i, 0, { startLine: startLine, endLine: endLine }); return; } } this._scheduledPaintLines.push({ startLine: startLine, endLine: endLine }); } }, _paintScheduledLines: function(skipRestoreSelection) { if (this._paintScheduledLinesTimer) clearTimeout(this._paintScheduledLinesTimer); delete this._paintScheduledLinesTimer; if (!this._scheduledPaintLines) return; if (this._repaintAllTimer) { this._paintScheduledLinesTimer = setTimeout(this._paintScheduledLines.bind(this), 50); return; } var scheduledPaintLines = this._scheduledPaintLines; delete this._scheduledPaintLines; this._restorePaintLinesOperationsCredit(); this._paintLineChunks(scheduledPaintLines, !skipRestoreSelection); this._adjustPaintLinesOperationsRefreshValue(); }, _restorePaintLinesOperationsCredit: function() { if (!this._paintLinesOperationsRefreshValue) this._paintLinesOperationsRefreshValue = 250; this._paintLinesOperationsCredit = this._paintLinesOperationsRefreshValue; this._paintLinesOperationsLastRefresh = Date.now(); }, _adjustPaintLinesOperationsRefreshValue: function() { var operationsDone = this._paintLinesOperationsRefreshValue - this._paintLinesOperationsCredit; if (operationsDone <= 0) return; var timePast = Date.now() - this._paintLinesOperationsLastRefresh; if (timePast <= 0) return; var value = Math.floor(operationsDone / timePast * 50); this._paintLinesOperationsRefreshValue = Number.constrain(value, 150, 1500); }, _paintLines: function(fromLine, toLine, restoreSelection) { this._paintLineChunks([ { startLine: fromLine, endLine: toLine } ], restoreSelection); }, _paintLineChunks: function(lineChunks, restoreSelection) { var visibleFrom = this._scrollTop(); var firstVisibleLineNumber = this._findFirstVisibleLineNumber(visibleFrom); var chunk; var selection; var invisibleLineRows = []; for (var i = 0; i < lineChunks.length; ++i) { var lineChunk = lineChunks[i]; if (this._scheduledPaintLines) { this._schedulePaintLines(lineChunk.startLine, lineChunk.endLine); continue; } for (var lineNumber = lineChunk.startLine; lineNumber < lineChunk.endLine; ++lineNumber) { if (!chunk || lineNumber < chunk.startLine || lineNumber >= chunk.startLine + chunk.linesCount) chunk = this.chunkForLine(lineNumber); var lineRow = chunk.expandedLineRow(lineNumber); if (!lineRow) continue; if (lineNumber < firstVisibleLineNumber) { invisibleLineRows.push(lineRow); continue; } if (restoreSelection && !selection) selection = this._getSelection(); this._paintLine(lineRow); if (this._paintLinesOperationsCredit < 0) { this._schedulePaintLines(lineNumber + 1, lineChunk.endLine); break; } } } for (var i = 0; i < invisibleLineRows.length; ++i) { if (restoreSelection && !selection) selection = this._getSelection(); this._paintLine(invisibleLineRows[i]); } if (restoreSelection) this._restoreSelection(selection); }, _paintLine: function(lineRow) { var lineNumber = lineRow.lineNumber; this.beginDomUpdates(); try { if (this._scheduledPaintLines || this._paintLinesOperationsCredit < 0) { this._schedulePaintLines(lineNumber, lineNumber + 1); return; } var highlight = this._textModel.getAttribute(lineNumber, "highlight"); if (!highlight) return; var decorationsElement = lineRow.decorationsElement; if (!decorationsElement) lineRow.removeChildren(); else { while (true) { var child = lineRow.firstChild; if (!child || child === decorationsElement) break; lineRow.removeChild(child); } } var line = this._textModel.line(lineNumber); if (!line) lineRow.insertBefore(document.createElement("br"), decorationsElement); var plainTextStart = -1; for (var j = 0; j < line.length;) { if (j > 1000) { if (plainTextStart === -1) plainTextStart = j; break; } var attribute = highlight[j]; if (!attribute || !attribute.tokenType) { if (plainTextStart === -1) plainTextStart = j; j++; } else { if (plainTextStart !== -1) { this._insertTextNodeBefore(lineRow, decorationsElement, line.substring(plainTextStart, j)); plainTextStart = -1; --this._paintLinesOperationsCredit; } this._insertSpanBefore(lineRow, decorationsElement, line.substring(j, j + attribute.length), attribute.tokenType); j += attribute.length; --this._paintLinesOperationsCredit; } } if (plainTextStart !== -1) { this._insertTextNodeBefore(lineRow, decorationsElement, line.substring(plainTextStart, line.length)); --this._paintLinesOperationsCredit; } } finally { if (this._rangeToMark && this._rangeToMark.startLine === lineNumber) this._markedRangeElement = WebInspector.highlightSearchResult(lineRow, this._rangeToMark.startColumn, this._rangeToMark.endColumn - this._rangeToMark.startColumn); this.endDomUpdates(); } }, _releaseLinesHighlight: function(lineRow) { if (!lineRow) return; if ("spans" in lineRow) { var spans = lineRow.spans; for (var j = 0; j < spans.length; ++j) this._cachedSpans.push(spans[j]); delete lineRow.spans; } if ("textNodes" in lineRow) { var textNodes = lineRow.textNodes; for (var j = 0; j < textNodes.length; ++j) this._cachedTextNodes.push(textNodes[j]); delete lineRow.textNodes; } this._cachedRows.push(lineRow); }, _getSelection: function(lastUndamagedLineRow) { var selection = window.getSelection(); if (!selection.rangeCount) return null; if (!this._container.isAncestor(selection.anchorNode) || !this._container.isAncestor(selection.focusNode)) return null; var start = this._selectionToPosition(selection.anchorNode, selection.anchorOffset, lastUndamagedLineRow); var end = selection.isCollapsed ? start : this._selectionToPosition(selection.focusNode, selection.focusOffset, lastUndamagedLineRow); return new WebInspector.TextRange(start.line, start.column, end.line, end.column); }, _restoreSelection: function(range, scrollIntoView) { if (!range) return; var start = this._positionToSelection(range.startLine, range.startColumn); var end = range.isEmpty() ? start : this._positionToSelection(range.endLine, range.endColumn); window.getSelection().setBaseAndExtent(start.container, start.offset, end.container, end.offset); if (scrollIntoView) { for (var node = end.container; node; node = node.parentElement) { if (node.scrollIntoViewIfNeeded) { node.scrollIntoViewIfNeeded(); break; } } } this._lastSelection = range; }, _selectionToPosition: function(container, offset, lastUndamagedLineRow) { if (container === this._container && offset === 0) return { line: 0, column: 0 }; if (container === this._container && offset === 1) return { line: this._textModel.linesCount - 1, column: this._textModel.lineLength(this._textModel.linesCount - 1) }; var lineNumber; var column = 0; var node; var scopeNode; if (lastUndamagedLineRow === null) { node = this._container.firstChild; scopeNode = this._container; lineNumber = 0; } else { var lineRow = this._enclosingLineRowOrSelf(container); if (!lastUndamagedLineRow || (typeof lineRow.lineNumber === "number" && lineRow.lineNumber <= lastUndamagedLineRow.lineNumber)) { node = lineRow; scopeNode = node; lineNumber = node.lineNumber; } else { node = lastUndamagedLineRow.nextSibling; scopeNode = this._container; lineNumber = lastUndamagedLineRow.lineNumber + 1; } } if (container === node && offset === 0) return { line: lineNumber, column: 0 }; for (; node && node !== container; node = node.traverseNextNode(scopeNode)) { if (node.nodeName.toLowerCase() === "br") { lineNumber++; column = 0; } else if (node.nodeType === Node.TEXT_NODE) { var text = node.textContent; for (var i = 0; i < text.length; ++i) { if (text.charAt(i) === "\n") { lineNumber++; column = 0; } else column++; } } } if (node === container && offset) { var text = node.textContent; var textOffset = (node._chunk && offset === 1) ? text.length : offset; for (var i = 0; i < textOffset; ++i) { if (text.charAt(i) === "\n") { lineNumber++; column = 0; } else column++; } } return { line: lineNumber, column: column }; }, _positionToSelection: function(line, column) { var chunk = this.chunkForLine(line); var lineRow = chunk.linesCount === 1 ? chunk.element : chunk.expandedLineRow(line); if (lineRow) var rangeBoundary = lineRow.rangeBoundaryForOffset(column); else { var offset = column; for (var i = chunk.startLine; i < line && i < this._textModel.linesCount; ++i) offset += this._textModel.lineLength(i) + 1; lineRow = chunk.element; if (lineRow.firstChild) var rangeBoundary = { container: lineRow.firstChild, offset: offset }; else var rangeBoundary = { container: lineRow, offset: 0 }; } return rangeBoundary; }, _enclosingLineRowOrSelf: function(element) { var lineRow = element.enclosingNodeOrSelfWithClass("webkit-line-content"); if (lineRow) return lineRow; for (lineRow = element; lineRow; lineRow = lineRow.parentElement) { if (lineRow.parentElement === this._container) return lineRow; } return null; }, _insertSpanBefore: function(element, oldChild, content, className) { if (className === "html-resource-link" || className === "html-external-link") { element.insertBefore(this._createLink(content, className === "html-external-link"), oldChild); return; } var span = this._cachedSpans.pop() || document.createElement("span"); span.className = "webkit-" + className; if (WebInspector.FALSE) span.addStyleClass("debug-fadeout"); span.textContent = content; element.insertBefore(span, oldChild); if (!("spans" in element)) element.spans = []; element.spans.push(span); }, _insertTextNodeBefore: function(element, oldChild, text) { var textNode = this._cachedTextNodes.pop(); if (textNode) textNode.nodeValue = text; else textNode = document.createTextNode(text); element.insertBefore(textNode, oldChild); if (!("textNodes" in element)) element.textNodes = []; element.textNodes.push(textNode); }, _createLink: function(content, isExternal) { var quote = content.charAt(0); if (content.length > 1 && (quote === "\"" || quote === "'")) content = content.substring(1, content.length - 1); else quote = null; var span = document.createElement("span"); span.className = "webkit-html-attribute-value"; if (quote) span.appendChild(document.createTextNode(quote)); span.appendChild(this._delegate.createLink(content, isExternal)); if (quote) span.appendChild(document.createTextNode(quote)); return span; }, _handleMutations: function(mutations) { if (this._readOnly) { delete this._keyDownCode; return; } var filteredMutations = mutations.slice(); var addedBRs = new Map(); for (var i = 0; i < mutations.length; ++i) { var mutation = mutations[i]; if (mutation.type !== "childList") continue; if (mutation.addedNodes.length === 1 && mutation.addedNodes[0].nodeName === "BR") addedBRs.put(mutation.addedNodes[0], mutation); else if (mutation.removedNodes.length === 1 && mutation.removedNodes[0].nodeName === "BR") { var noopMutation = addedBRs.get(mutation.removedNodes[0]); if (noopMutation) { filteredMutations.remove(mutation); filteredMutations.remove(noopMutation); } } } var dirtyLines; for (var i = 0; i < filteredMutations.length; ++i) { var mutation = filteredMutations[i]; var changedNodes = []; if (mutation.type === "childList" && mutation.addedNodes.length) changedNodes = Array.prototype.slice.call(mutation.addedNodes); else if (mutation.type === "childList" && mutation.removedNodes.length) changedNodes = Array.prototype.slice.call(mutation.removedNodes); changedNodes.push(mutation.target); for (var j = 0; j < changedNodes.length; ++j) { var lines = this._collectDirtyLines(mutation, changedNodes[j]); if (!lines) continue; if (!dirtyLines) { dirtyLines = lines; continue; } dirtyLines.start = Math.min(dirtyLines.start, lines.start); dirtyLines.end = Math.max(dirtyLines.end, lines.end); } } if (dirtyLines) { delete this._rangeToMark; this._applyDomUpdates(dirtyLines); } this._assertDOMMatchesTextModel(); delete this._keyDownCode; }, _collectDirtyLines: function(mutation, target) { var lineRow = this._enclosingLineRowOrSelf(target); if (!lineRow) return null; if (lineRow.decorationsElement && lineRow.decorationsElement.isSelfOrAncestor(target)) { if (this._syncDecorationsForLineListener) this._syncDecorationsForLineListener(lineRow.lineNumber); return null; } if (typeof lineRow.lineNumber !== "number") return null; var startLine = lineRow.lineNumber; var endLine = lineRow._chunk ? lineRow._chunk.endLine - 1 : lineRow.lineNumber; return { start: startLine, end: endLine }; }, _applyDomUpdates: function(dirtyLines) { var lastUndamagedLineNumber = dirtyLines.start - 1; var firstUndamagedLineNumber = dirtyLines.end + 1; var lastUndamagedLineChunk = lastUndamagedLineNumber >= 0 ? this._textChunks[this._chunkNumberForLine(lastUndamagedLineNumber)] : null; var firstUndamagedLineChunk = firstUndamagedLineNumber < this._textModel.linesCount ? this._textChunks[this._chunkNumberForLine(firstUndamagedLineNumber)] : null; var collectLinesFromNode = lastUndamagedLineChunk ? lastUndamagedLineChunk.lineRowContainingLine(lastUndamagedLineNumber) : null; var collectLinesToNode = firstUndamagedLineChunk ? firstUndamagedLineChunk.lineRowContainingLine(firstUndamagedLineNumber) : null; var lines = this._collectLinesFromDOM(collectLinesFromNode, collectLinesToNode); var startLine = dirtyLines.start; var endLine = dirtyLines.end; var editInfo = this._guessEditRangeBasedOnSelection(startLine, endLine, lines); if (!editInfo) { if (WebInspector.debugDefaultTextEditor) console.warn("Falling back to expensive edit"); var range = new WebInspector.TextRange(startLine, 0, endLine, this._textModel.lineLength(endLine)); if (!lines.length) { editInfo = new WebInspector.DefaultTextEditor.EditInfo(this._textModel.growRangeRight(range), ""); } else editInfo = new WebInspector.DefaultTextEditor.EditInfo(range, lines.join("\n")); } var selection = this._getSelection(collectLinesFromNode); if (editInfo.text === "}" && editInfo.range.isEmpty() && selection.isEmpty() && !this._textModel.line(editInfo.range.endLine).trim()) { var offset = this._closingBlockOffset(editInfo.range, selection); if (offset >= 0) { editInfo.range.startColumn = offset; selection.startColumn = offset + 1; selection.endColumn = offset + 1; } } this._textModel.editRange(editInfo.range, editInfo.text); this._paintScheduledLines(true); this._restoreSelection(selection); }, _guessEditRangeBasedOnSelection: function(startLine, endLine, lines) { var textInputData = this._textInputData; delete this._textInputData; var isBackspace = this._keyDownCode === WebInspector.KeyboardShortcut.Keys.Backspace.code; var isDelete = this._keyDownCode === WebInspector.KeyboardShortcut.Keys.Delete.code; if (!textInputData && (isDelete || isBackspace)) textInputData = ""; if (typeof textInputData === "undefined" || !this._lastSelection) return null; textInputData = textInputData || ""; var range = this._lastSelection.normalize(); if (isBackspace && range.isEmpty()) range = this._textModel.growRangeLeft(range); else if (isDelete && range.isEmpty()) range = this._textModel.growRangeRight(range); if (startLine > range.endLine || endLine < range.startLine) return null; var replacementLineCount = textInputData.split("\n").length - 1; var lineCountDelta = replacementLineCount - range.linesCount; if (startLine + lines.length - endLine - 1 !== lineCountDelta) return null; var cloneFromLine = Math.min(range.startLine, startLine); var postLastLine = startLine + lines.length + lineCountDelta; var cloneToLine = Math.min(Math.max(postLastLine, range.endLine) + 1, this._textModel.linesCount); var domModel = this._textModel.slice(cloneFromLine, cloneToLine); domModel.editRange(range.shift(-cloneFromLine), textInputData); for (var i = 0; i < lines.length; ++i) { if (domModel.line(i + startLine - cloneFromLine) !== lines[i]) return null; } return new WebInspector.DefaultTextEditor.EditInfo(range, textInputData); }, _assertDOMMatchesTextModel: function() { if (!WebInspector.debugDefaultTextEditor) return; console.assert(this.element.innerText === this._textModel.text() + "\n", "DOM does not match model."); for (var lineRow = this._container.firstChild; lineRow; lineRow = lineRow.nextSibling) { var lineNumber = lineRow.lineNumber; if (typeof lineNumber !== "number") { console.warn("No line number on line row"); continue; } if (lineRow._chunk) { var chunk = lineRow._chunk; console.assert(lineNumber === chunk.startLine); var chunkText = this._textModel.copyRange(new WebInspector.TextRange(chunk.startLine, 0, chunk.endLine - 1, this._textModel.lineLength(chunk.endLine - 1))); if (chunkText !== lineRow.textContent) console.warn("Chunk is not matching: %d %O", lineNumber, lineRow); } else if (this._textModel.line(lineNumber) !== lineRow.textContent) console.warn("Line is not matching: %d %O", lineNumber, lineRow); } }, _closingBlockOffset: function(oldRange, selection) { var nestingLevel = 1; for (var i = oldRange.endLine; i >= 0; --i) { var attribute = this._textModel.getAttribute(i, "highlight"); if (!attribute) continue; var columnNumbers = Object.keys(attribute).reverse(); for (var j = 0; j < columnNumbers.length; ++j) { var column = columnNumbers[j]; if (attribute[column].tokenType === "block-start") { if (!(--nestingLevel)) { var lineContent = this._textModel.line(i); return lineContent.length - lineContent.trimLeft().length; } } if (attribute[column].tokenType === "block-end") ++nestingLevel; } } return -1; }, textChanged: function(oldRange, newRange) { this.beginDomUpdates(); this._removeDecorationsInRange(oldRange); this._updateChunksForRanges(oldRange, newRange); this._updateHighlightsForRange(newRange); this.endDomUpdates(); }, _removeDecorationsInRange: function(range) { for (var i = this._chunkNumberForLine(range.startLine); i < this._textChunks.length; ++i) { var chunk = this._textChunks[i]; if (chunk.startLine > range.endLine) break; chunk.removeAllDecorations(); } }, _updateChunksForRanges: function(oldRange, newRange) { var firstDamagedChunkNumber = this._chunkNumberForLine(oldRange.startLine); var lastDamagedChunkNumber = firstDamagedChunkNumber; while (lastDamagedChunkNumber + 1 < this._textChunks.length) { if (this._textChunks[lastDamagedChunkNumber + 1].startLine > oldRange.endLine) break; ++lastDamagedChunkNumber; } var firstDamagedChunk = this._textChunks[firstDamagedChunkNumber]; var lastDamagedChunk = this._textChunks[lastDamagedChunkNumber]; var linesDiff = newRange.linesCount - oldRange.linesCount; if (linesDiff) { for (var chunkNumber = lastDamagedChunkNumber + 1; chunkNumber < this._textChunks.length; ++chunkNumber) this._textChunks[chunkNumber].startLine += linesDiff; } var lastUndamagedChunk = firstDamagedChunkNumber > 0 ? this._textChunks[firstDamagedChunkNumber - 1] : null; var firstUndamagedChunk = lastDamagedChunkNumber + 1 < this._textChunks.length ? this._textChunks[lastDamagedChunkNumber + 1] : null; var removeDOMFromNode = lastUndamagedChunk ? lastUndamagedChunk.lastElement().nextSibling : this._container.firstChild; var removeDOMToNode = firstUndamagedChunk ? firstUndamagedChunk.firstElement() : null; if (!linesDiff && firstDamagedChunk === lastDamagedChunk && firstDamagedChunk._expandedLineRows) { var lastUndamagedLineRow = lastDamagedChunk.expandedLineRow(oldRange.startLine - 1); var firstUndamagedLineRow = firstDamagedChunk.expandedLineRow(oldRange.endLine + 1); var localRemoveDOMFromNode = lastUndamagedLineRow ? lastUndamagedLineRow.nextSibling : removeDOMFromNode; var localRemoveDOMToNode = firstUndamagedLineRow || removeDOMToNode; removeSubsequentNodes(localRemoveDOMFromNode, localRemoveDOMToNode); for (var i = newRange.startLine; i < newRange.endLine + 1; ++i) { var row = firstDamagedChunk._createRow(i); firstDamagedChunk._expandedLineRows[i - firstDamagedChunk.startLine] = row; this._container.insertBefore(row, localRemoveDOMToNode); } firstDamagedChunk.updateCollapsedLineRow(); this._assertDOMMatchesTextModel(); return; } removeSubsequentNodes(removeDOMFromNode, removeDOMToNode); this._textChunks.splice(firstDamagedChunkNumber, lastDamagedChunkNumber - firstDamagedChunkNumber + 1); var startLine = firstDamagedChunk.startLine; var endLine = lastDamagedChunk.endLine + linesDiff; var lineSpan = endLine - startLine; var insertionIndex = firstDamagedChunkNumber; var chunkSize = Math.ceil(lineSpan / Math.ceil(lineSpan / this._defaultChunkSize)); for (var i = startLine; i < endLine; i += chunkSize) { var chunk = this._createNewChunk(i, Math.min(endLine, i + chunkSize)); this._textChunks.splice(insertionIndex++, 0, chunk); this._container.insertBefore(chunk.element, removeDOMToNode); } this._assertDOMMatchesTextModel(); }, _updateHighlightsForRange: function(range) { var visibleFrom = this._scrollTop(); var visibleTo = visibleFrom + this._clientHeight(); var result = this._findVisibleChunks(visibleFrom, visibleTo); var chunk = this._textChunks[result.end - 1]; var lastVisibleLine = chunk.startLine + chunk.linesCount; lastVisibleLine = Math.max(lastVisibleLine, range.endLine + 1); lastVisibleLine = Math.min(lastVisibleLine, this._textModel.linesCount); var updated = this._highlighter.updateHighlight(range.startLine, lastVisibleLine); if (!updated) { for (var i = this._chunkNumberForLine(range.startLine); i < this._textChunks.length; ++i) this._textChunks[i].collapse(); } this._repaintAll(); }, _collectLinesFromDOM: function(from, to) { var textContents = []; var hasContent = false; for (var node = from ? from.nextSibling : this._container; node && node !== to; node = node.traverseNextNode(this._container)) { if (node._isDecorationsElement) { node = node.nextSibling; if (!node || node === to) break; } hasContent = true; if (node.nodeName.toLowerCase() === "br") textContents.push("\n"); else if (node.nodeType === Node.TEXT_NODE) textContents.push(node.textContent); } if (!hasContent) return []; var textContent = textContents.join(""); textContent = textContent.replace(/\n$/, ""); return textContent.split("\n"); }, _handleSelectionChange: function(event) { var textRange = this._getSelection(); if (textRange) this._lastSelection = textRange; this._delegate.selectionChanged(textRange); }, __proto__: WebInspector.TextEditorChunkedPanel.prototype } WebInspector.TextEditorMainChunk = function(chunkedPanel, startLine, endLine) { this._chunkedPanel = chunkedPanel; this._textModel = chunkedPanel._textModel; this.element = document.createElement("div"); this.element.lineNumber = startLine; this.element.className = "webkit-line-content"; this.element._chunk = this; this._startLine = startLine; endLine = Math.min(this._textModel.linesCount, endLine); this.linesCount = endLine - startLine; this._expanded = false; this.updateCollapsedLineRow(); } WebInspector.TextEditorMainChunk.prototype = { addDecoration: function(decoration) { this._chunkedPanel.beginDomUpdates(); if (typeof decoration === "string") this.element.addStyleClass(decoration); else { if (!this.element.decorationsElement) { this.element.decorationsElement = document.createElement("div"); this.element.decorationsElement.className = "webkit-line-decorations"; this.element.decorationsElement._isDecorationsElement = true; this.element.appendChild(this.element.decorationsElement); } this.element.decorationsElement.appendChild(decoration); } this._chunkedPanel.endDomUpdates(); }, removeDecoration: function(decoration) { this._chunkedPanel.beginDomUpdates(); if (typeof decoration === "string") this.element.removeStyleClass(decoration); else if (this.element.decorationsElement) this.element.decorationsElement.removeChild(decoration); this._chunkedPanel.endDomUpdates(); }, removeAllDecorations: function() { this._chunkedPanel.beginDomUpdates(); this.element.className = "webkit-line-content"; if (this.element.decorationsElement) { this.element.removeChild(this.element.decorationsElement); delete this.element.decorationsElement; } this._chunkedPanel.endDomUpdates(); }, isDecorated: function() { return this.element.className !== "webkit-line-content" || !!(this.element.decorationsElement && this.element.decorationsElement.firstChild); }, get startLine() { return this._startLine; }, get endLine() { return this._startLine + this.linesCount; }, set startLine(startLine) { this._startLine = startLine; this.element.lineNumber = startLine; if (this._expandedLineRows) { for (var i = 0; i < this._expandedLineRows.length; ++i) this._expandedLineRows[i].lineNumber = startLine + i; } }, expanded: function() { return this._expanded; }, expand: function() { if (this._expanded) return; this._expanded = true; if (this.linesCount === 1) return; this._chunkedPanel.beginDomUpdates(); this._expandedLineRows = []; var parentElement = this.element.parentElement; for (var i = this.startLine; i < this.startLine + this.linesCount; ++i) { var lineRow = this._createRow(i); parentElement.insertBefore(lineRow, this.element); this._expandedLineRows.push(lineRow); } parentElement.removeChild(this.element); this._chunkedPanel.endDomUpdates(); }, collapse: function() { if (!this._expanded) return; this._expanded = false; if (this.linesCount === 1) return; this._chunkedPanel.beginDomUpdates(); var elementInserted = false; for (var i = 0; i < this._expandedLineRows.length; ++i) { var lineRow = this._expandedLineRows[i]; var parentElement = lineRow.parentElement; if (parentElement) { if (!elementInserted) { elementInserted = true; parentElement.insertBefore(this.element, lineRow); } parentElement.removeChild(lineRow); } this._chunkedPanel._releaseLinesHighlight(lineRow); } delete this._expandedLineRows; this._chunkedPanel.endDomUpdates(); }, get height() { if (!this._expandedLineRows) return this._chunkedPanel._totalHeight(this.element); return this._chunkedPanel._totalHeight(this._expandedLineRows[0], this._expandedLineRows[this._expandedLineRows.length - 1]); }, get offsetTop() { return (this._expandedLineRows && this._expandedLineRows.length) ? this._expandedLineRows[0].offsetTop : this.element.offsetTop; }, _createRow: function(lineNumber) { var lineRow = this._chunkedPanel._cachedRows.pop() || document.createElement("div"); lineRow.lineNumber = lineNumber; lineRow.className = "webkit-line-content"; lineRow.textContent = this._textModel.line(lineNumber); if (!lineRow.textContent) lineRow.appendChild(document.createElement("br")); return lineRow; }, lineRowContainingLine: function(lineNumber) { if (!this._expanded) return this.element; return this.expandedLineRow(lineNumber); }, expandedLineRow: function(lineNumber) { if (!this._expanded || lineNumber < this.startLine || lineNumber >= this.startLine + this.linesCount) return null; if (!this._expandedLineRows) return this.element; return this._expandedLineRows[lineNumber - this.startLine]; }, updateCollapsedLineRow: function() { if (this.linesCount === 1 && this._expanded) return; var lines = []; for (var i = this.startLine; i < this.startLine + this.linesCount; ++i) lines.push(this._textModel.line(i)); if (WebInspector.FALSE) console.log("Rebuilding chunk with " + lines.length + " lines"); this.element.removeChildren(); this.element.textContent = lines.join("\n"); if (!lines[lines.length - 1]) this.element.appendChild(document.createElement("br")); }, firstElement: function() { return this._expandedLineRows ? this._expandedLineRows[0] : this.element; }, lastElement: function() { return this._expandedLineRows ? this._expandedLineRows[this._expandedLineRows.length - 1] : this.element; } } WebInspector.debugDefaultTextEditor = false; WebInspector.SourceFrame = function(contentProvider) { WebInspector.View.call(this); this.element.addStyleClass("script-view"); this._url = contentProvider.contentURL(); this._contentProvider = contentProvider; var textEditorDelegate = new WebInspector.TextEditorDelegateForSourceFrame(this); if (WebInspector.experimentsSettings.codemirror.isEnabled()) { importScript("CodeMirrorTextEditor.js"); this._textEditor = new WebInspector.CodeMirrorTextEditor(this._url, textEditorDelegate); } else this._textEditor = new WebInspector.DefaultTextEditor(this._url, textEditorDelegate); this._currentSearchResultIndex = -1; this._searchResults = []; this._messages = []; this._rowMessages = {}; this._messageBubbles = {}; this._textEditor.setReadOnly(!this.canEditSource()); this._shortcuts = {}; this._shortcuts[WebInspector.KeyboardShortcut.makeKey("s", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)] = this._commitEditing.bind(this); this.element.addEventListener("keydown", this._handleKeyDown.bind(this), false); } WebInspector.SourceFrame.createSearchRegex = function(query, modifiers) { var regex; modifiers = modifiers || ""; try { if (/^\/.*\/$/.test(query)) regex = new RegExp(query.substring(1, query.length - 1), modifiers); } catch (e) { } if (!regex) regex = createPlainTextSearchRegex(query, "i" + modifiers); return regex; } WebInspector.SourceFrame.Events = { ScrollChanged: "ScrollChanged", SelectionChanged: "SelectionChanged" } WebInspector.SourceFrame.prototype = { wasShown: function() { this._ensureContentLoaded(); this._textEditor.show(this.element); this._wasShownOrLoaded(); }, willHide: function() { WebInspector.View.prototype.willHide.call(this); this._clearLineHighlight(); this._clearLineToReveal(); }, statusBarItems: function() { return []; }, defaultFocusedElement: function() { return this._textEditor.defaultFocusedElement(); }, get loaded() { return this._loaded; }, hasContent: function() { return true; }, get textEditor() { return this._textEditor; }, _ensureContentLoaded: function() { if (!this._contentRequested) { this._contentRequested = true; this._contentProvider.requestContent(this.setContent.bind(this)); } }, addMessage: function(msg) { this._messages.push(msg); if (this.loaded) this.addMessageToSource(msg.line - 1, msg); }, clearMessages: function() { for (var line in this._messageBubbles) { var bubble = this._messageBubbles[line]; bubble.parentNode.removeChild(bubble); } this._messages = []; this._rowMessages = {}; this._messageBubbles = {}; this._textEditor.doResize(); }, canHighlightLine: function(line) { return true; }, highlightLine: function(line) { this._clearLineToReveal(); this._clearLineToScrollTo(); this._lineToHighlight = line; this._innerHighlightLineIfNeeded(); this._textEditor.setSelection(WebInspector.TextRange.createFromLocation(line, 0)); }, _innerHighlightLineIfNeeded: function() { if (typeof this._lineToHighlight === "number") { if (this.loaded && this._textEditor.isShowing()) { this._textEditor.highlightLine(this._lineToHighlight); delete this._lineToHighlight } } }, _clearLineHighlight: function() { this._textEditor.clearLineHighlight(); delete this._lineToHighlight; }, revealLine: function(line) { this._clearLineHighlight(); this._clearLineToScrollTo(); this._lineToReveal = line; this._innerRevealLineIfNeeded(); }, _innerRevealLineIfNeeded: function() { if (typeof this._lineToReveal === "number") { if (this.loaded && this._textEditor.isShowing()) { this._textEditor.revealLine(this._lineToReveal); delete this._lineToReveal } } }, _clearLineToReveal: function() { delete this._lineToReveal; }, scrollToLine: function(line) { this._clearLineHighlight(); this._clearLineToReveal(); this._lineToScrollTo = line; this._innerScrollToLineIfNeeded(); }, _innerScrollToLineIfNeeded: function() { if (typeof this._lineToScrollTo === "number") { if (this.loaded && this._textEditor.isShowing()) { this._textEditor.scrollToLine(this._lineToScrollTo); delete this._lineToScrollTo } } }, _clearLineToScrollTo: function() { delete this._lineToScrollTo; }, setSelection: function(textRange) { this._selectionToSet = textRange; this._innerSetSelectionIfNeeded(); }, _innerSetSelectionIfNeeded: function() { if (this._selectionToSet && this.loaded && this._textEditor.isShowing()) { this._textEditor.setSelection(this._selectionToSet); delete this._selectionToSet; } }, _wasShownOrLoaded: function() { this._innerHighlightLineIfNeeded(); this._innerRevealLineIfNeeded(); this._innerScrollToLineIfNeeded(); this._innerSetSelectionIfNeeded(); }, onTextChanged: function(oldRange, newRange) { if (!this._isReplacing) WebInspector.searchController.cancelSearch(); this.clearMessages(); }, setContent: function(content, contentEncoded, mimeType) { this._textEditor.mimeType = mimeType; this._loaded = true; this._textEditor.setText(content || ""); this._textEditor.beginUpdates(); this._setTextEditorDecorations(); this._wasShownOrLoaded(); if (this._delayedFindSearchMatches) { this._delayedFindSearchMatches(); delete this._delayedFindSearchMatches; } this.onTextEditorContentLoaded(); this._textEditor.endUpdates(); }, onTextEditorContentLoaded: function() {}, _setTextEditorDecorations: function() { this._rowMessages = {}; this._messageBubbles = {}; this._textEditor.beginUpdates(); this._addExistingMessagesToSource(); this._textEditor.doResize(); this._textEditor.endUpdates(); }, performSearch: function(query, callback) { this.searchCanceled(); function doFindSearchMatches(query) { this._currentSearchResultIndex = -1; this._searchResults = []; var regex = WebInspector.SourceFrame.createSearchRegex(query); this._searchResults = this._collectRegexMatches(regex); var shiftToIndex = 0; var selection = this._textEditor.lastSelection(); for (var i = 0; selection && i < this._searchResults.length; ++i) { if (this._searchResults[i].compareTo(selection) >= 0) { shiftToIndex = i; break; } } if (shiftToIndex) this._searchResults = this._searchResults.rotate(shiftToIndex); callback(this, this._searchResults.length); } if (this.loaded) doFindSearchMatches.call(this, query); else this._delayedFindSearchMatches = doFindSearchMatches.bind(this, query); this._ensureContentLoaded(); }, searchCanceled: function() { delete this._delayedFindSearchMatches; if (!this.loaded) return; this._currentSearchResultIndex = -1; this._searchResults = []; this._textEditor.markAndRevealRange(null); }, hasSearchResults: function() { return this._searchResults.length > 0; }, jumpToFirstSearchResult: function() { this.jumpToSearchResult(0); }, jumpToLastSearchResult: function() { this.jumpToSearchResult(this._searchResults.length - 1); }, jumpToNextSearchResult: function() { this.jumpToSearchResult(this._currentSearchResultIndex + 1); }, jumpToPreviousSearchResult: function() { this.jumpToSearchResult(this._currentSearchResultIndex - 1); }, showingFirstSearchResult: function() { return this._searchResults.length && this._currentSearchResultIndex === 0; }, showingLastSearchResult: function() { return this._searchResults.length && this._currentSearchResultIndex === (this._searchResults.length - 1); }, get currentSearchResultIndex() { return this._currentSearchResultIndex; }, jumpToSearchResult: function(index) { if (!this.loaded || !this._searchResults.length) return; this._currentSearchResultIndex = (index + this._searchResults.length) % this._searchResults.length; this._textEditor.markAndRevealRange(this._searchResults[this._currentSearchResultIndex]); }, replaceSearchMatchWith: function(text) { var range = this._searchResults[this._currentSearchResultIndex]; if (!range) return; this._textEditor.markAndRevealRange(null); this._isReplacing = true; var newRange = this._textEditor.editRange(range, text); delete this._isReplacing; this._textEditor.setSelection(newRange.collapseToEnd()); }, replaceAllWith: function(query, replacement) { this._textEditor.markAndRevealRange(null); var text = this._textEditor.text(); var range = this._textEditor.range(); text = text.replace(WebInspector.SourceFrame.createSearchRegex(query, "g"), replacement); this._isReplacing = true; this._textEditor.editRange(range, text); delete this._isReplacing; }, _collectRegexMatches: function(regexObject) { var ranges = []; for (var i = 0; i < this._textEditor.linesCount; ++i) { var line = this._textEditor.line(i); var offset = 0; do { var match = regexObject.exec(line); if (match) { if (match[0].length) ranges.push(new WebInspector.TextRange(i, offset + match.index, i, offset + match.index + match[0].length)); offset += match.index + 1; line = line.substring(match.index + 1); } } while (match && line); } return ranges; }, _addExistingMessagesToSource: function() { var length = this._messages.length; for (var i = 0; i < length; ++i) this.addMessageToSource(this._messages[i].line - 1, this._messages[i]); }, addMessageToSource: function(lineNumber, msg) { if (lineNumber >= this._textEditor.linesCount) lineNumber = this._textEditor.linesCount - 1; if (lineNumber < 0) lineNumber = 0; var messageBubbleElement = this._messageBubbles[lineNumber]; if (!messageBubbleElement || messageBubbleElement.nodeType !== Node.ELEMENT_NODE || !messageBubbleElement.hasStyleClass("webkit-html-message-bubble")) { messageBubbleElement = document.createElement("div"); messageBubbleElement.className = "webkit-html-message-bubble"; this._messageBubbles[lineNumber] = messageBubbleElement; this._textEditor.addDecoration(lineNumber, messageBubbleElement); } var rowMessages = this._rowMessages[lineNumber]; if (!rowMessages) { rowMessages = []; this._rowMessages[lineNumber] = rowMessages; } for (var i = 0; i < rowMessages.length; ++i) { if (rowMessages[i].consoleMessage.isEqual(msg)) { rowMessages[i].repeatCount = msg.totalRepeatCount; this._updateMessageRepeatCount(rowMessages[i]); return; } } var rowMessage = { consoleMessage: msg }; rowMessages.push(rowMessage); var imageURL; switch (msg.level) { case WebInspector.ConsoleMessage.MessageLevel.Error: messageBubbleElement.addStyleClass("webkit-html-error-message"); imageURL = "Images/errorIcon.png"; break; case WebInspector.ConsoleMessage.MessageLevel.Warning: messageBubbleElement.addStyleClass("webkit-html-warning-message"); imageURL = "Images/warningIcon.png"; break; } var messageLineElement = document.createElement("div"); messageLineElement.className = "webkit-html-message-line"; messageBubbleElement.appendChild(messageLineElement); var image = document.createElement("img"); image.src = imageURL; image.className = "webkit-html-message-icon"; messageLineElement.appendChild(image); messageLineElement.appendChild(document.createTextNode(msg.message)); rowMessage.element = messageLineElement; rowMessage.repeatCount = msg.totalRepeatCount; this._updateMessageRepeatCount(rowMessage); }, _updateMessageRepeatCount: function(rowMessage) { if (rowMessage.repeatCount < 2) return; if (!rowMessage.repeatCountElement) { var repeatCountElement = document.createElement("span"); rowMessage.element.appendChild(repeatCountElement); rowMessage.repeatCountElement = repeatCountElement; } rowMessage.repeatCountElement.textContent = WebInspector.UIString(" (repeated %d times)", rowMessage.repeatCount); }, removeMessageFromSource: function(lineNumber, msg) { if (lineNumber >= this._textEditor.linesCount) lineNumber = this._textEditor.linesCount - 1; if (lineNumber < 0) lineNumber = 0; var rowMessages = this._rowMessages[lineNumber]; for (var i = 0; rowMessages && i < rowMessages.length; ++i) { var rowMessage = rowMessages[i]; if (rowMessage.consoleMessage !== msg) continue; var messageLineElement = rowMessage.element; var messageBubbleElement = messageLineElement.parentElement; messageBubbleElement.removeChild(messageLineElement); rowMessages.remove(rowMessage); if (!rowMessages.length) delete this._rowMessages[lineNumber]; if (!messageBubbleElement.childElementCount) { this._textEditor.removeDecoration(lineNumber, messageBubbleElement); delete this._messageBubbles[lineNumber]; } break; } }, populateLineGutterContextMenu: function(contextMenu, lineNumber) { }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { }, inheritScrollPositions: function(sourceFrame) { this._textEditor.inheritScrollPositions(sourceFrame._textEditor); }, canEditSource: function() { return false; }, commitEditing: function(text) { }, selectionChanged: function(textRange) { this.dispatchEventToListeners(WebInspector.SourceFrame.Events.SelectionChanged, textRange); }, scrollChanged: function(lineNumber) { this.dispatchEventToListeners(WebInspector.SourceFrame.Events.ScrollChanged, lineNumber); }, _handleKeyDown: function(e) { var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent(e); var handler = this._shortcuts[shortcutKey]; if (handler && handler()) e.consume(true); }, _commitEditing: function() { if (this._textEditor.readOnly()) return false; var content = this._textEditor.text(); this.commitEditing(content); return true; }, __proto__: WebInspector.View.prototype } WebInspector.TextEditorDelegateForSourceFrame = function(sourceFrame) { this._sourceFrame = sourceFrame; } WebInspector.TextEditorDelegateForSourceFrame.prototype = { onTextChanged: function(oldRange, newRange) { this._sourceFrame.onTextChanged(oldRange, newRange); }, selectionChanged: function(textRange) { this._sourceFrame.selectionChanged(textRange); }, scrollChanged: function(lineNumber) { this._sourceFrame.scrollChanged(lineNumber); }, populateLineGutterContextMenu: function(contextMenu, lineNumber) { this._sourceFrame.populateLineGutterContextMenu(contextMenu, lineNumber); }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { this._sourceFrame.populateTextAreaContextMenu(contextMenu, lineNumber); }, createLink: function(hrefValue, isExternal) { var targetLocation = WebInspector.ParsedURL.completeURL(this._sourceFrame._url, hrefValue); return WebInspector.linkifyURLAsNode(targetLocation || hrefValue, hrefValue, undefined, isExternal); }, __proto__: WebInspector.TextEditorDelegate.prototype } WebInspector.ResourceView = function(resource) { WebInspector.View.call(this); this.registerRequiredCSS("resourceView.css"); this.element.addStyleClass("resource-view"); this.resource = resource; } WebInspector.ResourceView.prototype = { hasContent: function() { return false; }, __proto__: WebInspector.View.prototype } WebInspector.ResourceView.hasTextContent = function(resource) { if (resource.type.isTextType()) return true; if (resource.type === WebInspector.resourceTypes.Other) return resource.content && !resource.contentEncoded; return false; } WebInspector.ResourceView.nonSourceViewForResource = function(resource) { switch (resource.type) { case WebInspector.resourceTypes.Image: return new WebInspector.ImageView(resource); case WebInspector.resourceTypes.Font: return new WebInspector.FontView(resource); default: return new WebInspector.ResourceView(resource); } } WebInspector.ResourceSourceFrame = function(resource) { this._resource = resource; WebInspector.SourceFrame.call(this, resource); } WebInspector.ResourceSourceFrame.prototype = { get resource() { return this._resource; }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { contextMenu.appendApplicableItems(this._resource); if (this._resource.request) contextMenu.appendApplicableItems(this._resource.request); }, __proto__: WebInspector.SourceFrame.prototype } WebInspector.FontView = function(resource) { WebInspector.ResourceView.call(this, resource); this.element.addStyleClass("font"); } WebInspector.FontView._fontPreviewLines = [ "ABCDEFGHIJKLM", "NOPQRSTUVWXYZ", "abcdefghijklm", "nopqrstuvwxyz", "1234567890" ]; WebInspector.FontView._fontId = 0; WebInspector.FontView._measureFontSize = 50; WebInspector.FontView.prototype = { hasContent: function() { return true; }, _createContentIfNeeded: function() { if (this.fontPreviewElement) return; var uniqueFontName = "WebInspectorFontPreview" + (++WebInspector.FontView._fontId); this.fontStyleElement = document.createElement("style"); this.fontStyleElement.textContent = "@font-face { font-family: \"" + uniqueFontName + "\"; src: url(" + this.resource.url + "); }"; document.head.appendChild(this.fontStyleElement); var fontPreview = document.createElement("div"); for (var i = 0; i < WebInspector.FontView._fontPreviewLines.length; ++i) { if (i > 0) fontPreview.appendChild(document.createElement("br")); fontPreview.appendChild(document.createTextNode(WebInspector.FontView._fontPreviewLines[i])); } this.fontPreviewElement = fontPreview.cloneNode(true); this.fontPreviewElement.style.setProperty("font-family", uniqueFontName); this.fontPreviewElement.style.setProperty("visibility", "hidden"); this._dummyElement = fontPreview; this._dummyElement.style.visibility = "hidden"; this._dummyElement.style.zIndex = "-1"; this._dummyElement.style.display = "inline"; this._dummyElement.style.position = "absolute"; this._dummyElement.style.setProperty("font-family", uniqueFontName); this._dummyElement.style.setProperty("font-size", WebInspector.FontView._measureFontSize + "px"); this.element.appendChild(this.fontPreviewElement); }, wasShown: function() { this._createContentIfNeeded(); this.updateFontPreviewSize(); }, onResize: function() { if (this._inResize) return; this._inResize = true; try { this.updateFontPreviewSize(); } finally { delete this._inResize; } }, _measureElement: function() { this.element.appendChild(this._dummyElement); var result = { width: this._dummyElement.offsetWidth, height: this._dummyElement.offsetHeight }; this.element.removeChild(this._dummyElement); return result; }, updateFontPreviewSize: function() { if (!this.fontPreviewElement || !this.isShowing()) return; this.fontPreviewElement.style.removeProperty("visibility"); var dimension = this._measureElement(); const height = dimension.height; const width = dimension.width; const containerWidth = this.element.offsetWidth - 50; const containerHeight = this.element.offsetHeight - 30; if (!height || !width || !containerWidth || !containerHeight) { this.fontPreviewElement.style.removeProperty("font-size"); return; } var widthRatio = containerWidth / width; var heightRatio = containerHeight / height; var finalFontSize = Math.floor(WebInspector.FontView._measureFontSize * Math.min(widthRatio, heightRatio)) - 2; this.fontPreviewElement.style.setProperty("font-size", finalFontSize + "px", null); }, __proto__: WebInspector.ResourceView.prototype } WebInspector.ImageView = function(resource) { WebInspector.ResourceView.call(this, resource); this.element.addStyleClass("image"); } WebInspector.ImageView.prototype = { hasContent: function() { return true; }, wasShown: function() { this._createContentIfNeeded(); }, _createContentIfNeeded: function() { if (this._container) return; var imageContainer = document.createElement("div"); imageContainer.className = "image"; this.element.appendChild(imageContainer); var imagePreviewElement = document.createElement("img"); imagePreviewElement.addStyleClass("resource-image-view"); imageContainer.appendChild(imagePreviewElement); imagePreviewElement.addEventListener("contextmenu", this._contextMenu.bind(this), true); this._container = document.createElement("div"); this._container.className = "info"; this.element.appendChild(this._container); var imageNameElement = document.createElement("h1"); imageNameElement.className = "title"; imageNameElement.textContent = this.resource.displayName; this._container.appendChild(imageNameElement); var infoListElement = document.createElement("dl"); infoListElement.className = "infoList"; this.resource.populateImageSource(imagePreviewElement); function onImageLoad() { var content = this.resource.content; if (content) var resourceSize = this._base64ToSize(content); else var resourceSize = this.resource.resourceSize; var imageProperties = [ { name: WebInspector.UIString("Dimensions"), value: WebInspector.UIString("%d × %d", imagePreviewElement.naturalWidth, imagePreviewElement.naturalHeight) }, { name: WebInspector.UIString("File size"), value: Number.bytesToString(resourceSize) }, { name: WebInspector.UIString("MIME type"), value: this.resource.mimeType } ]; infoListElement.removeChildren(); for (var i = 0; i < imageProperties.length; ++i) { var dt = document.createElement("dt"); dt.textContent = imageProperties[i].name; infoListElement.appendChild(dt); var dd = document.createElement("dd"); dd.textContent = imageProperties[i].value; infoListElement.appendChild(dd); } var dt = document.createElement("dt"); dt.textContent = WebInspector.UIString("URL"); infoListElement.appendChild(dt); var dd = document.createElement("dd"); var externalResource = true; dd.appendChild(WebInspector.linkifyURLAsNode(this.resource.url, undefined, undefined, externalResource)); infoListElement.appendChild(dd); this._container.appendChild(infoListElement); } imagePreviewElement.addEventListener("load", onImageLoad.bind(this), false); }, _base64ToSize: function(content) { if (!content.length) return 0; var size = (content.length || 0) * 3 / 4; if (content.length > 0 && content[content.length - 1] === "=") size--; if (content.length > 1 && content[content.length - 2] === "=") size--; return size; }, _contextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy image URL" : "Copy Image URL"), this._copyImageURL.bind(this)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open image in new tab" : "Open Image in New Tab"), this._openInNewTab.bind(this)); contextMenu.show(); }, _copyImageURL: function(event) { InspectorFrontendHost.copyText(this.resource.url); }, _openInNewTab: function(event) { InspectorFrontendHost.openInNewTab(this.resource.url); }, __proto__: WebInspector.ResourceView.prototype } WebInspector.SplitView = function(isVertical, sidebarSizeSettingName, defaultSidebarSize) { WebInspector.View.call(this); this._isVertical = isVertical; this.registerRequiredCSS("splitView.css"); this.element.className = "split-view"; this._firstElement = document.createElement("div"); this._firstElement.className = "split-view-contents split-view-contents-" + (isVertical ? "vertical" : "horizontal"); if (isVertical) this._firstElement.style.left = 0; else this._firstElement.style.top = 0; this.element.appendChild(this._firstElement); this._secondElement = document.createElement("div"); this._secondElement.className = "split-view-contents split-view-contents-" + (isVertical ? "vertical" : "horizontal"); if (isVertical) this._secondElement.style.right = 0; else this._secondElement.style.bottom = 0; this.element.appendChild(this._secondElement); this._resizerElement = document.createElement("div"); this._resizerElement.className = "split-view-resizer split-view-resizer-" + (isVertical ? "vertical" : "horizontal"); this.installResizer(this._resizerElement); this._resizable = true; this.element.appendChild(this._resizerElement); defaultSidebarSize = defaultSidebarSize || 200; this._savedSidebarSize = defaultSidebarSize; this._sidebarSizeSettingName = sidebarSizeSettingName; if (this._sidebarSizeSettingName) WebInspector.settings[this._sidebarSizeSettingName] = WebInspector.settings.createSetting(this._sidebarSizeSettingName, undefined); this._secondIsSidebar = true; } WebInspector.SplitView.prototype = { firstElement: function() { return this._firstElement; }, secondElement: function() { return this._secondElement; }, setSecondIsSidebar: function(secondIsSidebar) { this._secondIsSidebar = secondIsSidebar; }, resizerElement: function() { return this._resizerElement; }, showOnlyFirst: function() { this._showOnly(this._firstElement, this._secondElement); }, showOnlySecond: function() { this._showOnly(this._secondElement, this._firstElement); }, _showOnly: function(sideA, sideB) { sideA.removeStyleClass("hidden"); sideA.addStyleClass("maximized"); sideB.addStyleClass("hidden"); sideB.removeStyleClass("maximized"); this._removeAllLayoutProperties(); this._firstElement.style.right = 0; this._firstElement.style.bottom = 0; this._firstElement.style.width = "100%"; this._firstElement.style.height = "100%"; this._secondElement.style.left = 0; this._secondElement.style.top = 0; this._secondElement.style.width = "100%"; this._secondElement.style.height = "100%"; this._isShowingOne = true; this.setResizable(false); this.doResize(); }, _removeAllLayoutProperties: function() { this._firstElement.style.removeProperty("right"); this._firstElement.style.removeProperty("bottom"); this._firstElement.style.removeProperty("width"); this._firstElement.style.removeProperty("height"); this._secondElement.style.removeProperty("left"); this._secondElement.style.removeProperty("top"); this._secondElement.style.removeProperty("width"); this._secondElement.style.removeProperty("height"); }, showBoth: function() { this._isShowingOne = false; this._firstElement.removeStyleClass("hidden"); this._firstElement.removeStyleClass("maximized"); this._secondElement.removeStyleClass("hidden"); this._secondElement.removeStyleClass("maximized"); delete this._sidebarSize; this.setSidebarSize(this._lastSidebarSize()); this.setResizable(true); this.doResize(); }, setResizable: function(resizable) { if (this._resizable === resizable) return; this._resizable = resizable; if (resizable) this._resizerElement.removeStyleClass("hidden"); else this._resizerElement.addStyleClass("hidden"); }, setSidebarSize: function(size) { if (this._sidebarSize === size) return; size = this.applyConstraints(size); this._innerSetSidebarSize(size); this._saveSidebarSize(size); }, sidebarSize: function() { return this._sidebarSize; }, totalSize: function() { return this._totalSize; }, _innerSetSidebarSize: function(size) { if (this._isShowingOne) return; this._removeAllLayoutProperties(); if (this._isVertical) { var resizerWidth = this._resizerElement.offsetWidth; if (this._secondIsSidebar) { this._firstElement.style.right = size + "px"; this._secondElement.style.width = size + "px"; this._resizerElement.style.right = size - resizerWidth / 2 + "px"; } else { this._firstElement.style.width = size + "px";; this._secondElement.style.left = size + "px";; this._resizerElement.style.left = size - resizerWidth / 2 + "px"; } } else { var resizerHeight = this._resizerElement.offsetHeight; if (this._secondIsSidebar) { this._firstElement.style.bottom = size + "px";; this._secondElement.style.height = size + "px";; this._resizerElement.style.bottom = size - resizerHeight / 2 + "px"; } else { this._firstElement.style.height = size + "px";; this._secondElement.style.top = size + "px";; this._resizerElement.style.top = size - resizerHeight / 2 + "px"; } } this._sidebarSize = size; this.doResize(); }, applyConstraints: function(size) { const minSize = 20; size = Math.max(size, minSize); if (this._totalSize - size < minSize) size = this._totalSize - minSize; return size; }, wasShown: function() { this._totalSize = this._isVertical ? this.element.offsetWidth : this.element.offsetHeight; this.setSidebarSize(this._lastSidebarSize()); }, onResize: function() { var oldTotalSize = this._totalSize; this._totalSize = this._isVertical ? this.element.offsetWidth : this.element.offsetHeight; }, _startResizerDragging: function(event) { if (!this._resizable) return false; this._dragOffset = (this._secondIsSidebar ? this._totalSize - this._sidebarSize : this._sidebarSize) - (this._isVertical ? event.pageX : event.pageY); return true; }, _resizerDragging: function(event) { var newOffset = (this._isVertical ? event.pageX : event.pageY) + this._dragOffset; var newSize = (this._secondIsSidebar ? this._totalSize - newOffset : newOffset); this.setSidebarSize(newSize); event.preventDefault(); }, _endResizerDragging: function(event) { delete this._dragOffset; }, installResizer: function(resizerElement) { WebInspector.installDragHandle(resizerElement, this._startResizerDragging.bind(this), this._resizerDragging.bind(this), this._endResizerDragging.bind(this), this._isVertical ? "ew-resize" : "ns-resize"); }, _lastSidebarSize: function() { return this._sidebarSizeSettingName ? WebInspector.settings[this._sidebarSizeSettingName].get() || this._savedSidebarSize : this._savedSidebarSize; }, _saveSidebarSize: function(size) { this._savedSidebarSize = size; if (!this._sidebarSizeSettingName) return; WebInspector.settings[this._sidebarSizeSettingName].set(this._savedSidebarSize); }, __proto__: WebInspector.View.prototype } WebInspector.SidebarView = function(sidebarPosition, sidebarWidthSettingName, defaultSidebarWidth) { WebInspector.SplitView.call(this, true, sidebarWidthSettingName, defaultSidebarWidth || 200); this._leftElement = this.firstElement(); this._rightElement = this.secondElement(); this._minimumSidebarWidth = Preferences.minSidebarWidth; this._minimumMainWidthPercent = 50; this._mainElementHidden = false; this._sidebarElementHidden = false; this._innerSetSidebarPosition(sidebarPosition || WebInspector.SidebarView.SidebarPosition.Left); this.setSecondIsSidebar(sidebarPosition !== WebInspector.SidebarView.SidebarPosition.Left); } WebInspector.SidebarView.EventTypes = { Resized: "Resized" } WebInspector.SidebarView.SidebarPosition = { Left: "Left", Right: "Right" } WebInspector.SidebarView.prototype = { _hasLeftSidebar: function() { return this._sidebarPosition === WebInspector.SidebarView.SidebarPosition.Left; }, get mainElement() { return this._hasLeftSidebar() ? this._rightElement : this._leftElement; }, get sidebarElement() { return this._hasLeftSidebar() ? this._leftElement : this._rightElement; }, _innerSetSidebarPosition: function(sidebarPosition) { this._sidebarPosition = sidebarPosition; if (this._hasLeftSidebar()) { this._leftElement.addStyleClass("split-view-sidebar-left"); this._rightElement.removeStyleClass("split-view-sidebar-right"); } else { this._rightElement.addStyleClass("split-view-sidebar-right"); this._leftElement.removeStyleClass("split-view-sidebar-left"); } }, setMinimumSidebarWidth: function(width) { this._minimumSidebarWidth = width; }, setMinimumMainWidthPercent: function(widthPercent) { this._minimumMainWidthPercent = widthPercent; }, setSidebarWidth: function(width) { this.setSidebarSize(width); }, sidebarWidth: function() { return this.sidebarSize(); }, onResize: function() { WebInspector.SplitView.prototype.onResize.call(this); this.dispatchEventToListeners(WebInspector.SidebarView.EventTypes.Resized, this.sidebarWidth()); }, applyConstraints: function(size) { return Number.constrain(size, this._minimumSidebarWidth, this.element.offsetWidth * (100 - this._minimumMainWidthPercent) / 100); }, hideMainElement: function() { if (this._hasLeftSidebar()) this.showOnlyFirst(); else this.showOnlySecond(); }, showMainElement: function() { this.showBoth(); }, hideSidebarElement: function() { if (this._hasLeftSidebar()) this.showOnlySecond(); else this.showOnlyFirst(); }, showSidebarElement: function() { this.showBoth(); }, elementsToRestoreScrollPositionsFor: function() { return [ this.mainElement, this.sidebarElement ]; }, __proto__: WebInspector.SplitView.prototype } WebInspector.ConsolePanel = function() { WebInspector.Panel.call(this, "console"); WebInspector.consoleView.addEventListener(WebInspector.ConsoleView.Events.EntryAdded, this._consoleMessageAdded, this); WebInspector.consoleView.addEventListener(WebInspector.ConsoleView.Events.ConsoleCleared, this._consoleCleared, this); this._view = WebInspector.consoleView; } WebInspector.ConsolePanel.prototype = { get statusBarItems() { return this._view.statusBarItems; }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); if (WebInspector.drawer.visible) { WebInspector.drawer.hide(WebInspector.Drawer.AnimationType.Immediately); this._drawerWasVisible = true; } this._view.show(this.element); }, willHide: function() { if (this._drawerWasVisible) { WebInspector.drawer.show(this._view, WebInspector.Drawer.AnimationType.Immediately); delete this._drawerWasVisible; } WebInspector.Panel.prototype.willHide.call(this); }, searchCanceled: function() { this._clearCurrentSearchResultHighlight(); delete this._searchResults; delete this._searchRegex; }, performSearch: function(query) { WebInspector.searchController.updateSearchMatchesCount(0, this); this.searchCanceled(); this._searchRegex = createPlainTextSearchRegex(query, "gi"); this._searchResults = []; var messages = WebInspector.consoleView.messages; for (var i = 0; i < messages.length; i++) { if (messages[i].matchesRegex(this._searchRegex)) { this._searchResults.push(messages[i]); this._searchRegex.lastIndex = 0; } } WebInspector.searchController.updateSearchMatchesCount(this._searchResults.length, this); this._currentSearchResultIndex = -1; if (this._searchResults.length) this._jumpToSearchResult(0); }, jumpToNextSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; this._jumpToSearchResult((this._currentSearchResultIndex + 1) % this._searchResults.length); }, jumpToPreviousSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; var index = this._currentSearchResultIndex - 1; if (index === -1) index = this._searchResults.length - 1; this._jumpToSearchResult(index); return true; }, _clearCurrentSearchResultHighlight: function() { if (!this._searchResults) return; var highlightedMessage = this._searchResults[this._currentSearchResultIndex]; if (highlightedMessage) highlightedMessage.clearHighlight(); this._currentSearchResultIndex = -1; }, _jumpToSearchResult: function(index) { this._clearCurrentSearchResultHighlight(); this._currentSearchResultIndex = index; WebInspector.searchController.updateCurrentMatchIndex(this._currentSearchResultIndex, this); this._searchResults[index].highlightSearchResults(this._searchRegex); }, _consoleMessageAdded: function(event) { if (!this._searchRegex || !this.isShowing()) return; var message = event.data; this._searchRegex.lastIndex = 0; if (message.matchesRegex(this._searchRegex)) { this._searchResults.push(message); WebInspector.searchController.updateSearchMatchesCount(this._searchResults.length, this); } }, _consoleCleared: function() { if (!this._searchResults) return; this._clearCurrentSearchResultHighlight(); this._searchResults.length = 0; if (this.isShowing()) WebInspector.searchController.updateSearchMatchesCount(0, this); }, __proto__: WebInspector.Panel.prototype } function defineCommonExtensionSymbols(apiPrivate) { if (!apiPrivate.audits) apiPrivate.audits = {}; apiPrivate.audits.Severity = { Info: "info", Warning: "warning", Severe: "severe" }; if (!apiPrivate.console) apiPrivate.console = {}; apiPrivate.console.Severity = { Tip: "tip", Debug: "debug", Log: "log", Warning: "warning", Error: "error" }; if (!apiPrivate.panels) apiPrivate.panels = {}; apiPrivate.panels.SearchAction = { CancelSearch: "cancelSearch", PerformSearch: "performSearch", NextSearchResult: "nextSearchResult", PreviousSearchResult: "previousSearchResult" }; apiPrivate.Events = { AuditStarted: "audit-started-", ButtonClicked: "button-clicked-", ConsoleMessageAdded: "console-message-added", ElementsPanelObjectSelected: "panel-objectSelected-elements", NetworkRequestFinished: "network-request-finished", Reset: "reset", OpenResource: "open-resource", PanelSearch: "panel-search-", Reload: "Reload", ResourceAdded: "resource-added", ResourceContentCommitted: "resource-content-committed", TimelineEventRecorded: "timeline-event-recorded", ViewShown: "view-shown-", ViewHidden: "view-hidden-" }; apiPrivate.Commands = { AddAuditCategory: "addAuditCategory", AddAuditResult: "addAuditResult", AddConsoleMessage: "addConsoleMessage", AddRequestHeaders: "addRequestHeaders", CreatePanel: "createPanel", CreateSidebarPane: "createSidebarPane", CreateStatusBarButton: "createStatusBarButton", EvaluateOnInspectedPage: "evaluateOnInspectedPage", GetConsoleMessages: "getConsoleMessages", GetHAR: "getHAR", GetPageResources: "getPageResources", GetRequestContent: "getRequestContent", GetResourceContent: "getResourceContent", Subscribe: "subscribe", SetOpenResourceHandler: "setOpenResourceHandler", SetResourceContent: "setResourceContent", SetSidebarContent: "setSidebarContent", SetSidebarHeight: "setSidebarHeight", SetSidebarPage: "setSidebarPage", ShowPanel: "showPanel", StopAuditCategoryRun: "stopAuditCategoryRun", Unsubscribe: "unsubscribe", UpdateAuditProgress: "updateAuditProgress", UpdateButton: "updateButton", InspectedURLChanged: "inspectedURLChanged" }; } function injectedExtensionAPI(injectedScriptId) { var apiPrivate = {}; defineCommonExtensionSymbols(apiPrivate); var commands = apiPrivate.Commands; var events = apiPrivate.Events; var userAction = false; function EventSinkImpl(type, customDispatch) { this._type = type; this._listeners = []; this._customDispatch = customDispatch; } EventSinkImpl.prototype = { addListener: function(callback) { if (typeof callback !== "function") throw "addListener: callback is not a function"; if (this._listeners.length === 0) extensionServer.sendRequest({ command: commands.Subscribe, type: this._type }); this._listeners.push(callback); extensionServer.registerHandler("notify-" + this._type, this._dispatch.bind(this)); }, removeListener: function(callback) { var listeners = this._listeners; for (var i = 0; i < listeners.length; ++i) { if (listeners[i] === callback) { listeners.splice(i, 1); break; } } if (this._listeners.length === 0) extensionServer.sendRequest({ command: commands.Unsubscribe, type: this._type }); }, _fire: function() { var listeners = this._listeners.slice(); for (var i = 0; i < listeners.length; ++i) listeners[i].apply(null, arguments); }, _dispatch: function(request) { if (this._customDispatch) this._customDispatch.call(this, request); else this._fire.apply(this, request.arguments); } } function InspectorExtensionAPI() { this.audits = new Audits(); this.inspectedWindow = new InspectedWindow(); this.panels = new Panels(); this.network = new Network(); defineDeprecatedProperty(this, "webInspector", "resources", "network"); this.timeline = new Timeline(); this.console = new ConsoleAPI(); this.onReset = new EventSink(events.Reset); } InspectorExtensionAPI.prototype = { log: function(message) { extensionServer.sendRequest({ command: commands.Log, message: message }); } } function ConsoleAPI() { this.onMessageAdded = new EventSink(events.ConsoleMessageAdded); } ConsoleAPI.prototype = { getMessages: function(callback) { extensionServer.sendRequest({ command: commands.GetConsoleMessages }, callback); }, addMessage: function(severity, text, url, line) { extensionServer.sendRequest({ command: commands.AddConsoleMessage, severity: severity, text: text, url: url, line: line }); }, get Severity() { return apiPrivate.console.Severity; } } function Network() { function dispatchRequestEvent(message) { var request = message.arguments[1]; request.__proto__ = new Request(message.arguments[0]); this._fire(request); } this.onRequestFinished = new EventSink(events.NetworkRequestFinished, dispatchRequestEvent); defineDeprecatedProperty(this, "network", "onFinished", "onRequestFinished"); this.onNavigated = new EventSink(events.InspectedURLChanged); } Network.prototype = { getHAR: function(callback) { function callbackWrapper(result) { var entries = (result && result.entries) || []; for (var i = 0; i < entries.length; ++i) { entries[i].__proto__ = new Request(entries[i]._requestId); delete entries[i]._requestId; } callback(result); } return extensionServer.sendRequest({ command: commands.GetHAR }, callback && callbackWrapper); }, addRequestHeaders: function(headers) { return extensionServer.sendRequest({ command: commands.AddRequestHeaders, headers: headers, extensionId: window.location.hostname }); } } function RequestImpl(id) { this._id = id; } RequestImpl.prototype = { getContent: function(callback) { function callbackWrapper(response) { callback(response.content, response.encoding); } extensionServer.sendRequest({ command: commands.GetRequestContent, id: this._id }, callback && callbackWrapper); } } function Panels() { var panels = { elements: new ElementsPanel() }; function panelGetter(name) { return panels[name]; } for (var panel in panels) this.__defineGetter__(panel, panelGetter.bind(null, panel)); } Panels.prototype = { create: function(title, icon, page, callback) { var id = "extension-panel-" + extensionServer.nextObjectId(); var request = { command: commands.CreatePanel, id: id, title: title, icon: icon, page: page }; extensionServer.sendRequest(request, callback && callback.bind(this, new ExtensionPanel(id))); }, setOpenResourceHandler: function(callback) { var hadHandler = extensionServer.hasHandler(events.OpenResource); if (!callback) extensionServer.unregisterHandler(events.OpenResource); else { function callbackWrapper(message) { userAction = true; try { callback.call(null, new Resource(message.resource), message.lineNumber); } finally { userAction = false; } } extensionServer.registerHandler(events.OpenResource, callbackWrapper); } if (hadHandler === !callback) extensionServer.sendRequest({ command: commands.SetOpenResourceHandler, "handlerPresent": !!callback }); }, get SearchAction() { return apiPrivate.panels.SearchAction; } } function ExtensionViewImpl(id) { this._id = id; function dispatchShowEvent(message) { var frameIndex = message.arguments[0]; this._fire(window.parent.frames[frameIndex]); } this.onShown = new EventSink(events.ViewShown + id, dispatchShowEvent); this.onHidden = new EventSink(events.ViewHidden + id); } function PanelWithSidebarImpl(id) { this._id = id; } PanelWithSidebarImpl.prototype = { createSidebarPane: function(title, callback) { var id = "extension-sidebar-" + extensionServer.nextObjectId(); var request = { command: commands.CreateSidebarPane, panel: this._id, id: id, title: title }; function callbackWrapper() { callback(new ExtensionSidebarPane(id)); } extensionServer.sendRequest(request, callback && callbackWrapper); }, __proto__: ExtensionViewImpl.prototype } function ElementsPanel() { var id = "elements"; PanelWithSidebar.call(this, id); this.onSelectionChanged = new EventSink(events.ElementsPanelObjectSelected); } function ExtensionPanelImpl(id) { ExtensionViewImpl.call(this, id); this.onSearch = new EventSink(events.PanelSearch + id); } ExtensionPanelImpl.prototype = { createStatusBarButton: function(iconPath, tooltipText, disabled) { var id = "button-" + extensionServer.nextObjectId(); var request = { command: commands.CreateStatusBarButton, panel: this._id, id: id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled }; extensionServer.sendRequest(request); return new Button(id); }, show: function() { if (!userAction) return; var request = { command: commands.ShowPanel, id: this._id }; extensionServer.sendRequest(request); }, __proto__: ExtensionViewImpl.prototype } function ExtensionSidebarPaneImpl(id) { ExtensionViewImpl.call(this, id); } ExtensionSidebarPaneImpl.prototype = { setHeight: function(height) { extensionServer.sendRequest({ command: commands.SetSidebarHeight, id: this._id, height: height }); }, setExpression: function(expression, rootTitle, evaluateOptions) { var callback = extractCallbackArgument(arguments); var request = { command: commands.SetSidebarContent, id: this._id, expression: expression, rootTitle: rootTitle, evaluateOnPage: true, }; if (typeof evaluateOptions === "object") request.evaluateOptions = evaluateOptions; extensionServer.sendRequest(request, callback); }, setObject: function(jsonObject, rootTitle, callback) { extensionServer.sendRequest({ command: commands.SetSidebarContent, id: this._id, expression: jsonObject, rootTitle: rootTitle }, callback); }, setPage: function(page) { extensionServer.sendRequest({ command: commands.SetSidebarPage, id: this._id, page: page }); } } function ButtonImpl(id) { this._id = id; this.onClicked = new EventSink(events.ButtonClicked + id); } ButtonImpl.prototype = { update: function(iconPath, tooltipText, disabled) { var request = { command: commands.UpdateButton, id: this._id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled }; extensionServer.sendRequest(request); } }; function Audits() { } Audits.prototype = { addCategory: function(displayName, resultCount) { var id = "extension-audit-category-" + extensionServer.nextObjectId(); if (typeof resultCount !== "undefined") console.warn("Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead."); extensionServer.sendRequest({ command: commands.AddAuditCategory, id: id, displayName: displayName, resultCount: resultCount }); return new AuditCategory(id); } } function AuditCategoryImpl(id) { function dispatchAuditEvent(request) { var auditResult = new AuditResult(request.arguments[0]); try { this._fire(auditResult); } catch (e) { console.error("Uncaught exception in extension audit event handler: " + e); auditResult.done(); } } this._id = id; this.onAuditStarted = new EventSink(events.AuditStarted + id, dispatchAuditEvent); } function AuditResultImpl(id) { this._id = id; this.createURL = this._nodeFactory.bind(null, "url"); this.createSnippet = this._nodeFactory.bind(null, "snippet"); this.createText = this._nodeFactory.bind(null, "text"); this.createObject = this._nodeFactory.bind(null, "object"); this.createNode = this._nodeFactory.bind(null, "node"); } AuditResultImpl.prototype = { addResult: function(displayName, description, severity, details) { if (details && !(details instanceof AuditResultNode)) details = new AuditResultNode(details instanceof Array ? details : [details]); var request = { command: commands.AddAuditResult, resultId: this._id, displayName: displayName, description: description, severity: severity, details: details }; extensionServer.sendRequest(request); }, createResult: function() { return new AuditResultNode(Array.prototype.slice.call(arguments)); }, updateProgress: function(worked, totalWork) { extensionServer.sendRequest({ command: commands.UpdateAuditProgress, resultId: this._id, progress: worked / totalWork }); }, done: function() { extensionServer.sendRequest({ command: commands.StopAuditCategoryRun, resultId: this._id }); }, get Severity() { return apiPrivate.audits.Severity; }, createResourceLink: function(url, lineNumber) { return { type: "resourceLink", arguments: [url, lineNumber && lineNumber - 1] }; }, _nodeFactory: function(type) { return { type: type, arguments: Array.prototype.slice.call(arguments, 1) }; } } function AuditResultNode(contents) { this.contents = contents; this.children = []; this.expanded = false; } AuditResultNode.prototype = { addChild: function() { var node = new AuditResultNode(Array.prototype.slice.call(arguments)); this.children.push(node); return node; } }; function InspectedWindow() { function dispatchResourceEvent(message) { this._fire(new Resource(message.arguments[0])); } function dispatchResourceContentEvent(message) { this._fire(new Resource(message.arguments[0]), message.arguments[1]); } this.onResourceAdded = new EventSink(events.ResourceAdded, dispatchResourceEvent); this.onResourceContentCommitted = new EventSink(events.ResourceContentCommitted, dispatchResourceContentEvent); } InspectedWindow.prototype = { reload: function(optionsOrUserAgent) { var options = null; if (typeof optionsOrUserAgent === "object") options = optionsOrUserAgent; else if (typeof optionsOrUserAgent === "string") { options = { userAgent: optionsOrUserAgent }; console.warn("Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. " + "Use inspectedWindow.reload({ userAgent: value}) instead."); } return extensionServer.sendRequest({ command: commands.Reload, options: options }); }, eval: function(expression, evaluateOptions) { var callback = extractCallbackArgument(arguments); function callbackWrapper(result) { callback(result.value, result.isException); } var request = { command: commands.EvaluateOnInspectedPage, expression: expression }; if (typeof evaluateOptions === "object") request.evaluateOptions = evaluateOptions; return extensionServer.sendRequest(request, callback && callbackWrapper); }, getResources: function(callback) { function wrapResource(resourceData) { return new Resource(resourceData); } function callbackWrapper(resources) { callback(resources.map(wrapResource)); } return extensionServer.sendRequest({ command: commands.GetPageResources }, callback && callbackWrapper); } } function ResourceImpl(resourceData) { this._url = resourceData.url this._type = resourceData.type; } ResourceImpl.prototype = { get url() { return this._url; }, get type() { return this._type; }, getContent: function(callback) { function callbackWrapper(response) { callback(response.content, response.encoding); } return extensionServer.sendRequest({ command: commands.GetResourceContent, url: this._url }, callback && callbackWrapper); }, setContent: function(content, commit, callback) { return extensionServer.sendRequest({ command: commands.SetResourceContent, url: this._url, content: content, commit: commit }, callback); } } function TimelineImpl() { this.onEventRecorded = new EventSink(events.TimelineEventRecorded); } function ExtensionServerClient() { this._callbacks = {}; this._handlers = {}; this._lastRequestId = 0; this._lastObjectId = 0; this.registerHandler("callback", this._onCallback.bind(this)); var channel = new MessageChannel(); this._port = channel.port1; this._port.addEventListener("message", this._onMessage.bind(this), false); this._port.start(); window.parent.postMessage("registerExtension", [ channel.port2 ], "*"); } ExtensionServerClient.prototype = { sendRequest: function(message, callback) { if (typeof callback === "function") message.requestId = this._registerCallback(callback); return this._port.postMessage(message); }, hasHandler: function(command) { return !!this._handlers[command]; }, registerHandler: function(command, handler) { this._handlers[command] = handler; }, unregisterHandler: function(command) { delete this._handlers[command]; }, nextObjectId: function() { return injectedScriptId + "_" + ++this._lastObjectId; }, _registerCallback: function(callback) { var id = ++this._lastRequestId; this._callbacks[id] = callback; return id; }, _onCallback: function(request) { if (request.requestId in this._callbacks) { var callback = this._callbacks[request.requestId]; delete this._callbacks[request.requestId]; callback(request.result); } }, _onMessage: function(event) { var request = event.data; var handler = this._handlers[request.command]; if (handler) handler.call(this, request); } } function populateInterfaceClass(interface, implementation) { for (var member in implementation) { if (member.charAt(0) === "_") continue; var descriptor = null; for (var owner = implementation; owner && !descriptor; owner = owner.__proto__) descriptor = Object.getOwnPropertyDescriptor(owner, member); if (!descriptor) continue; if (typeof descriptor.value === "function") interface[member] = descriptor.value.bind(implementation); else if (typeof descriptor.get === "function") interface.__defineGetter__(member, descriptor.get.bind(implementation)); else Object.defineProperty(interface, member, descriptor); } } function declareInterfaceClass(implConstructor) { return function() { var impl = { __proto__: implConstructor.prototype }; implConstructor.apply(impl, arguments); populateInterfaceClass(this, impl); } } function defineDeprecatedProperty(object, className, oldName, newName) { var warningGiven = false; function getter() { if (!warningGiven) { console.warn(className + "." + oldName + " is deprecated. Use " + className + "." + newName + " instead"); warningGiven = true; } return object[newName]; } object.__defineGetter__(oldName, getter); } function extractCallbackArgument(args) { var lastArgument = args[args.length - 1]; return typeof lastArgument === "function" ? lastArgument : undefined; } var AuditCategory = declareInterfaceClass(AuditCategoryImpl); var AuditResult = declareInterfaceClass(AuditResultImpl); var Button = declareInterfaceClass(ButtonImpl); var EventSink = declareInterfaceClass(EventSinkImpl); var ExtensionPanel = declareInterfaceClass(ExtensionPanelImpl); var ExtensionSidebarPane = declareInterfaceClass(ExtensionSidebarPaneImpl); var PanelWithSidebar = declareInterfaceClass(PanelWithSidebarImpl); var Request = declareInterfaceClass(RequestImpl); var Resource = declareInterfaceClass(ResourceImpl); var Timeline = declareInterfaceClass(TimelineImpl); var extensionServer = new ExtensionServerClient(); return new InspectorExtensionAPI(); } function buildPlatformExtensionAPI(extensionInfo) { function platformExtensionAPI(coreAPI) { window.webInspector = coreAPI; } return platformExtensionAPI.toString(); } function buildExtensionAPIInjectedScript(extensionInfo) { return "(function(injectedScriptHost, inspectedWindow, injectedScriptId){ " + defineCommonExtensionSymbols.toString() + ";" + injectedExtensionAPI.toString() + ";" + buildPlatformExtensionAPI(extensionInfo) + ";" + "platformExtensionAPI(injectedExtensionAPI(injectedScriptId));" + "return {};" + "})"; } WebInspector.ExtensionAuditCategory = function(extensionOrigin, id, displayName, ruleCount) { this._extensionOrigin = extensionOrigin; this._id = id; this._displayName = displayName; this._ruleCount = ruleCount; } WebInspector.ExtensionAuditCategory.prototype = { get id() { return this._id; }, get displayName() { return this._displayName; }, run: function(requests, ruleResultCallback, categoryDoneCallback, progress) { var results = new WebInspector.ExtensionAuditCategoryResults(this, ruleResultCallback, categoryDoneCallback, progress); WebInspector.extensionServer.startAuditRun(this, results); } } WebInspector.ExtensionAuditCategoryResults = function(category, ruleResultCallback, categoryDoneCallback, progress) { this._category = category; this._ruleResultCallback = ruleResultCallback; this._categoryDoneCallback = categoryDoneCallback; this._progress = progress; this._progress.setTotalWork(1); this._expectedResults = category._ruleCount; this._actualResults = 0; this.id = category.id + "-" + ++WebInspector.ExtensionAuditCategoryResults._lastId; } WebInspector.ExtensionAuditCategoryResults.prototype = { done: function() { WebInspector.extensionServer.stopAuditRun(this); this._progress.done(); this._categoryDoneCallback(); }, addResult: function(displayName, description, severity, details) { var result = new WebInspector.AuditRuleResult(displayName); result.addChild(description); result.severity = severity; if (details) this._addNode(result, details); this._addResult(result); }, _addNode: function(parent, node) { var contents = WebInspector.auditFormatters.partiallyApply(WebInspector.ExtensionAuditFormatters, this, node.contents); var addedNode = parent.addChild(contents, node.expanded); if (node.children) { for (var i = 0; i < node.children.length; ++i) this._addNode(addedNode, node.children[i]); } }, _addResult: function(result) { this._ruleResultCallback(result); ++this._actualResults; if (typeof this._expectedResults === "number") { this._progress.setWorked(this._actualResults / this._expectedResults); if (this._actualResults === this._expectedResults) this.done(); } }, updateProgress: function(progress) { this._progress.setWorked(progress); }, evaluate: function(expression, evaluateOptions, callback) { function onEvaluate(error, result, wasThrown) { if (wasThrown) return; var object = WebInspector.RemoteObject.fromPayload(result); callback(object); } WebInspector.extensionServer.evaluate(expression, false, false, evaluateOptions, this._category._extensionOrigin, onEvaluate); } } WebInspector.ExtensionAuditFormatters = { object: function(expression, title, evaluateOptions) { var parentElement = document.createElement("div"); function onEvaluate(remoteObject) { var section = new WebInspector.ObjectPropertiesSection(remoteObject, title); section.expanded = true; section.editable = false; parentElement.appendChild(section.element); } this.evaluate(expression, evaluateOptions, onEvaluate); return parentElement; }, node: function(expression, evaluateOptions) { var parentElement = document.createElement("div"); function onNodeAvailable(nodeId) { if (!nodeId) return; var treeOutline = new WebInspector.ElementsTreeOutline(false, false, true); treeOutline.rootDOMNode = WebInspector.domAgent.nodeForId(nodeId); treeOutline.element.addStyleClass("outline-disclosure"); treeOutline.setVisible(true); parentElement.appendChild(treeOutline.element); } function onEvaluate(remoteObject) { remoteObject.pushNodeToFrontend(onNodeAvailable); } this.evaluate(expression, evaluateOptions, onEvaluate); return parentElement; } } WebInspector.ExtensionAuditCategoryResults._lastId = 0; WebInspector.ExtensionServer = function() { this._clientObjects = {}; this._handlers = {}; this._subscribers = {}; this._subscriptionStartHandlers = {}; this._subscriptionStopHandlers = {}; this._extraHeaders = {}; this._requests = {}; this._lastRequestId = 0; this._registeredExtensions = {}; this._status = new WebInspector.ExtensionStatus(); var commands = WebInspector.extensionAPI.Commands; this._registerHandler(commands.AddAuditCategory, this._onAddAuditCategory.bind(this)); this._registerHandler(commands.AddAuditResult, this._onAddAuditResult.bind(this)); this._registerHandler(commands.AddConsoleMessage, this._onAddConsoleMessage.bind(this)); this._registerHandler(commands.AddRequestHeaders, this._onAddRequestHeaders.bind(this)); this._registerHandler(commands.CreatePanel, this._onCreatePanel.bind(this)); this._registerHandler(commands.CreateSidebarPane, this._onCreateSidebarPane.bind(this)); this._registerHandler(commands.CreateStatusBarButton, this._onCreateStatusBarButton.bind(this)); this._registerHandler(commands.EvaluateOnInspectedPage, this._onEvaluateOnInspectedPage.bind(this)); this._registerHandler(commands.GetHAR, this._onGetHAR.bind(this)); this._registerHandler(commands.GetConsoleMessages, this._onGetConsoleMessages.bind(this)); this._registerHandler(commands.GetPageResources, this._onGetPageResources.bind(this)); this._registerHandler(commands.GetRequestContent, this._onGetRequestContent.bind(this)); this._registerHandler(commands.GetResourceContent, this._onGetResourceContent.bind(this)); this._registerHandler(commands.Log, this._onLog.bind(this)); this._registerHandler(commands.Reload, this._onReload.bind(this)); this._registerHandler(commands.SetOpenResourceHandler, this._onSetOpenResourceHandler.bind(this)); this._registerHandler(commands.SetResourceContent, this._onSetResourceContent.bind(this)); this._registerHandler(commands.SetSidebarHeight, this._onSetSidebarHeight.bind(this)); this._registerHandler(commands.SetSidebarContent, this._onSetSidebarContent.bind(this)); this._registerHandler(commands.SetSidebarPage, this._onSetSidebarPage.bind(this)); this._registerHandler(commands.ShowPanel, this._onShowPanel.bind(this)); this._registerHandler(commands.StopAuditCategoryRun, this._onStopAuditCategoryRun.bind(this)); this._registerHandler(commands.Subscribe, this._onSubscribe.bind(this)); this._registerHandler(commands.Unsubscribe, this._onUnsubscribe.bind(this)); this._registerHandler(commands.UpdateButton, this._onUpdateButton.bind(this)); this._registerHandler(commands.UpdateAuditProgress, this._onUpdateAuditProgress.bind(this)); window.addEventListener("message", this._onWindowMessage.bind(this), false); } WebInspector.ExtensionServer.prototype = { hasExtensions: function() { return !!Object.keys(this._registeredExtensions).length; }, notifySearchAction: function(panelId, action, searchString) { this._postNotification(WebInspector.extensionAPI.Events.PanelSearch + panelId, action, searchString); }, notifyViewShown: function(identifier, frameIndex) { this._postNotification(WebInspector.extensionAPI.Events.ViewShown + identifier, frameIndex); }, notifyViewHidden: function(identifier) { this._postNotification(WebInspector.extensionAPI.Events.ViewHidden + identifier); }, notifyButtonClicked: function(identifier) { this._postNotification(WebInspector.extensionAPI.Events.ButtonClicked + identifier); }, _inspectedURLChanged: function(event) { this._requests = {}; var url = event.data; this._postNotification(WebInspector.extensionAPI.Events.InspectedURLChanged, url); }, _mainFrameNavigated: function(event) { this._postNotification(WebInspector.extensionAPI.Events.Reset); }, startAuditRun: function(category, auditRun) { this._clientObjects[auditRun.id] = auditRun; this._postNotification("audit-started-" + category.id, auditRun.id); }, stopAuditRun: function(auditRun) { delete this._clientObjects[auditRun.id]; }, _postNotification: function(type, vararg) { var subscribers = this._subscribers[type]; if (!subscribers) return; var message = { command: "notify-" + type, arguments: Array.prototype.slice.call(arguments, 1) }; for (var i = 0; i < subscribers.length; ++i) subscribers[i].postMessage(message); }, _onSubscribe: function(message, port) { var subscribers = this._subscribers[message.type]; if (subscribers) subscribers.push(port); else { this._subscribers[message.type] = [ port ]; if (this._subscriptionStartHandlers[message.type]) this._subscriptionStartHandlers[message.type](); } }, _onUnsubscribe: function(message, port) { var subscribers = this._subscribers[message.type]; if (!subscribers) return; subscribers.remove(port); if (!subscribers.length) { delete this._subscribers[message.type]; if (this._subscriptionStopHandlers[message.type]) this._subscriptionStopHandlers[message.type](); } }, _onAddRequestHeaders: function(message) { var id = message.extensionId; if (typeof id !== "string") return this._status.E_BADARGTYPE("extensionId", typeof id, "string"); var extensionHeaders = this._extraHeaders[id]; if (!extensionHeaders) { extensionHeaders = {}; this._extraHeaders[id] = extensionHeaders; } for (var name in message.headers) extensionHeaders[name] = message.headers[name]; var allHeaders = ({}); for (var extension in this._extraHeaders) { var headers = this._extraHeaders[extension]; for (name in headers) { if (typeof headers[name] === "string") allHeaders[name] = headers[name]; } } NetworkAgent.setExtraHTTPHeaders(allHeaders); }, _onCreatePanel: function(message, port) { var id = message.id; if (id in this._clientObjects || id in WebInspector.panels) return this._status.E_EXISTS(id); var page = this._expandResourcePath(port._extensionOrigin, message.page); var panelDescriptor = new WebInspector.PanelDescriptor(id, message.title, undefined, undefined, new WebInspector.ExtensionPanel(id, page)); panelDescriptor.setIconURL(this._expandResourcePath(port._extensionOrigin, message.icon)); this._clientObjects[id] = panelDescriptor.panel(); WebInspector.inspectorView.addPanel(panelDescriptor); return this._status.OK(); }, _onShowPanel: function(message) { WebInspector.showPanel(message.id); }, _onCreateStatusBarButton: function(message, port) { var panel = this._clientObjects[message.panel]; if (!panel || !(panel instanceof WebInspector.ExtensionPanel)) return this._status.E_NOTFOUND(message.panel); var button = new WebInspector.ExtensionButton(message.id, this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled); this._clientObjects[message.id] = button; panel.addStatusBarItem(button.element); return this._status.OK(); }, _onUpdateButton: function(message, port) { var button = this._clientObjects[message.id]; if (!button || !(button instanceof WebInspector.ExtensionButton)) return this._status.E_NOTFOUND(message.id); button.update(this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled); return this._status.OK(); }, _onCreateSidebarPane: function(message) { var panel = WebInspector.panel(message.panel); if (!panel) return this._status.E_NOTFOUND(message.panel); if (!panel.sidebarElement || !panel.sidebarPanes) return this._status.E_NOTSUPPORTED(); var id = message.id; var sidebar = new WebInspector.ExtensionSidebarPane(message.title, message.id); this._clientObjects[id] = sidebar; panel.sidebarPanes[id] = sidebar; panel.sidebarElement.appendChild(sidebar.element); return this._status.OK(); }, _onSetSidebarHeight: function(message) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); sidebar.setHeight(message.height); return this._status.OK(); }, _onSetSidebarContent: function(message, port) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); function callback(error) { var result = error ? this._status.E_FAILED(error) : this._status.OK(); this._dispatchCallback(message.requestId, port, result); } if (message.evaluateOnPage) return sidebar.setExpression(message.expression, message.rootTitle, message.evaluateOptions, port._extensionOrigin, callback.bind(this)); sidebar.setObject(message.expression, message.rootTitle, callback.bind(this)); }, _onSetSidebarPage: function(message, port) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); sidebar.setPage(this._expandResourcePath(port._extensionOrigin, message.page)); }, _onSetOpenResourceHandler: function(message, port) { var name = this._registeredExtensions[port._extensionOrigin].name || ("Extension " + port._extensionOrigin); if (message.handlerPresent) WebInspector.openAnchorLocationRegistry.registerHandler(name, this._handleOpenURL.bind(this, port)); else WebInspector.openAnchorLocationRegistry.unregisterHandler(name); }, _handleOpenURL: function(port, details) { var url = (details.url); var contentProvider = WebInspector.workspace.uiSourceCodeForURL(url) || WebInspector.resourceForURL(url); if (!contentProvider) return false; var lineNumber = details.lineNumber; if (typeof lineNumber === "number") lineNumber += 1; port.postMessage({ command: "open-resource", resource: this._makeResource(contentProvider), lineNumber: lineNumber }); return true; }, _onLog: function(message) { WebInspector.log(message.message); }, _onReload: function(message) { var options = (message.options || {}); NetworkAgent.setUserAgentOverride(typeof options.userAgent === "string" ? options.userAgent : ""); var injectedScript; if (options.injectedScript) { injectedScript = "((function(){" + options.injectedScript + "})(),function(){return {}})"; } PageAgent.reload(!!options.ignoreCache, injectedScript); return this._status.OK(); }, _onEvaluateOnInspectedPage: function(message, port) { function callback(error, resultPayload, wasThrown) { var result = {}; if (error) { result.isException = true; result.value = error.toString(); } else result.value = resultPayload.value; if (wasThrown) result.isException = true; this._dispatchCallback(message.requestId, port, result); } return this.evaluate(message.expression, true, true, message.evaluateOptions, port._extensionOrigin, callback.bind(this)); }, _onGetConsoleMessages: function() { return WebInspector.console.messages.map(this._makeConsoleMessage); }, _onAddConsoleMessage: function(message) { function convertSeverity(level) { switch (level) { case WebInspector.extensionAPI.console.Severity.Tip: return WebInspector.ConsoleMessage.MessageLevel.Tip; case WebInspector.extensionAPI.console.Severity.Log: return WebInspector.ConsoleMessage.MessageLevel.Log; case WebInspector.extensionAPI.console.Severity.Warning: return WebInspector.ConsoleMessage.MessageLevel.Warning; case WebInspector.extensionAPI.console.Severity.Error: return WebInspector.ConsoleMessage.MessageLevel.Error; case WebInspector.extensionAPI.console.Severity.Debug: return WebInspector.ConsoleMessage.MessageLevel.Debug; } } var level = convertSeverity(message.severity); if (!level) return this._status.E_BADARG("message.severity", message.severity); var consoleMessage = WebInspector.ConsoleMessage.create( WebInspector.ConsoleMessage.MessageSource.JS, level, message.text, WebInspector.ConsoleMessage.MessageType.Log, message.url, message.line); WebInspector.console.addMessage(consoleMessage); }, _makeConsoleMessage: function(message) { function convertLevel(level) { if (!level) return; switch (level) { case WebInspector.ConsoleMessage.MessageLevel.Tip: return WebInspector.extensionAPI.console.Severity.Tip; case WebInspector.ConsoleMessage.MessageLevel.Log: return WebInspector.extensionAPI.console.Severity.Log; case WebInspector.ConsoleMessage.MessageLevel.Warning: return WebInspector.extensionAPI.console.Severity.Warning; case WebInspector.ConsoleMessage.MessageLevel.Error: return WebInspector.extensionAPI.console.Severity.Error; case WebInspector.ConsoleMessage.MessageLevel.Debug: return WebInspector.extensionAPI.console.Severity.Debug; default: return WebInspector.extensionAPI.console.Severity.Log; } } var result = { severity: convertLevel(message.level), text: message.text, }; if (message.url) result.url = message.url; if (message.line) result.line = message.line; return result; }, _onGetHAR: function() { var requests = WebInspector.networkLog.requests; var harLog = (new WebInspector.HARLog(requests)).build(); for (var i = 0; i < harLog.entries.length; ++i) harLog.entries[i]._requestId = this._requestId(requests[i]); return harLog; }, _makeResource: function(contentProvider) { return { url: contentProvider.contentURL(), type: contentProvider.contentType().name() }; }, _onGetPageResources: function() { var resources = {}; function pushResourceData(contentProvider) { if (!resources[contentProvider.contentURL()]) resources[contentProvider.contentURL()] = this._makeResource(contentProvider); } WebInspector.workspace.uiSourceCodes().forEach(pushResourceData.bind(this)); WebInspector.resourceTreeModel.forAllResources(pushResourceData.bind(this)); return Object.values(resources); }, _getResourceContent: function(contentProvider, message, port) { function onContentAvailable(content, contentEncoded, mimeType) { var response = { encoding: contentEncoded ? "base64" : "", content: content }; this._dispatchCallback(message.requestId, port, response); } contentProvider.requestContent(onContentAvailable.bind(this)); }, _onGetRequestContent: function(message, port) { var request = this._requestById(message.id); if (!request) return this._status.E_NOTFOUND(message.id); this._getResourceContent(request, message, port); }, _onGetResourceContent: function(message, port) { var url = (message.url); var contentProvider = WebInspector.workspace.uiSourceCodeForURL(url) || WebInspector.resourceForURL(url); if (!contentProvider) return this._status.E_NOTFOUND(url); this._getResourceContent(contentProvider, message, port); }, _onSetResourceContent: function(message, port) { function callbackWrapper(error) { var response = error ? this._status.E_FAILED(error) : this._status.OK(); this._dispatchCallback(message.requestId, port, response); } var url = (message.url); var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(url); if (!uiSourceCode) { var resource = WebInspector.resourceTreeModel.resourceForURL(url); if (!resource) return this._status.E_NOTFOUND(url); return this._status.E_NOTSUPPORTED("Resource is not editable") } uiSourceCode.setWorkingCopy(message.content); if (message.commit) uiSourceCode.commitWorkingCopy(callbackWrapper.bind(this)); else callbackWrapper.call(this, null); }, _requestId: function(request) { if (!request._extensionRequestId) { request._extensionRequestId = ++this._lastRequestId; this._requests[request._extensionRequestId] = request; } return request._extensionRequestId; }, _requestById: function(id) { return this._requests[id]; }, _onAddAuditCategory: function(message, port) { var category = new WebInspector.ExtensionAuditCategory(port._extensionOrigin, message.id, message.displayName, message.resultCount); if (WebInspector.panel("audits").getCategory(category.id)) return this._status.E_EXISTS(category.id); this._clientObjects[message.id] = category; WebInspector.panel("audits").addCategory(category); }, _onAddAuditResult: function(message) { var auditResult = this._clientObjects[message.resultId]; if (!auditResult) return this._status.E_NOTFOUND(message.resultId); try { auditResult.addResult(message.displayName, message.description, message.severity, message.details); } catch (e) { return e; } return this._status.OK(); }, _onUpdateAuditProgress: function(message) { var auditResult = this._clientObjects[message.resultId]; if (!auditResult) return this._status.E_NOTFOUND(message.resultId); auditResult.updateProgress(Math.min(Math.max(0, message.progress), 1)); }, _onStopAuditCategoryRun: function(message) { var auditRun = this._clientObjects[message.resultId]; if (!auditRun) return this._status.E_NOTFOUND(message.resultId); auditRun.done(); }, _dispatchCallback: function(requestId, port, result) { if (requestId) port.postMessage({ command: "callback", requestId: requestId, result: result }); }, initExtensions: function() { this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ConsoleMessageAdded, WebInspector.console, WebInspector.ConsoleModel.Events.MessageAdded, this._notifyConsoleMessageAdded); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.NetworkRequestFinished, WebInspector.networkManager, WebInspector.NetworkManager.EventTypes.RequestFinished, this._notifyRequestFinished); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ResourceAdded, WebInspector.workspace, WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._notifyResourceAdded); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ElementsPanelObjectSelected, WebInspector.notifications, WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._notifyElementsSelectionChanged); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ResourceContentCommitted, WebInspector.workspace, WebInspector.Workspace.Events.UISourceCodeContentCommitted, this._notifyUISourceCodeContentCommitted); function onTimelineSubscriptionStarted() { WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, this._notifyTimelineEventRecorded, this); WebInspector.timelineManager.start(); } function onTimelineSubscriptionStopped() { WebInspector.timelineManager.stop(); WebInspector.timelineManager.removeEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, this._notifyTimelineEventRecorded, this); } this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.TimelineEventRecorded, onTimelineSubscriptionStarted.bind(this), onTimelineSubscriptionStopped.bind(this)); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._inspectedURLChanged, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this); this._initDone = true; if (this._pendingExtensions) { this._pendingExtensions.forEach(this._innerAddExtension, this); delete this._pendingExtensions; } InspectorExtensionRegistry.getExtensionsAsync(); }, _notifyConsoleMessageAdded: function(event) { this._postNotification(WebInspector.extensionAPI.Events.ConsoleMessageAdded, this._makeConsoleMessage(event.data)); }, _notifyResourceAdded: function(event) { var uiSourceCode = (event.data); this._postNotification(WebInspector.extensionAPI.Events.ResourceAdded, this._makeResource(uiSourceCode)); }, _notifyUISourceCodeContentCommitted: function(event) { var uiSourceCode = (event.data.uiSourceCode); var content = (event.data.content); this._postNotification(WebInspector.extensionAPI.Events.ResourceContentCommitted, this._makeResource(uiSourceCode), content); }, _notifyRequestFinished: function(event) { var request = (event.data); this._postNotification(WebInspector.extensionAPI.Events.NetworkRequestFinished, this._requestId(request), (new WebInspector.HAREntry(request)).build()); }, _notifyElementsSelectionChanged: function() { this._postNotification(WebInspector.extensionAPI.Events.ElementsPanelObjectSelected); }, _notifyTimelineEventRecorded: function(event) { this._postNotification(WebInspector.extensionAPI.Events.TimelineEventRecorded, event.data); }, _addExtensions: function(extensions) { extensions.forEach(this._addExtension, this); }, _addExtension: function(extensionInfo) { if (this._initDone) { this._innerAddExtension(extensionInfo); return; } if (this._pendingExtensions) this._pendingExtensions.push(extensionInfo); else this._pendingExtensions = [extensionInfo]; }, _innerAddExtension: function(extensionInfo) { const urlOriginRegExp = new RegExp("([^:]+:\/\/[^/]*)\/"); var startPage = extensionInfo.startPage; var name = extensionInfo.name; try { var originMatch = urlOriginRegExp.exec(startPage); if (!originMatch) { console.error("Skipping extension with invalid URL: " + startPage); return false; } var extensionOrigin = originMatch[1]; if (!this._registeredExtensions[extensionOrigin]) { InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin, buildExtensionAPIInjectedScript(extensionInfo)); this._registeredExtensions[extensionOrigin] = { name: name }; } var iframe = document.createElement("iframe"); iframe.src = startPage; iframe.style.display = "none"; document.body.appendChild(iframe); } catch (e) { console.error("Failed to initialize extension " + startPage + ":" + e); return false; } return true; }, _onWindowMessage: function(event) { if (event.data === "registerExtension") this._registerExtension(event.origin, event.ports[0]); }, _registerExtension: function(origin, port) { if (!this._registeredExtensions.hasOwnProperty(origin)) { if (origin !== window.location.origin) console.error("Ignoring unauthorized client request from " + origin); return; } port._extensionOrigin = origin; port.addEventListener("message", this._onmessage.bind(this), false); port.start(); }, _onmessage: function(event) { var message = event.data; var result; if (message.command in this._handlers) result = this._handlers[message.command](message, event.target); else result = this._status.E_NOTSUPPORTED(message.command); if (result && message.requestId) this._dispatchCallback(message.requestId, event.target, result); }, _registerHandler: function(command, callback) { this._handlers[command] = callback; }, _registerSubscriptionHandler: function(eventTopic, onSubscribeFirst, onUnsubscribeLast) { this._subscriptionStartHandlers[eventTopic] = onSubscribeFirst; this._subscriptionStopHandlers[eventTopic] = onUnsubscribeLast; }, _registerAutosubscriptionHandler: function(eventTopic, eventTarget, frontendEventType, handler) { this._registerSubscriptionHandler(eventTopic, eventTarget.addEventListener.bind(eventTarget, frontendEventType, handler, this), eventTarget.removeEventListener.bind(eventTarget, frontendEventType, handler, this)); }, _expandResourcePath: function(extensionPath, resourcePath) { if (!resourcePath) return; return extensionPath + this._normalizePath(resourcePath); }, _normalizePath: function(path) { var source = path.split("/"); var result = []; for (var i = 0; i < source.length; ++i) { if (source[i] === ".") continue; if (source[i] === "") continue; if (source[i] === "..") result.pop(); else result.push(source[i]); } return "/" + result.join("/"); }, evaluate: function(expression, exposeCommandLineAPI, returnByValue, options, securityOrigin, callback) { var contextId; if (typeof options === "object" && options["useContentScriptContext"]) { var mainFrame = WebInspector.resourceTreeModel.mainFrame; if (!mainFrame) return this._status.E_FAILED("main frame not available yet"); var context = WebInspector.runtimeModel.contextByFrameAndSecurityOrigin(mainFrame, securityOrigin); if (!context) return this._status.E_NOTFOUND(securityOrigin); contextId = context.id; } RuntimeAgent.evaluate(expression, "extension", exposeCommandLineAPI, true, contextId, returnByValue, false, callback); } } WebInspector.ExtensionStatus = function() { function makeStatus(code, description) { var details = Array.prototype.slice.call(arguments, 2); var status = { code: code, description: description, details: details }; if (code !== "OK") { status.isError = true; console.log("Extension server error: " + String.vsprintf(description, details)); } return status; } this.OK = makeStatus.bind(null, "OK", "OK"); this.E_EXISTS = makeStatus.bind(null, "E_EXISTS", "Object already exists: %s"); this.E_BADARG = makeStatus.bind(null, "E_BADARG", "Invalid argument %s: %s"); this.E_BADARGTYPE = makeStatus.bind(null, "E_BADARGTYPE", "Invalid type for argument %s: got %s, expected %s"); this.E_NOTFOUND = makeStatus.bind(null, "E_NOTFOUND", "Object not found: %s"); this.E_NOTSUPPORTED = makeStatus.bind(null, "E_NOTSUPPORTED", "Object does not support requested operation: %s"); this.E_FAILED = makeStatus.bind(null, "E_FAILED", "Operation failed: %s"); } WebInspector.addExtensions = function(extensions) { WebInspector.extensionServer._addExtensions(extensions); } WebInspector.extensionAPI = {}; defineCommonExtensionSymbols(WebInspector.extensionAPI); WebInspector.extensionServer = new WebInspector.ExtensionServer(); window.addExtension = function(page, name) { WebInspector.extensionServer._addExtension({ startPage: page, name: name, }); } WebInspector.ExtensionView = function(id, src, className) { WebInspector.View.call(this); this.element.className = "fill"; this._id = id; this._iframe = document.createElement("iframe"); this._iframe.addEventListener("load", this._onLoad.bind(this), false); this._iframe.src = src; this._iframe.className = className; this.setDefaultFocusedElement(this._iframe); this.element.appendChild(this._iframe); } WebInspector.ExtensionView.prototype = { wasShown: function() { if (typeof this._frameIndex === "number") WebInspector.extensionServer.notifyViewShown(this._id, this._frameIndex); }, willHide: function() { if (typeof this._frameIndex === "number") WebInspector.extensionServer.notifyViewHidden(this._id); }, _onLoad: function() { this._frameIndex = Array.prototype.indexOf.call(window.frames, this._iframe.contentWindow); if (this.isShowing()) WebInspector.extensionServer.notifyViewShown(this._id, this._frameIndex); }, __proto__: WebInspector.View.prototype } WebInspector.ExtensionNotifierView = function(id) { WebInspector.View.call(this); this._id = id; } WebInspector.ExtensionNotifierView.prototype = { wasShown: function() { WebInspector.extensionServer.notifyViewShown(this._id); }, willHide: function() { WebInspector.extensionServer.notifyViewHidden(this._id); }, __proto__: WebInspector.View.prototype } WebInspector.ExtensionPanel = function(id, pageURL) { WebInspector.Panel.call(this, id); this.setHideOnDetach(); this._statusBarItems = []; var extensionView = new WebInspector.ExtensionView(id, pageURL, "extension panel"); extensionView.show(this.element); this.setDefaultFocusedElement(extensionView.defaultFocusedElement()); } WebInspector.ExtensionPanel.prototype = { defaultFocusedElement: function() { return WebInspector.View.prototype.defaultFocusedElement.call(this); }, get statusBarItems() { return this._statusBarItems; }, addStatusBarItem: function(element) { this._statusBarItems.push(element); }, searchCanceled: function(startingNewSearch) { WebInspector.extensionServer.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.CancelSearch); WebInspector.Panel.prototype.searchCanceled.apply(this, arguments); }, performSearch: function(query) { WebInspector.extensionServer.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.PerformSearch, query); WebInspector.Panel.prototype.performSearch.apply(this, arguments); }, jumpToNextSearchResult: function() { WebInspector.extensionServer.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.NextSearchResult); WebInspector.Panel.prototype.jumpToNextSearchResult.call(this); }, jumpToPreviousSearchResult: function() { WebInspector.extensionServer.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.PreviousSearchResult); WebInspector.Panel.prototype.jumpToPreviousSearchResult.call(this); }, __proto__: WebInspector.Panel.prototype } WebInspector.ExtensionButton = function(id, iconURL, tooltip, disabled) { this._id = id; this.element = document.createElement("button"); this.element.className = "status-bar-item extension"; this.element.addEventListener("click", this._onClicked.bind(this), false); this.update(iconURL, tooltip, disabled); } WebInspector.ExtensionButton.prototype = { update: function(iconURL, tooltip, disabled) { if (typeof iconURL === "string") this.element.style.backgroundImage = "url(" + iconURL + ")"; if (typeof tooltip === "string") this.element.title = tooltip; if (typeof disabled === "boolean") this.element.disabled = disabled; }, _onClicked: function() { WebInspector.extensionServer.notifyButtonClicked(this._id); } } WebInspector.ExtensionSidebarPane = function(title, id) { WebInspector.SidebarPane.call(this, title); this._id = id; } WebInspector.ExtensionSidebarPane.prototype = { setObject: function(object, title, callback) { this._createObjectPropertiesView(); this._setObject(WebInspector.RemoteObject.fromLocalObject(object), title, callback); }, setExpression: function(expression, title, evaluateOptions, securityOrigin, callback) { this._createObjectPropertiesView(); return WebInspector.extensionServer.evaluate(expression, true, false, evaluateOptions, securityOrigin, this._onEvaluate.bind(this, title, callback)); }, setPage: function(url) { if (this._objectPropertiesView) { this._objectPropertiesView.detach(); delete this._objectPropertiesView; } if (this._extensionView) this._extensionView.detach(true); this._extensionView = new WebInspector.ExtensionView(this._id, url, "extension fill"); this._extensionView.show(this.bodyElement); if (!this.bodyElement.style.height) this.setHeight("150px"); }, setHeight: function(height) { this.bodyElement.style.height = height; }, _onEvaluate: function(title, callback, error, result, wasThrown) { if (error) callback(error.toString()); else this._setObject(WebInspector.RemoteObject.fromPayload(result), title, callback); }, _createObjectPropertiesView: function() { if (this._objectPropertiesView) return; if (this._extensionView) { this._extensionView.detach(true); delete this._extensionView; } this._objectPropertiesView = new WebInspector.ExtensionNotifierView(this._id); this._objectPropertiesView.show(this.bodyElement); }, _setObject: function(object, title, callback) { if (!this._objectPropertiesView) { callback("operation cancelled"); return; } this._objectPropertiesView.element.removeChildren(); var section = new WebInspector.ObjectPropertiesSection(object, title); if (!title) section.headerElement.addStyleClass("hidden"); section.expanded = true; section.editable = false; this._objectPropertiesView.element.appendChild(section.element); callback(); }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.EmptyView = function(text) { WebInspector.View.call(this); this._text = text; } WebInspector.EmptyView.prototype = { wasShown: function() { this.element.className = "storage-empty-view"; this.element.textContent = this._text; }, set text(text) { this._text = text; if (this.isShowing()) this.element.textContent = this._text; }, __proto__: WebInspector.View.prototype } WebInspector.Formatter = function() { } WebInspector.Formatter.createFormatter = function(contentType) { if (contentType === WebInspector.resourceTypes.Script || contentType === WebInspector.resourceTypes.Document) return new WebInspector.ScriptFormatter(); return new WebInspector.IdentityFormatter(); } WebInspector.Formatter.locationToPosition = function(lineEndings, lineNumber, columnNumber) { var position = lineNumber ? lineEndings[lineNumber - 1] + 1 : 0; return position + columnNumber; } WebInspector.Formatter.positionToLocation = function(lineEndings, position) { var lineNumber = lineEndings.upperBound(position - 1); if (!lineNumber) var columnNumber = position; else var columnNumber = position - lineEndings[lineNumber - 1] - 1; return [lineNumber, columnNumber]; } WebInspector.Formatter.prototype = { formatContent: function(mimeType, content, callback) { } } WebInspector.ScriptFormatter = function() { this._tasks = []; } WebInspector.ScriptFormatter.prototype = { formatContent: function(mimeType, content, callback) { content = content.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''); const method = "format"; var parameters = { mimeType: mimeType, content: content, indentString: WebInspector.settings.textEditorIndent.get() }; this._tasks.push({ data: parameters, callback: callback }); this._worker.postMessage({ method: method, params: parameters }); }, _didFormatContent: function(event) { var task = this._tasks.shift(); var originalContent = task.data.content; var formattedContent = event.data.content; var mapping = event.data["mapping"]; var sourceMapping = new WebInspector.FormatterSourceMappingImpl(originalContent.lineEndings(), formattedContent.lineEndings(), mapping); task.callback(formattedContent, sourceMapping); }, get _worker() { if (!this._cachedWorker) { this._cachedWorker = new Worker("ScriptFormatterWorker.js"); this._cachedWorker.onmessage = (this._didFormatContent.bind(this)); } return this._cachedWorker; } } WebInspector.IdentityFormatter = function() { this._tasks = []; } WebInspector.IdentityFormatter.prototype = { formatContent: function(mimeType, content, callback) { callback(content, new WebInspector.IdentityFormatterSourceMapping()); } } WebInspector.FormatterMappingPayload = function() { this.original = []; this.formatted = []; } WebInspector.FormatterSourceMapping = function() { } WebInspector.FormatterSourceMapping.prototype = { originalToFormatted: function(lineNumber, columnNumber) { }, formattedToOriginal: function(lineNumber, columnNumber) { } } WebInspector.IdentityFormatterSourceMapping = function() { } WebInspector.IdentityFormatterSourceMapping.prototype = { originalToFormatted: function(lineNumber, columnNumber) { return [lineNumber, columnNumber || 0]; }, formattedToOriginal: function(lineNumber, columnNumber) { return [lineNumber, columnNumber || 0]; } } WebInspector.FormatterSourceMappingImpl = function(originalLineEndings, formattedLineEndings, mapping) { this._originalLineEndings = originalLineEndings; this._formattedLineEndings = formattedLineEndings; this._mapping = mapping; } WebInspector.FormatterSourceMappingImpl.prototype = { originalToFormatted: function(lineNumber, columnNumber) { var originalPosition = WebInspector.Formatter.locationToPosition(this._originalLineEndings, lineNumber, columnNumber || 0); var formattedPosition = this._convertPosition(this._mapping.original, this._mapping.formatted, originalPosition || 0); return WebInspector.Formatter.positionToLocation(this._formattedLineEndings, formattedPosition); }, formattedToOriginal: function(lineNumber, columnNumber) { var formattedPosition = WebInspector.Formatter.locationToPosition(this._formattedLineEndings, lineNumber, columnNumber || 0); var originalPosition = this._convertPosition(this._mapping.formatted, this._mapping.original, formattedPosition); return WebInspector.Formatter.positionToLocation(this._originalLineEndings, originalPosition || 0); }, _convertPosition: function(positions1, positions2, position) { var index = positions1.upperBound(position) - 1; var convertedPosition = positions2[index] + position - positions1[index]; if (index < positions2.length - 1 && convertedPosition > positions2[index + 1]) convertedPosition = positions2[index + 1]; return convertedPosition; } } WebInspector.DOMSyntaxHighlighter = function(mimeType, stripExtraWhitespace) { this._tokenizer = WebInspector.SourceTokenizer.Registry.getInstance().getTokenizer(mimeType); this._stripExtraWhitespace = stripExtraWhitespace; } WebInspector.DOMSyntaxHighlighter.prototype = { createSpan: function(content, className) { var span = document.createElement("span"); span.className = "webkit-" + className; if (this._stripExtraWhitespace) content = content.replace(/^[\n\r]*/, "").replace(/\s*$/, ""); span.appendChild(document.createTextNode(content)); return span; }, syntaxHighlightNode: function(node) { this._tokenizer.condition = this._tokenizer.createInitialCondition(); var lines = node.textContent.split("\n"); node.removeChildren(); for (var i = lines[0].length ? 0 : 1; i < lines.length; ++i) { var line = lines[i]; var plainTextStart = 0; this._tokenizer.line = line; var column = 0; do { var newColumn = this._tokenizer.nextToken(column); var tokenType = this._tokenizer.tokenType; if (tokenType) { if (column > plainTextStart) { var plainText = line.substring(plainTextStart, column); node.appendChild(document.createTextNode(plainText)); } var token = line.substring(column, newColumn); node.appendChild(this.createSpan(token, tokenType)); plainTextStart = newColumn; } column = newColumn; } while (column < line.length) if (plainTextStart < line.length) { var plainText = line.substring(plainTextStart, line.length); node.appendChild(document.createTextNode(plainText)); } if (i < lines.length - 1) node.appendChild(document.createElement("br")); } } } WebInspector.TextRange = function(startLine, startColumn, endLine, endColumn) { this.startLine = startLine; this.startColumn = startColumn; this.endLine = endLine; this.endColumn = endColumn; } WebInspector.TextRange.createFromLocation = function(line, column) { return new WebInspector.TextRange(line, column, line, column); } WebInspector.TextRange.fromObject = function (serializedTextRange) { return new WebInspector.TextRange(serializedTextRange.startLine, serializedTextRange.startColumn, serializedTextRange.endLine, serializedTextRange.endColumn); } WebInspector.TextRange.prototype = { isEmpty: function() { return this.startLine === this.endLine && this.startColumn === this.endColumn; }, get linesCount() { return this.endLine - this.startLine; }, collapseToEnd: function() { return new WebInspector.TextRange(this.endLine, this.endColumn, this.endLine, this.endColumn); }, normalize: function() { if (this.startLine > this.endLine || (this.startLine === this.endLine && this.startColumn > this.endColumn)) return new WebInspector.TextRange(this.endLine, this.endColumn, this.startLine, this.startColumn); else return this.clone(); }, clone: function() { return new WebInspector.TextRange(this.startLine, this.startColumn, this.endLine, this.endColumn); }, serializeToObject: function() { var serializedTextRange = {}; serializedTextRange.startLine = this.startLine; serializedTextRange.startColumn = this.startColumn; serializedTextRange.endLine = this.endLine; serializedTextRange.endColumn = this.endColumn; return serializedTextRange; }, compareTo: function(other) { if (this.startLine > other.startLine) return 1; if (this.startLine < other.startLine) return -1; if (this.startColumn > other.startColumn) return 1; if (this.startColumn < other.startColumn) return -1; return 0; }, shift: function(lineOffset) { return new WebInspector.TextRange(this.startLine + lineOffset, this.startColumn, this.endLine + lineOffset, this.endColumn); }, toString: function() { return JSON.stringify(this); } } WebInspector.TextEditorCommand = function(newRange, originalText) { this.newRange = newRange; this.originalText = originalText; } WebInspector.TextEditorModel = function() { this._lines = [""]; this._attributes = []; this._undoStack = []; this._noPunctuationRegex = /[^ !%&()*+,-.:;<=>?\[\]\^{|}~]+/; this._lineBreak = "\n"; } WebInspector.TextEditorModel.Indent = { TwoSpaces: " ", FourSpaces: " ", EightSpaces: " ", TabCharacter: "\t" } WebInspector.TextEditorModel.Events = { TextChanged: "TextChanged" } WebInspector.TextEditorModel.endsWithBracketRegex = /[{(\[]\s*$/; WebInspector.TextEditorModel.prototype = { get linesCount() { return this._lines.length; }, text: function() { return this._lines.join(this._lineBreak); }, range: function() { return new WebInspector.TextRange(0, 0, this._lines.length - 1, this._lines[this._lines.length - 1].length); }, get lineBreak() { return this._lineBreak; }, line: function(lineNumber) { if (lineNumber >= this._lines.length) throw "Out of bounds:" + lineNumber; return this._lines[lineNumber]; }, lineLength: function(lineNumber) { return this._lines[lineNumber].length; }, setText: function(text) { this._resetUndoStack(); text = text || ""; var range = this.range(); this._lineBreak = /\r\n/.test(text) ? "\r\n" : "\n"; var newRange = this._innerSetText(range, text); this.dispatchEventToListeners(WebInspector.TextEditorModel.Events.TextChanged, { oldRange: range, newRange: newRange}); }, editRange: function(range, text) { if (this._lastEditedRange && (!text || text.indexOf("\n") !== -1 || this._lastEditedRange.endLine !== range.startLine || this._lastEditedRange.endColumn !== range.startColumn)) this._markUndoableState(); return this._innerEditRange(range, text); }, _innerEditRange: function(range, text) { var originalText = this.copyRange(range); this._lastEditedRange = range; var newRange = range; if (text !== originalText) { newRange = this._innerSetText(range, text); this._pushUndoableCommand(newRange, originalText); } this.dispatchEventToListeners(WebInspector.TextEditorModel.Events.TextChanged, { oldRange: range, newRange: newRange, editRange: true }); return newRange; }, _innerSetText: function(range, text) { this._eraseRange(range); if (text === "") return new WebInspector.TextRange(range.startLine, range.startColumn, range.startLine, range.startColumn); var newLines = text.split(/\r?\n/); var prefix = this._lines[range.startLine].substring(0, range.startColumn); var suffix = this._lines[range.startLine].substring(range.startColumn); var postCaret = prefix.length; if (newLines.length === 1) { this._setLine(range.startLine, prefix + newLines[0] + suffix); postCaret += newLines[0].length; } else { this._setLine(range.startLine, prefix + newLines[0]); this._insertLines(range, newLines); this._setLine(range.startLine + newLines.length - 1, newLines[newLines.length - 1] + suffix); postCaret = newLines[newLines.length - 1].length; } return new WebInspector.TextRange(range.startLine, range.startColumn, range.startLine + newLines.length - 1, postCaret); }, _insertLines: function(range, newLines) { var lines = new Array(this._lines.length + newLines.length - 1); for (var i = 0; i <= range.startLine; ++i) lines[i] = this._lines[i]; for (var i = 1; i < newLines.length; ++i) lines[range.startLine + i] = newLines[i]; for (var i = range.startLine + newLines.length; i < lines.length; ++i) lines[i] = this._lines[i - newLines.length + 1]; this._lines = lines; var attributes = new Array(lines.length); var insertionIndex = range.startColumn ? range.startLine + 1 : range.startLine; for (var i = 0; i < insertionIndex; ++i) attributes[i] = this._attributes[i]; for (var i = insertionIndex + newLines.length - 1; i < attributes.length; ++i) attributes[i] = this._attributes[i - newLines.length + 1]; this._attributes = attributes; }, _eraseRange: function(range) { if (range.isEmpty()) return; var prefix = this._lines[range.startLine].substring(0, range.startColumn); var suffix = this._lines[range.endLine].substring(range.endColumn); if (range.endLine > range.startLine) { this._lines.splice(range.startLine + 1, range.endLine - range.startLine); this._attributes.splice(range.startColumn ? range.startLine + 1 : range.startLine, range.endLine - range.startLine); } this._setLine(range.startLine, prefix + suffix); }, _setLine: function(lineNumber, text) { this._lines[lineNumber] = text; }, wordRange: function(lineNumber, column) { return new WebInspector.TextRange(lineNumber, this.wordStart(lineNumber, column, true), lineNumber, this.wordEnd(lineNumber, column, true)); }, wordStart: function(lineNumber, column, gapless) { var line = this._lines[lineNumber]; var prefix = line.substring(0, column).split("").reverse().join(""); var prefixMatch = this._noPunctuationRegex.exec(prefix); return prefixMatch && (!gapless || prefixMatch.index === 0) ? column - prefixMatch.index - prefixMatch[0].length : column; }, wordEnd: function(lineNumber, column, gapless) { var line = this._lines[lineNumber]; var suffix = line.substring(column); var suffixMatch = this._noPunctuationRegex.exec(suffix); return suffixMatch && (!gapless || suffixMatch.index === 0) ? column + suffixMatch.index + suffixMatch[0].length : column; }, copyRange: function(range) { if (!range) range = this.range(); var clip = []; if (range.startLine === range.endLine) { clip.push(this._lines[range.startLine].substring(range.startColumn, range.endColumn)); return clip.join(this._lineBreak); } clip.push(this._lines[range.startLine].substring(range.startColumn)); for (var i = range.startLine + 1; i < range.endLine; ++i) clip.push(this._lines[i]); clip.push(this._lines[range.endLine].substring(0, range.endColumn)); return clip.join(this._lineBreak); }, setAttribute: function(line, name, value) { var attrs = this._attributes[line]; if (!attrs) { attrs = {}; this._attributes[line] = attrs; } attrs[name] = value; }, getAttribute: function(line, name) { var attrs = this._attributes[line]; return attrs ? attrs[name] : null; }, removeAttribute: function(line, name) { var attrs = this._attributes[line]; if (attrs) delete attrs[name]; }, _pushUndoableCommand: function(newRange, originalText) { var command = new WebInspector.TextEditorCommand(newRange.clone(), originalText); if (this._inUndo) this._redoStack.push(command); else { if (!this._inRedo) this._redoStack = []; this._undoStack.push(command); } return command; }, undo: function() { if (!this._undoStack.length) return null; this._markRedoableState(); this._inUndo = true; var range = this._doUndo(this._undoStack); delete this._inUndo; return range; }, redo: function() { if (!this._redoStack || !this._redoStack.length) return null; this._markUndoableState(); this._inRedo = true; var range = this._doUndo(this._redoStack); delete this._inRedo; return range; }, _doUndo: function(stack) { var range = null; for (var i = stack.length - 1; i >= 0; --i) { var command = stack[i]; stack.length = i; range = this._innerEditRange(command.newRange, command.originalText); if (i > 0 && stack[i - 1].explicit) return range; } return range; }, _markUndoableState: function() { if (this._undoStack.length) this._undoStack[this._undoStack.length - 1].explicit = true; }, _markRedoableState: function() { if (this._redoStack.length) this._redoStack[this._redoStack.length - 1].explicit = true; }, _resetUndoStack: function() { this._undoStack = []; }, indentLines: function(range) { this._markUndoableState(); var indent = WebInspector.settings.textEditorIndent.get(); var newRange = range.clone(); if (range.startColumn) newRange.startColumn += indent.length; var indentEndLine = range.endLine; if (range.endColumn) newRange.endColumn += indent.length; else indentEndLine--; for (var lineNumber = range.startLine; lineNumber <= indentEndLine; lineNumber++) this._innerEditRange(WebInspector.TextRange.createFromLocation(lineNumber, 0), indent); return newRange; }, unindentLines: function(range) { this._markUndoableState(); var indent = WebInspector.settings.textEditorIndent.get(); var indentLength = indent === WebInspector.TextEditorModel.Indent.TabCharacter ? 4 : indent.length; var lineIndentRegex = new RegExp("^ {1," + indentLength + "}"); var newRange = range.clone(); var indentEndLine = range.endLine; if (!range.endColumn) indentEndLine--; for (var lineNumber = range.startLine; lineNumber <= indentEndLine; lineNumber++) { var line = this.line(lineNumber); var firstCharacter = line.charAt(0); var lineIndentLength; if (firstCharacter === " ") lineIndentLength = line.match(lineIndentRegex)[0].length; else if (firstCharacter === "\t") lineIndentLength = 1; else continue; this._innerEditRange(new WebInspector.TextRange(lineNumber, 0, lineNumber, lineIndentLength), ""); if (lineNumber === range.startLine) newRange.startColumn = Math.max(0, newRange.startColumn - lineIndentLength); if (lineNumber === range.endLine) newRange.endColumn = Math.max(0, newRange.endColumn - lineIndentLength); } return newRange; }, slice: function(from, to) { var textModel = new WebInspector.TextEditorModel(); textModel._lines = this._lines.slice(from, to); textModel._lineBreak = this._lineBreak; return textModel; }, growRangeLeft: function(range) { var result = range.clone(); if (result.startColumn) --result.startColumn; else if (result.startLine) result.startColumn = this.lineLength(--result.startLine); return result; }, growRangeRight: function(range) { var result = range.clone(); if (result.endColumn < this.lineLength(result.endLine)) ++result.endColumn; else if (result.endLine < this.linesCount) { result.endColumn = 0; ++result.endLine; } return result; }, __proto__: WebInspector.Object.prototype } WebInspector.TextEditorHighlighter = function(textModel, damageCallback) { this._textModel = textModel; this._tokenizer = WebInspector.SourceTokenizer.Registry.getInstance().getTokenizer("text/html"); this._damageCallback = damageCallback; this._highlightChunkLimit = 1000; } WebInspector.TextEditorHighlighter._MaxLineCount = 10000; WebInspector.TextEditorHighlighter.prototype = { set mimeType(mimeType) { var tokenizer = WebInspector.SourceTokenizer.Registry.getInstance().getTokenizer(mimeType); if (tokenizer) this._tokenizer = tokenizer; }, set highlightChunkLimit(highlightChunkLimit) { this._highlightChunkLimit = highlightChunkLimit; }, highlight: function(endLine, forceRun) { if (this._textModel.linesCount > WebInspector.TextEditorHighlighter._MaxLineCount) return; var state = this._textModel.getAttribute(endLine - 1, "highlight"); if (state && state.postConditionStringified) { return; } this._requestedEndLine = endLine; if (this._highlightTimer && !forceRun) { return; } var startLine = endLine; while (startLine > 0) { state = this._textModel.getAttribute(startLine - 1, "highlight"); if (state && state.postConditionStringified) break; startLine--; } this._highlightInChunks(startLine, endLine); }, updateHighlight: function(startLine, endLine) { if (this._textModel.linesCount > WebInspector.TextEditorHighlighter._MaxLineCount) return; this._clearHighlightState(startLine); if (startLine) { var state = this._textModel.getAttribute(startLine - 1, "highlight"); if (!state || !state.postConditionStringified) { return false; } } var restored = this._highlightLines(startLine, endLine); if (!restored) { for (var i = this._lastHighlightedLine; i < this._textModel.linesCount; ++i) { var state = this._textModel.getAttribute(i, "highlight"); if (!state && i > endLine) break; this._textModel.setAttribute(i, "highlight-outdated", state); this._textModel.removeAttribute(i, "highlight"); } if (this._highlightTimer) { clearTimeout(this._highlightTimer); this._requestedEndLine = endLine; this._highlightTimer = setTimeout(this._highlightInChunks.bind(this, this._lastHighlightedLine, this._requestedEndLine), 10); } } return restored; }, _highlightInChunks: function(startLine, endLine) { delete this._highlightTimer; var state = this._textModel.getAttribute(this._requestedEndLine - 1, "highlight"); if (state && state.postConditionStringified) return; if (this._requestedEndLine !== endLine) { this._highlightTimer = setTimeout(this._highlightInChunks.bind(this, startLine, this._requestedEndLine), 100); return; } if (this._requestedEndLine > this._textModel.linesCount) this._requestedEndLine = this._textModel.linesCount; this._highlightLines(startLine, this._requestedEndLine); if (this._lastHighlightedLine < this._requestedEndLine) this._highlightTimer = setTimeout(this._highlightInChunks.bind(this, this._lastHighlightedLine, this._requestedEndLine), 10); }, _highlightLines: function(startLine, endLine) { var state = this._textModel.getAttribute(startLine - 1, "highlight"); var postConditionStringified = state ? state.postConditionStringified : JSON.stringify(this._tokenizer.createInitialCondition()); var tokensCount = 0; for (var lineNumber = startLine; lineNumber < endLine; ++lineNumber) { state = this._selectHighlightState(lineNumber, postConditionStringified); if (state.postConditionStringified) { postConditionStringified = state.postConditionStringified; } else { var lastHighlightedColumn = 0; if (state.midConditionStringified) { lastHighlightedColumn = state.lastHighlightedColumn; postConditionStringified = state.midConditionStringified; } var line = this._textModel.line(lineNumber); this._tokenizer.line = line; this._tokenizer.condition = JSON.parse(postConditionStringified); do { var newColumn = this._tokenizer.nextToken(lastHighlightedColumn); var tokenType = this._tokenizer.tokenType; if (tokenType) state[lastHighlightedColumn] = { length: newColumn - lastHighlightedColumn, tokenType: tokenType }; lastHighlightedColumn = newColumn; if (++tokensCount > this._highlightChunkLimit) break; } while (lastHighlightedColumn < line.length); postConditionStringified = JSON.stringify(this._tokenizer.condition); if (lastHighlightedColumn < line.length) { state.lastHighlightedColumn = lastHighlightedColumn; state.midConditionStringified = postConditionStringified; break; } else { delete state.lastHighlightedColumn; delete state.midConditionStringified; state.postConditionStringified = postConditionStringified; } } var nextLineState = this._textModel.getAttribute(lineNumber + 1, "highlight"); if (nextLineState && nextLineState.preConditionStringified === state.postConditionStringified) { ++lineNumber; this._damageCallback(startLine, lineNumber); for (; lineNumber < endLine; ++lineNumber) { state = this._textModel.getAttribute(lineNumber, "highlight"); if (!state || !state.postConditionStringified) break; } this._lastHighlightedLine = lineNumber; return true; } } this._damageCallback(startLine, lineNumber); this._lastHighlightedLine = lineNumber; return false; }, _selectHighlightState: function(lineNumber, preConditionStringified) { var state = this._textModel.getAttribute(lineNumber, "highlight"); if (state && state.preConditionStringified === preConditionStringified) return state; var outdatedState = this._textModel.getAttribute(lineNumber, "highlight-outdated"); if (outdatedState && outdatedState.preConditionStringified === preConditionStringified) { this._textModel.setAttribute(lineNumber, "highlight", outdatedState); this._textModel.setAttribute(lineNumber, "highlight-outdated", state); return outdatedState; } if (state) this._textModel.setAttribute(lineNumber, "highlight-outdated", state); state = {}; state.preConditionStringified = preConditionStringified; this._textModel.setAttribute(lineNumber, "highlight", state); return state; }, _clearHighlightState: function(lineNumber) { this._textModel.removeAttribute(lineNumber, "highlight"); this._textModel.removeAttribute(lineNumber, "highlight-outdated"); } } WebInspector.SourceTokenizer = function() { } WebInspector.SourceTokenizer.prototype = { set line(line) { this._line = line; }, set condition(condition) { this._condition = condition; }, get condition() { return this._condition; }, getLexCondition: function() { return this.condition.lexCondition; }, setLexCondition: function(lexCondition) { this.condition.lexCondition = lexCondition; }, _charAt: function(cursor) { return cursor < this._line.length ? this._line.charAt(cursor) : "\n"; }, createInitialCondition: function() { }, nextToken: function(cursor) { } } WebInspector.SourceTokenizer.Registry = function() { this._tokenizers = {}; this._tokenizerConstructors = { "text/css": "SourceCSSTokenizer", "text/html": "SourceHTMLTokenizer", "text/javascript": "SourceJavaScriptTokenizer", "text/x-scss": "SourceCSSTokenizer" }; } WebInspector.SourceTokenizer.Registry.getInstance = function() { if (!WebInspector.SourceTokenizer.Registry._instance) WebInspector.SourceTokenizer.Registry._instance = new WebInspector.SourceTokenizer.Registry(); return WebInspector.SourceTokenizer.Registry._instance; } WebInspector.SourceTokenizer.Registry.prototype = { getTokenizer: function(mimeType) { if (!this._tokenizerConstructors[mimeType]) return null; var tokenizerClass = this._tokenizerConstructors[mimeType]; var tokenizer = this._tokenizers[tokenizerClass]; if (!tokenizer) { tokenizer = new WebInspector[tokenizerClass](); this._tokenizers[tokenizerClass] = tokenizer; } return tokenizer; } } WebInspector.SourceCSSTokenizer = function() { WebInspector.SourceTokenizer.call(this); this._propertyKeywords = WebInspector.CSSMetadata.cssPropertiesMetainfoKeySet(); this._colorKeywords = WebInspector.CSSMetadata.colors(); this._valueKeywords = [ "above", "absolute", "activeborder", "activecaption", "afar", "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", "both", "bottom", "break-all", "break-word", "button", "button-bevel", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", "col-resize", "collapse", "compact", "condensed", "contain", "content", "content-box", "context-menu", "continuous", "copy", "cover", "crop", "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", "decimal-leading-zero", "default", "default-button", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer", "landscape", "lao", "large", "larger", "left", "level", "lighter", "line-through", "linear", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", "lower-roman", "lowercase", "ltr", "malayalam", "match", "media-controls-background", "media-current-time-display", "media-fullscreen-button", "media-mute-button", "media-play-button", "media-return-to-realtime-button", "media-rewind-button", "media-seek-back-button", "media-seek-forward-button", "media-slider", "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", "media-volume-slider-container", "media-volume-sliderthumb", "medium", "menu", "menulist", "menulist-button", "menulist-text", "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize", "narrower", "navy", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", "outside", "overlay", "overline", "padding", "padding-box", "painted", "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radio", "read-only", "read-write", "read-write-plaintext-only", "relative", "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", "single", "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps", "small-caption", "smaller", "solid", "somali", "source-atop", "source-in", "source-out", "source-over", "space", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", "subpixel-antialiased", "super", "sw-resize", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "white", "wider", "window", "windowframe", "windowtext", "x-large", "x-small", "xor", "xx-large", "xx-small", "yellow", "-wap-marquee", "-webkit-activelink", "-webkit-auto", "-webkit-baseline-middle", "-webkit-body", "-webkit-box", "-webkit-center", "-webkit-control", "-webkit-focus-ring-color", "-webkit-grab", "-webkit-grabbing", "-webkit-gradient", "-webkit-inline-box", "-webkit-left", "-webkit-link", "-webkit-marquee", "-webkit-mini-control", "-webkit-nowrap", "-webkit-pictograph", "-webkit-right", "-webkit-small-control", "-webkit-text", "-webkit-xxx-large", "-webkit-zoom-in", "-webkit-zoom-out", ].keySet(); this._scssValueKeywords = [ "abs", "adjust-color", "adjust-hue", "alpha", "append", "ceil", "change-color", "comparable", "complement", "darken", "desaturate", "fade-in", "fade-out", "floor", "grayscale", "hue", "ie-hex-str", "invert", "join", "length", "lighten", "lightness", "max", "min", "mix", "nth", "opacify", "opacity", "percentage", "quote", "round", "saturate", "saturation", "scale-color", "transparentize", "type-of", "unit", "unitless", "unquote", "zip" ].keySet(); this._lexConditions = { INITIAL: 0, COMMENT: 1, DSTRING: 2, SSTRING: 3 }; this._parseConditions = { INITIAL: 0, PROPERTY: 1, PROPERTY_VALUE: 2, AT_RULE: 3, AT_MEDIA_RULE: 4 }; this.case_INITIAL = 1000; this.case_COMMENT = 1002; this.case_DSTRING = 1003; this.case_SSTRING = 1004; this.condition = this.createInitialCondition(); } WebInspector.SourceCSSTokenizer.SCSSAtRelatedKeywords = ["from", "if", "in", "through"].keySet(); WebInspector.SourceCSSTokenizer.MediaTypes = ["all", "aural", "braille", "embossed", "handheld", "import", "print", "projection", "screen", "tty", "tv"].keySet(); WebInspector.SourceCSSTokenizer.prototype = { createInitialCondition: function() { return { lexCondition: this._lexConditions.INITIAL, parseCondition: this._parseConditions.INITIAL }; }, _stringToken: function(cursor, stringEnds) { if (this._isPropertyValue()) this.tokenType = "css-string"; else this.tokenType = null; return cursor; }, _isPropertyValue: function() { return this._condition.parseCondition === this._parseConditions.PROPERTY_VALUE || this._condition.parseCondition === this._parseConditions.AT_RULE; }, _setParseCondition: function(condition) { this._condition.parseCondition = condition; }, nextToken: function(cursor) { var cursorOnEnter = cursor; var gotoCase = 1; var YYMARKER; while (1) { switch (gotoCase) { case 1: var yych; var yyaccept = 0; if (this.getLexCondition() < 2) { if (this.getLexCondition() < 1) { { gotoCase = this.case_INITIAL; continue; }; } else { { gotoCase = this.case_COMMENT; continue; }; } } else { if (this.getLexCondition() < 3) { { gotoCase = this.case_DSTRING; continue; }; } else { { gotoCase = this.case_SSTRING; continue; }; } } case this.case_COMMENT: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 4; continue; }; { gotoCase = 3; continue; }; } else { if (yych <= '\r') { gotoCase = 4; continue; }; if (yych == '*') { gotoCase = 6; continue; }; { gotoCase = 3; continue; }; } case 2: { this.tokenType = "css-comment"; return cursor; } case 3: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 12; continue; }; case 4: ++cursor; { this.tokenType = null; return cursor; } case 6: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych == '*') { gotoCase = 9; continue; }; if (yych != '/') { gotoCase = 11; continue; }; case 7: ++cursor; this.setLexCondition(this._lexConditions.INITIAL); { this.tokenType = "css-comment"; return cursor; } case 9: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 9; continue; }; if (yych == '/') { gotoCase = 7; continue; }; case 11: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 12: if (yych <= '\f') { if (yych == '\n') { gotoCase = 2; continue; }; { gotoCase = 11; continue; }; } else { if (yych <= '\r') { gotoCase = 2; continue; }; if (yych == '*') { gotoCase = 9; continue; }; { gotoCase = 11; continue; }; } case this.case_DSTRING: yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 17; continue; }; if (yych <= '\f') { gotoCase = 16; continue; }; { gotoCase = 17; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 16; continue; }; { gotoCase = 19; continue; }; } else { if (yych == '\\') { gotoCase = 21; continue; }; { gotoCase = 16; continue; }; } } case 15: { return this._stringToken(cursor); } case 16: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 23; continue; }; case 17: ++cursor; case 18: { this.tokenType = null; return cursor; } case 19: ++cursor; case 20: this.setLexCondition(this._lexConditions.INITIAL); { return this._stringToken(cursor, true); } case 21: yych = this._charAt(++cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 22; continue; }; if (yych <= '&') { gotoCase = 18; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 18; continue; }; } else { if (yych != 'b') { gotoCase = 18; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych >= 'g') { gotoCase = 18; continue; }; } else { if (yych <= 'n') { gotoCase = 22; continue; }; if (yych <= 'q') { gotoCase = 18; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 18; continue; }; } else { if (yych != 'v') { gotoCase = 18; continue; }; } } } case 22: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 23: if (yych <= '\r') { if (yych == '\n') { gotoCase = 15; continue; }; if (yych <= '\f') { gotoCase = 22; continue; }; { gotoCase = 15; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 22; continue; }; { gotoCase = 26; continue; }; } else { if (yych != '\\') { gotoCase = 22; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 22; continue; }; if (yych >= '\'') { gotoCase = 22; continue; }; } else { if (yych <= '\\') { if (yych >= '\\') { gotoCase = 22; continue; }; } else { if (yych == 'b') { gotoCase = 22; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych <= 'f') { gotoCase = 22; continue; }; } else { if (yych <= 'n') { gotoCase = 22; continue; }; if (yych >= 'r') { gotoCase = 22; continue; }; } } else { if (yych <= 't') { if (yych >= 't') { gotoCase = 22; continue; }; } else { if (yych == 'v') { gotoCase = 22; continue; }; } } } cursor = YYMARKER; { gotoCase = 15; continue; }; case 26: ++cursor; yych = this._charAt(cursor); { gotoCase = 20; continue; }; case this.case_INITIAL: yych = this._charAt(cursor); if (yych <= ':') { if (yych <= '&') { if (yych <= '"') { if (yych <= ' ') { gotoCase = 29; continue; }; if (yych <= '!') { gotoCase = 31; continue; }; { gotoCase = 33; continue; }; } else { if (yych <= '#') { gotoCase = 34; continue; }; if (yych <= '$') { gotoCase = 35; continue; }; if (yych >= '&') { gotoCase = 31; continue; }; } } else { if (yych <= '-') { if (yych <= '\'') { gotoCase = 36; continue; }; if (yych >= '-') { gotoCase = 37; continue; }; } else { if (yych <= '.') { gotoCase = 38; continue; }; if (yych <= '/') { gotoCase = 39; continue; }; if (yych <= '9') { gotoCase = 40; continue; }; { gotoCase = 42; continue; }; } } } else { if (yych <= ']') { if (yych <= '=') { if (yych <= ';') { gotoCase = 44; continue; }; if (yych >= '=') { gotoCase = 31; continue; }; } else { if (yych <= '?') { gotoCase = 29; continue; }; if (yych != '\\') { gotoCase = 31; continue; }; } } else { if (yych <= 'z') { if (yych == '_') { gotoCase = 31; continue; }; if (yych >= 'a') { gotoCase = 31; continue; }; } else { if (yych <= '{') { gotoCase = 46; continue; }; if (yych == '}') { gotoCase = 48; continue; }; } } } case 29: ++cursor; case 30: { this.tokenType = null; return cursor; } case 31: ++cursor; yych = this._charAt(cursor); { gotoCase = 51; continue; }; case 32: { var token = this._line.substring(cursorOnEnter, cursor); this.tokenType = null; if (this._condition.parseCondition === this._parseConditions.INITIAL || this._condition.parseCondition === this._parseConditions.PROPERTY) { if (token.charAt(0) === "@") { this.tokenType = "css-at-rule"; this._setParseCondition(token === "@media" ? this._parseConditions.AT_MEDIA_RULE : this._parseConditions.AT_RULE); this._condition.atKeyword = token; } else if (this._condition.parseCondition === this._parseConditions.INITIAL) this.tokenType = "css-selector"; else if (this._propertyKeywords.hasOwnProperty(token)) this.tokenType = "css-property"; } else if (this._condition.parseCondition === this._parseConditions.AT_MEDIA_RULE || this._condition.parseCondition === this._parseConditions.AT_RULE) { if (WebInspector.SourceCSSTokenizer.SCSSAtRelatedKeywords.hasOwnProperty(token)) this.tokenType = "css-at-rule"; else if (WebInspector.SourceCSSTokenizer.MediaTypes.hasOwnProperty(token)) this.tokenType = "css-keyword"; } if (this.tokenType) return cursor; if (this._isPropertyValue()) { var firstChar = token.charAt(0); if (firstChar === "$") this.tokenType = "scss-variable"; else if (firstChar === "!") this.tokenType = "css-bang-keyword"; else if (this._condition.atKeyword === "@extend") this.tokenType = "css-selector"; else if (this._valueKeywords.hasOwnProperty(token) || this._scssValueKeywords.hasOwnProperty(token)) this.tokenType = "css-keyword"; else if (this._colorKeywords.hasOwnProperty(token)) { this.tokenType = "css-color"; } } else if (this._condition.parseCondition !== this._parseConditions.PROPERTY_VALUE) this.tokenType = "css-selector"; return cursor; } case 33: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '.') { if (yych <= '!') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 32; continue; }; { gotoCase = 132; continue; }; } else { if (yych <= '\r') { gotoCase = 32; continue; }; if (yych <= ' ') { gotoCase = 132; continue; }; { gotoCase = 130; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 116; continue; }; if (yych <= '%') { gotoCase = 132; continue; }; { gotoCase = 130; continue; }; } else { if (yych == '-') { gotoCase = 130; continue; }; { gotoCase = 132; continue; }; } } } else { if (yych <= '\\') { if (yych <= '=') { if (yych <= '9') { gotoCase = 130; continue; }; if (yych <= '<') { gotoCase = 132; continue; }; { gotoCase = 130; continue; }; } else { if (yych <= '?') { gotoCase = 132; continue; }; if (yych <= '[') { gotoCase = 130; continue; }; { gotoCase = 134; continue; }; } } else { if (yych <= '_') { if (yych == '^') { gotoCase = 132; continue; }; { gotoCase = 130; continue; }; } else { if (yych <= '`') { gotoCase = 132; continue; }; if (yych <= 'z') { gotoCase = 130; continue; }; { gotoCase = 132; continue; }; } } } case 34: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 30; continue; }; if (yych <= '9') { gotoCase = 127; continue; }; { gotoCase = 30; continue; }; } else { if (yych <= 'Z') { gotoCase = 127; continue; }; if (yych <= '`') { gotoCase = 30; continue; }; if (yych <= 'z') { gotoCase = 127; continue; }; { gotoCase = 30; continue; }; } case 35: yych = this._charAt(++cursor); if (yych <= '<') { if (yych <= '\'') { if (yych <= ' ') { gotoCase = 30; continue; }; if (yych <= '"') { gotoCase = 124; continue; }; if (yych <= '%') { gotoCase = 30; continue; }; { gotoCase = 124; continue; }; } else { if (yych <= '-') { if (yych <= ',') { gotoCase = 30; continue; }; { gotoCase = 124; continue; }; } else { if (yych <= '.') { gotoCase = 30; continue; }; if (yych <= '9') { gotoCase = 124; continue; }; { gotoCase = 30; continue; }; } } } else { if (yych <= ']') { if (yych <= '?') { if (yych <= '=') { gotoCase = 124; continue; }; { gotoCase = 30; continue; }; } else { if (yych == '\\') { gotoCase = 30; continue; }; { gotoCase = 124; continue; }; } } else { if (yych <= '_') { if (yych <= '^') { gotoCase = 30; continue; }; { gotoCase = 124; continue; }; } else { if (yych <= '`') { gotoCase = 30; continue; }; if (yych <= 'z') { gotoCase = 124; continue; }; { gotoCase = 30; continue; }; } } } case 36: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '.') { if (yych <= '"') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 32; continue; }; { gotoCase = 118; continue; }; } else { if (yych <= '\r') { gotoCase = 32; continue; }; if (yych <= ' ') { gotoCase = 118; continue; }; { gotoCase = 114; continue; }; } } else { if (yych <= '\'') { if (yych <= '%') { gotoCase = 118; continue; }; if (yych <= '&') { gotoCase = 114; continue; }; { gotoCase = 116; continue; }; } else { if (yych == '-') { gotoCase = 114; continue; }; { gotoCase = 118; continue; }; } } } else { if (yych <= '\\') { if (yych <= '=') { if (yych <= '9') { gotoCase = 114; continue; }; if (yych <= '<') { gotoCase = 118; continue; }; { gotoCase = 114; continue; }; } else { if (yych <= '?') { gotoCase = 118; continue; }; if (yych <= '[') { gotoCase = 114; continue; }; { gotoCase = 120; continue; }; } } else { if (yych <= '_') { if (yych == '^') { gotoCase = 118; continue; }; { gotoCase = 114; continue; }; } else { if (yych <= '`') { gotoCase = 118; continue; }; if (yych <= 'z') { gotoCase = 114; continue; }; { gotoCase = 118; continue; }; } } } case 37: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '.') { gotoCase = 67; continue; }; if (yych <= '/') { gotoCase = 51; continue; }; if (yych <= '9') { gotoCase = 52; continue; }; { gotoCase = 51; continue; }; case 38: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 30; continue; }; if (yych <= '9') { gotoCase = 70; continue; }; { gotoCase = 30; continue; }; case 39: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '*') { gotoCase = 106; continue; }; { gotoCase = 51; continue; }; case 40: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); switch (yych) { case '!': case '"': case '&': case '\'': case '-': case '/': case '=': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case 'a': case 'b': case 'f': case 'h': case 'j': case 'l': case 'n': case 'o': case 'q': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { gotoCase = 50; continue; }; case '%': { gotoCase = 69; continue; }; case '.': { gotoCase = 67; continue; }; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { gotoCase = 52; continue; }; case 'H': { gotoCase = 54; continue; }; case '_': { gotoCase = 55; continue; }; case 'c': { gotoCase = 56; continue; }; case 'd': { gotoCase = 57; continue; }; case 'e': { gotoCase = 58; continue; }; case 'g': { gotoCase = 59; continue; }; case 'i': { gotoCase = 60; continue; }; case 'k': { gotoCase = 61; continue; }; case 'm': { gotoCase = 62; continue; }; case 'p': { gotoCase = 63; continue; }; case 'r': { gotoCase = 64; continue; }; case 's': { gotoCase = 65; continue; }; case 't': { gotoCase = 66; continue; }; default: { gotoCase = 41; continue; }; } case 41: { if (this._isPropertyValue()) this.tokenType = "css-number"; else this.tokenType = null; return cursor; } case 42: ++cursor; { this.tokenType = null; if (this._condition.parseCondition === this._parseConditions.PROPERTY || this._condition.parseCondition === this._parseConditions.INITIAL) this._setParseCondition(this._parseConditions.PROPERTY_VALUE); return cursor; } case 44: ++cursor; { this.tokenType = null; this._setParseCondition(this._condition.openBraces ? this._parseConditions.PROPERTY : this._parseConditions.INITIAL); delete this._condition.atKeyword; return cursor; } case 46: ++cursor; { this.tokenType = "block-start"; this._condition.openBraces = (this._condition.openBraces || 0) + 1; if (this._condition.parseCondition === this._parseConditions.AT_MEDIA_RULE) this._setParseCondition(this._parseConditions.INITIAL); else this._setParseCondition(this._parseConditions.PROPERTY); return cursor; } case 48: ++cursor; { this.tokenType = "block-end"; if (this._condition.openBraces > 0) --this._condition.openBraces; this._setParseCondition(this._condition.openBraces ? this._parseConditions.PROPERTY : this._parseConditions.INITIAL); delete this._condition.atKeyword; return cursor; } case 50: ++cursor; yych = this._charAt(cursor); case 51: if (yych <= '<') { if (yych <= '\'') { if (yych <= ' ') { gotoCase = 32; continue; }; if (yych <= '"') { gotoCase = 50; continue; }; if (yych <= '%') { gotoCase = 32; continue; }; { gotoCase = 50; continue; }; } else { if (yych <= '-') { if (yych <= ',') { gotoCase = 32; continue; }; { gotoCase = 50; continue; }; } else { if (yych <= '.') { gotoCase = 32; continue; }; if (yych <= '9') { gotoCase = 50; continue; }; { gotoCase = 32; continue; }; } } } else { if (yych <= ']') { if (yych <= '?') { if (yych <= '=') { gotoCase = 50; continue; }; { gotoCase = 32; continue; }; } else { if (yych == '\\') { gotoCase = 32; continue; }; { gotoCase = 50; continue; }; } } else { if (yych <= '_') { if (yych <= '^') { gotoCase = 32; continue; }; { gotoCase = 50; continue; }; } else { if (yych <= '`') { gotoCase = 32; continue; }; if (yych <= 'z') { gotoCase = 50; continue; }; { gotoCase = 32; continue; }; } } } case 52: yyaccept = 1; YYMARKER = ++cursor; yych = this._charAt(cursor); switch (yych) { case '!': case '"': case '&': case '\'': case '-': case '/': case '=': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case 'a': case 'b': case 'f': case 'h': case 'j': case 'l': case 'n': case 'o': case 'q': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { gotoCase = 50; continue; }; case '%': { gotoCase = 69; continue; }; case '.': { gotoCase = 67; continue; }; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { gotoCase = 52; continue; }; case 'H': { gotoCase = 54; continue; }; case '_': { gotoCase = 55; continue; }; case 'c': { gotoCase = 56; continue; }; case 'd': { gotoCase = 57; continue; }; case 'e': { gotoCase = 58; continue; }; case 'g': { gotoCase = 59; continue; }; case 'i': { gotoCase = 60; continue; }; case 'k': { gotoCase = 61; continue; }; case 'm': { gotoCase = 62; continue; }; case 'p': { gotoCase = 63; continue; }; case 'r': { gotoCase = 64; continue; }; case 's': { gotoCase = 65; continue; }; case 't': { gotoCase = 66; continue; }; default: { gotoCase = 41; continue; }; } case 54: yych = this._charAt(++cursor); if (yych == 'z') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 55: yych = this._charAt(++cursor); if (yych == '_') { gotoCase = 103; continue; }; { gotoCase = 51; continue; }; case 56: yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 57: yych = this._charAt(++cursor); if (yych == 'e') { gotoCase = 102; continue; }; { gotoCase = 51; continue; }; case 58: yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 65; continue; }; if (yych == 'x') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 59: yych = this._charAt(++cursor); if (yych == 'r') { gotoCase = 100; continue; }; { gotoCase = 51; continue; }; case 60: yych = this._charAt(++cursor); if (yych == 'n') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 61: yych = this._charAt(++cursor); if (yych == 'H') { gotoCase = 99; continue; }; { gotoCase = 51; continue; }; case 62: yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 65; continue; }; if (yych == 's') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 63: yych = this._charAt(++cursor); if (yych <= 's') { if (yych == 'c') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; } else { if (yych <= 't') { gotoCase = 65; continue; }; if (yych == 'x') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; } case 64: yych = this._charAt(++cursor); if (yych == 'a') { gotoCase = 97; continue; }; if (yych == 'e') { gotoCase = 98; continue; }; { gotoCase = 51; continue; }; case 65: yych = this._charAt(++cursor); if (yych <= '<') { if (yych <= '\'') { if (yych <= ' ') { gotoCase = 41; continue; }; if (yych <= '"') { gotoCase = 50; continue; }; if (yych <= '%') { gotoCase = 41; continue; }; { gotoCase = 50; continue; }; } else { if (yych <= '-') { if (yych <= ',') { gotoCase = 41; continue; }; { gotoCase = 50; continue; }; } else { if (yych <= '.') { gotoCase = 41; continue; }; if (yych <= '9') { gotoCase = 50; continue; }; { gotoCase = 41; continue; }; } } } else { if (yych <= ']') { if (yych <= '?') { if (yych <= '=') { gotoCase = 50; continue; }; { gotoCase = 41; continue; }; } else { if (yych == '\\') { gotoCase = 41; continue; }; { gotoCase = 50; continue; }; } } else { if (yych <= '_') { if (yych <= '^') { gotoCase = 41; continue; }; { gotoCase = 50; continue; }; } else { if (yych <= '`') { gotoCase = 41; continue; }; if (yych <= 'z') { gotoCase = 50; continue; }; { gotoCase = 41; continue; }; } } } case 66: yych = this._charAt(++cursor); if (yych == 'u') { gotoCase = 95; continue; }; { gotoCase = 51; continue; }; case 67: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 68; continue; }; if (yych <= '9') { gotoCase = 70; continue; }; case 68: cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 32; continue; }; } else { { gotoCase = 41; continue; }; } case 69: yych = this._charAt(++cursor); { gotoCase = 41; continue; }; case 70: yyaccept = 1; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'f') { if (yych <= 'H') { if (yych <= '/') { if (yych == '%') { gotoCase = 69; continue; }; { gotoCase = 41; continue; }; } else { if (yych <= '9') { gotoCase = 70; continue; }; if (yych <= 'G') { gotoCase = 41; continue; }; { gotoCase = 82; continue; }; } } else { if (yych <= 'b') { if (yych == '_') { gotoCase = 74; continue; }; { gotoCase = 41; continue; }; } else { if (yych <= 'c') { gotoCase = 76; continue; }; if (yych <= 'd') { gotoCase = 79; continue; }; if (yych >= 'f') { gotoCase = 41; continue; }; } } } else { if (yych <= 'm') { if (yych <= 'i') { if (yych <= 'g') { gotoCase = 80; continue; }; if (yych <= 'h') { gotoCase = 41; continue; }; { gotoCase = 78; continue; }; } else { if (yych == 'k') { gotoCase = 83; continue; }; if (yych <= 'l') { gotoCase = 41; continue; }; { gotoCase = 77; continue; }; } } else { if (yych <= 'q') { if (yych == 'p') { gotoCase = 75; continue; }; { gotoCase = 41; continue; }; } else { if (yych <= 'r') { gotoCase = 73; continue; }; if (yych <= 's') { gotoCase = 69; continue; }; if (yych <= 't') { gotoCase = 81; continue; }; { gotoCase = 41; continue; }; } } } yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 69; continue; }; if (yych == 'x') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 73: yych = this._charAt(++cursor); if (yych == 'a') { gotoCase = 93; continue; }; if (yych == 'e') { gotoCase = 94; continue; }; { gotoCase = 68; continue; }; case 74: yych = this._charAt(++cursor); if (yych == '_') { gotoCase = 90; continue; }; { gotoCase = 68; continue; }; case 75: yych = this._charAt(++cursor); if (yych <= 's') { if (yych == 'c') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; } else { if (yych <= 't') { gotoCase = 69; continue; }; if (yych == 'x') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; } case 76: yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 77: yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 69; continue; }; if (yych == 's') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 78: yych = this._charAt(++cursor); if (yych == 'n') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 79: yych = this._charAt(++cursor); if (yych == 'e') { gotoCase = 89; continue; }; { gotoCase = 68; continue; }; case 80: yych = this._charAt(++cursor); if (yych == 'r') { gotoCase = 87; continue; }; { gotoCase = 68; continue; }; case 81: yych = this._charAt(++cursor); if (yych == 'u') { gotoCase = 85; continue; }; { gotoCase = 68; continue; }; case 82: yych = this._charAt(++cursor); if (yych == 'z') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 83: yych = this._charAt(++cursor); if (yych != 'H') { gotoCase = 68; continue; }; yych = this._charAt(++cursor); if (yych == 'z') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 85: yych = this._charAt(++cursor); if (yych != 'r') { gotoCase = 68; continue; }; yych = this._charAt(++cursor); if (yych == 'n') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 87: yych = this._charAt(++cursor); if (yych != 'a') { gotoCase = 68; continue; }; yych = this._charAt(++cursor); if (yych == 'd') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 89: yych = this._charAt(++cursor); if (yych == 'g') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 90: yych = this._charAt(++cursor); if (yych != 'q') { gotoCase = 68; continue; }; yych = this._charAt(++cursor); if (yych != 'e') { gotoCase = 68; continue; }; yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 93: yych = this._charAt(++cursor); if (yych == 'd') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 94: yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 69; continue; }; { gotoCase = 68; continue; }; case 95: yych = this._charAt(++cursor); if (yych != 'r') { gotoCase = 51; continue; }; yych = this._charAt(++cursor); if (yych == 'n') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 97: yych = this._charAt(++cursor); if (yych == 'd') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 98: yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 99: yych = this._charAt(++cursor); if (yych == 'z') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 100: yych = this._charAt(++cursor); if (yych != 'a') { gotoCase = 51; continue; }; yych = this._charAt(++cursor); if (yych == 'd') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 102: yych = this._charAt(++cursor); if (yych == 'g') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 103: yych = this._charAt(++cursor); if (yych != 'q') { gotoCase = 51; continue; }; yych = this._charAt(++cursor); if (yych != 'e') { gotoCase = 51; continue; }; yych = this._charAt(++cursor); if (yych == 'm') { gotoCase = 65; continue; }; { gotoCase = 51; continue; }; case 106: ++cursor; yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 110; continue; }; { gotoCase = 106; continue; }; } else { if (yych <= '\r') { gotoCase = 110; continue; }; if (yych != '*') { gotoCase = 106; continue; }; } case 108: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 108; continue; }; if (yych == '/') { gotoCase = 112; continue; }; { gotoCase = 106; continue; }; case 110: ++cursor; this.setLexCondition(this._lexConditions.COMMENT); { this.tokenType = "css-comment"; return cursor; } case 112: ++cursor; { this.tokenType = "css-comment"; return cursor; } case 114: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '.') { if (yych <= '"') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 32; continue; }; { gotoCase = 118; continue; }; } else { if (yych <= '\r') { gotoCase = 32; continue; }; if (yych <= ' ') { gotoCase = 118; continue; }; { gotoCase = 114; continue; }; } } else { if (yych <= '\'') { if (yych <= '%') { gotoCase = 118; continue; }; if (yych <= '&') { gotoCase = 114; continue; }; } else { if (yych == '-') { gotoCase = 114; continue; }; { gotoCase = 118; continue; }; } } } else { if (yych <= '\\') { if (yych <= '=') { if (yych <= '9') { gotoCase = 114; continue; }; if (yych <= '<') { gotoCase = 118; continue; }; { gotoCase = 114; continue; }; } else { if (yych <= '?') { gotoCase = 118; continue; }; if (yych <= '[') { gotoCase = 114; continue; }; { gotoCase = 120; continue; }; } } else { if (yych <= '_') { if (yych == '^') { gotoCase = 118; continue; }; { gotoCase = 114; continue; }; } else { if (yych <= '`') { gotoCase = 118; continue; }; if (yych <= 'z') { gotoCase = 114; continue; }; { gotoCase = 118; continue; }; } } } case 116: ++cursor; if ((yych = this._charAt(cursor)) <= '<') { if (yych <= '\'') { if (yych <= ' ') { gotoCase = 117; continue; }; if (yych <= '"') { gotoCase = 50; continue; }; if (yych >= '&') { gotoCase = 50; continue; }; } else { if (yych <= '-') { if (yych >= '-') { gotoCase = 50; continue; }; } else { if (yych <= '.') { gotoCase = 117; continue; }; if (yych <= '9') { gotoCase = 50; continue; }; } } } else { if (yych <= ']') { if (yych <= '?') { if (yych <= '=') { gotoCase = 50; continue; }; } else { if (yych != '\\') { gotoCase = 50; continue; }; } } else { if (yych <= '_') { if (yych >= '_') { gotoCase = 50; continue; }; } else { if (yych <= '`') { gotoCase = 117; continue; }; if (yych <= 'z') { gotoCase = 50; continue; }; } } } case 117: { return this._stringToken(cursor, true); } case 118: ++cursor; yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 68; continue; }; if (yych <= '\f') { gotoCase = 118; continue; }; { gotoCase = 68; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 118; continue; }; { gotoCase = 123; continue; }; } else { if (yych != '\\') { gotoCase = 118; continue; }; } } case 120: ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 68; continue; }; } else { if (yych != '\r') { gotoCase = 68; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 118; continue; }; if (yych <= '&') { gotoCase = 68; continue; }; { gotoCase = 118; continue; }; } else { if (yych == '\\') { gotoCase = 118; continue; }; { gotoCase = 68; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 118; continue; }; if (yych <= 'e') { gotoCase = 68; continue; }; { gotoCase = 118; continue; }; } else { if (yych == 'n') { gotoCase = 118; continue; }; { gotoCase = 68; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 68; continue; }; { gotoCase = 118; continue; }; } else { if (yych == 'v') { gotoCase = 118; continue; }; { gotoCase = 68; continue; }; } } } ++cursor; this.setLexCondition(this._lexConditions.SSTRING); { return this._stringToken(cursor); } case 123: yych = this._charAt(++cursor); { gotoCase = 117; continue; }; case 124: ++cursor; yych = this._charAt(cursor); if (yych <= '<') { if (yych <= '\'') { if (yych <= ' ') { gotoCase = 126; continue; }; if (yych <= '"') { gotoCase = 124; continue; }; if (yych >= '&') { gotoCase = 124; continue; }; } else { if (yych <= '-') { if (yych >= '-') { gotoCase = 124; continue; }; } else { if (yych <= '.') { gotoCase = 126; continue; }; if (yych <= '9') { gotoCase = 124; continue; }; } } } else { if (yych <= ']') { if (yych <= '?') { if (yych <= '=') { gotoCase = 124; continue; }; } else { if (yych != '\\') { gotoCase = 124; continue; }; } } else { if (yych <= '_') { if (yych >= '_') { gotoCase = 124; continue; }; } else { if (yych <= '`') { gotoCase = 126; continue; }; if (yych <= 'z') { gotoCase = 124; continue; }; } } } case 126: { if (this._condition.parseCondition === this._condition.parseCondition.INITIAL || this._condition.parseCondition === this._condition.parseCondition.AT_RULE) this._setParseCondition(this._parseConditions.PROPERTY); this.tokenType = "scss-variable"; return cursor; } case 127: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 129; continue; }; if (yych <= '9') { gotoCase = 127; continue; }; } else { if (yych <= 'Z') { gotoCase = 127; continue; }; if (yych <= '`') { gotoCase = 129; continue; }; if (yych <= 'z') { gotoCase = 127; continue; }; } case 129: { if (this._isPropertyValue()) this.tokenType = "css-color"; else if (this._condition.parseCondition === this._parseConditions.INITIAL) this.tokenType = "css-selector"; else this.tokenType = null; return cursor; } case 130: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '.') { if (yych <= '!') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 32; continue; }; } else { if (yych <= '\r') { gotoCase = 32; continue; }; if (yych >= '!') { gotoCase = 130; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 116; continue; }; if (yych >= '&') { gotoCase = 130; continue; }; } else { if (yych == '-') { gotoCase = 130; continue; }; } } } else { if (yych <= '\\') { if (yych <= '=') { if (yych <= '9') { gotoCase = 130; continue; }; if (yych >= '=') { gotoCase = 130; continue; }; } else { if (yych <= '?') { gotoCase = 132; continue; }; if (yych <= '[') { gotoCase = 130; continue; }; { gotoCase = 134; continue; }; } } else { if (yych <= '_') { if (yych != '^') { gotoCase = 130; continue; }; } else { if (yych <= '`') { gotoCase = 132; continue; }; if (yych <= 'z') { gotoCase = 130; continue; }; } } } case 132: ++cursor; yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 68; continue; }; if (yych <= '\f') { gotoCase = 132; continue; }; { gotoCase = 68; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 132; continue; }; { gotoCase = 123; continue; }; } else { if (yych != '\\') { gotoCase = 132; continue; }; } } case 134: ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 68; continue; }; } else { if (yych != '\r') { gotoCase = 68; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 132; continue; }; if (yych <= '&') { gotoCase = 68; continue; }; { gotoCase = 132; continue; }; } else { if (yych == '\\') { gotoCase = 132; continue; }; { gotoCase = 68; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 132; continue; }; if (yych <= 'e') { gotoCase = 68; continue; }; { gotoCase = 132; continue; }; } else { if (yych == 'n') { gotoCase = 132; continue; }; { gotoCase = 68; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 68; continue; }; { gotoCase = 132; continue; }; } else { if (yych == 'v') { gotoCase = 132; continue; }; { gotoCase = 68; continue; }; } } } ++cursor; this.setLexCondition(this._lexConditions.DSTRING); { return this._stringToken(cursor); } case this.case_SSTRING: yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 141; continue; }; if (yych <= '\f') { gotoCase = 140; continue; }; { gotoCase = 141; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 140; continue; }; { gotoCase = 143; continue; }; } else { if (yych == '\\') { gotoCase = 145; continue; }; { gotoCase = 140; continue; }; } } case 139: { return this._stringToken(cursor); } case 140: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 147; continue; }; case 141: ++cursor; case 142: { this.tokenType = null; return cursor; } case 143: ++cursor; case 144: this.setLexCondition(this._lexConditions.INITIAL); { return this._stringToken(cursor, true); } case 145: yych = this._charAt(++cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 146; continue; }; if (yych <= '&') { gotoCase = 142; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 142; continue; }; } else { if (yych != 'b') { gotoCase = 142; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych >= 'g') { gotoCase = 142; continue; }; } else { if (yych <= 'n') { gotoCase = 146; continue; }; if (yych <= 'q') { gotoCase = 142; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 142; continue; }; } else { if (yych != 'v') { gotoCase = 142; continue; }; } } } case 146: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 147: if (yych <= '\r') { if (yych == '\n') { gotoCase = 139; continue; }; if (yych <= '\f') { gotoCase = 146; continue; }; { gotoCase = 139; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 146; continue; }; { gotoCase = 150; continue; }; } else { if (yych != '\\') { gotoCase = 146; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 146; continue; }; if (yych >= '\'') { gotoCase = 146; continue; }; } else { if (yych <= '\\') { if (yych >= '\\') { gotoCase = 146; continue; }; } else { if (yych == 'b') { gotoCase = 146; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych <= 'f') { gotoCase = 146; continue; }; } else { if (yych <= 'n') { gotoCase = 146; continue; }; if (yych >= 'r') { gotoCase = 146; continue; }; } } else { if (yych <= 't') { if (yych >= 't') { gotoCase = 146; continue; }; } else { if (yych == 'v') { gotoCase = 146; continue; }; } } } cursor = YYMARKER; { gotoCase = 139; continue; }; case 150: ++cursor; yych = this._charAt(cursor); { gotoCase = 144; continue; }; } } }, __proto__: WebInspector.SourceTokenizer.prototype } WebInspector.SourceHTMLTokenizer = function() { WebInspector.SourceTokenizer.call(this); this._lexConditions = { INITIAL: 0, COMMENT: 1, DOCTYPE: 2, TAG: 3, DSTRING: 4, SSTRING: 5 }; this.case_INITIAL = 1000; this.case_COMMENT = 1001; this.case_DOCTYPE = 1002; this.case_TAG = 1003; this.case_DSTRING = 1004; this.case_SSTRING = 1005; this._parseConditions = { INITIAL: 0, ATTRIBUTE: 1, ATTRIBUTE_VALUE: 2, LINKIFY: 4, A_NODE: 8, SCRIPT: 16, STYLE: 32 }; this.condition = this.createInitialCondition(); } WebInspector.SourceHTMLTokenizer.prototype = { createInitialCondition: function() { return { lexCondition: this._lexConditions.INITIAL, parseCondition: this._parseConditions.INITIAL }; }, set line(line) { if (this._condition.internalJavaScriptTokenizerCondition) { var match = /<\/script/i.exec(line); if (match) { this._internalJavaScriptTokenizer.line = line.substring(0, match.index); } else this._internalJavaScriptTokenizer.line = line; } else if (this._condition.internalCSSTokenizerCondition) { var match = /<\/style/i.exec(line); if (match) { this._internalCSSTokenizer.line = line.substring(0, match.index); } else this._internalCSSTokenizer.line = line; } this._line = line; }, _isExpectingAttribute: function() { return this._condition.parseCondition & this._parseConditions.ATTRIBUTE; }, _isExpectingAttributeValue: function() { return this._condition.parseCondition & this._parseConditions.ATTRIBUTE_VALUE; }, _setExpectingAttribute: function() { if (this._isExpectingAttributeValue()) this._condition.parseCondition ^= this._parseConditions.ATTRIBUTE_VALUE; this._condition.parseCondition |= this._parseConditions.ATTRIBUTE; }, _setExpectingAttributeValue: function() { if (this._isExpectingAttribute()) this._condition.parseCondition ^= this._parseConditions.ATTRIBUTE; this._condition.parseCondition |= this._parseConditions.ATTRIBUTE_VALUE; }, _stringToken: function(cursor, stringEnds) { if (!this._isExpectingAttributeValue()) { this.tokenType = null; return cursor; } this.tokenType = this._attrValueTokenType(); if (stringEnds) this._setExpectingAttribute(); return cursor; }, _attrValueTokenType: function() { if (this._condition.parseCondition & this._parseConditions.LINKIFY) { if (this._condition.parseCondition & this._parseConditions.A_NODE) return "html-external-link"; return "html-resource-link"; } return "html-attribute-value"; }, get _internalJavaScriptTokenizer() { return WebInspector.SourceTokenizer.Registry.getInstance().getTokenizer("text/javascript"); }, get _internalCSSTokenizer() { return WebInspector.SourceTokenizer.Registry.getInstance().getTokenizer("text/css"); }, scriptStarted: function(cursor) { this._condition.internalJavaScriptTokenizerCondition = this._internalJavaScriptTokenizer.createInitialCondition(); }, scriptEnded: function(cursor) { }, styleSheetStarted: function(cursor) { this._condition.internalCSSTokenizerCondition = this._internalCSSTokenizer.createInitialCondition(); }, styleSheetEnded: function(cursor) { }, nextToken: function(cursor) { if (this._condition.internalJavaScriptTokenizerCondition) { this.line = this._line; if (cursor !== this._internalJavaScriptTokenizer._line.length) { this._internalJavaScriptTokenizer.condition = this._condition.internalJavaScriptTokenizerCondition; var result = this._internalJavaScriptTokenizer.nextToken(cursor); this.tokenType = this._internalJavaScriptTokenizer.tokenType; this._condition.internalJavaScriptTokenizerCondition = this._internalJavaScriptTokenizer.condition; return result; } else if (cursor !== this._line.length) delete this._condition.internalJavaScriptTokenizerCondition; } else if (this._condition.internalCSSTokenizerCondition) { this.line = this._line; if (cursor !== this._internalCSSTokenizer._line.length) { this._internalCSSTokenizer.condition = this._condition.internalCSSTokenizerCondition; var result = this._internalCSSTokenizer.nextToken(cursor); this.tokenType = this._internalCSSTokenizer.tokenType; this._condition.internalCSSTokenizerCondition = this._internalCSSTokenizer.condition; return result; } else if (cursor !== this._line.length) delete this._condition.internalCSSTokenizerCondition; } var cursorOnEnter = cursor; var gotoCase = 1; var YYMARKER; while (1) { switch (gotoCase) { case 1: var yych; var yyaccept = 0; if (this.getLexCondition() < 3) { if (this.getLexCondition() < 1) { { gotoCase = this.case_INITIAL; continue; }; } else { if (this.getLexCondition() < 2) { { gotoCase = this.case_COMMENT; continue; }; } else { { gotoCase = this.case_DOCTYPE; continue; }; } } } else { if (this.getLexCondition() < 4) { { gotoCase = this.case_TAG; continue; }; } else { if (this.getLexCondition() < 5) { { gotoCase = this.case_DSTRING; continue; }; } else { { gotoCase = this.case_SSTRING; continue; }; } } } case this.case_COMMENT: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 4; continue; }; { gotoCase = 3; continue; }; } else { if (yych <= '\r') { gotoCase = 4; continue; }; if (yych == '-') { gotoCase = 6; continue; }; { gotoCase = 3; continue; }; } case 2: { this.tokenType = "html-comment"; return cursor; } case 3: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 9; continue; }; case 4: ++cursor; case 5: { this.tokenType = null; return cursor; } case 6: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych != '-') { gotoCase = 5; continue; }; case 7: ++cursor; yych = this._charAt(cursor); if (yych == '>') { gotoCase = 10; continue; }; case 8: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 9: if (yych <= '\f') { if (yych == '\n') { gotoCase = 2; continue; }; { gotoCase = 8; continue; }; } else { if (yych <= '\r') { gotoCase = 2; continue; }; if (yych == '-') { gotoCase = 12; continue; }; { gotoCase = 8; continue; }; } case 10: ++cursor; this.setLexCondition(this._lexConditions.INITIAL); { this.tokenType = "html-comment"; return cursor; } case 12: ++cursor; yych = this._charAt(cursor); if (yych == '-') { gotoCase = 7; continue; }; cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 2; continue; }; } else { { gotoCase = 5; continue; }; } case this.case_DOCTYPE: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 18; continue; }; { gotoCase = 17; continue; }; } else { if (yych <= '\r') { gotoCase = 18; continue; }; if (yych == '>') { gotoCase = 20; continue; }; { gotoCase = 17; continue; }; } case 16: { this.tokenType = "html-doctype"; return cursor; } case 17: yych = this._charAt(++cursor); { gotoCase = 23; continue; }; case 18: ++cursor; { this.tokenType = null; return cursor; } case 20: ++cursor; this.setLexCondition(this._lexConditions.INITIAL); { this.tokenType = "html-doctype"; return cursor; } case 22: ++cursor; yych = this._charAt(cursor); case 23: if (yych <= '\f') { if (yych == '\n') { gotoCase = 16; continue; }; { gotoCase = 22; continue; }; } else { if (yych <= '\r') { gotoCase = 16; continue; }; if (yych == '>') { gotoCase = 16; continue; }; { gotoCase = 22; continue; }; } case this.case_DSTRING: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 28; continue; }; { gotoCase = 27; continue; }; } else { if (yych <= '\r') { gotoCase = 28; continue; }; if (yych == '"') { gotoCase = 30; continue; }; { gotoCase = 27; continue; }; } case 26: { return this._stringToken(cursor); } case 27: yych = this._charAt(++cursor); { gotoCase = 34; continue; }; case 28: ++cursor; { this.tokenType = null; return cursor; } case 30: ++cursor; case 31: this.setLexCondition(this._lexConditions.TAG); { return this._stringToken(cursor, true); } case 32: yych = this._charAt(++cursor); { gotoCase = 31; continue; }; case 33: ++cursor; yych = this._charAt(cursor); case 34: if (yych <= '\f') { if (yych == '\n') { gotoCase = 26; continue; }; { gotoCase = 33; continue; }; } else { if (yych <= '\r') { gotoCase = 26; continue; }; if (yych == '"') { gotoCase = 32; continue; }; { gotoCase = 33; continue; }; } case this.case_INITIAL: yych = this._charAt(cursor); if (yych == '<') { gotoCase = 39; continue; }; ++cursor; { this.tokenType = null; return cursor; } case 39: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '/') { if (yych == '!') { gotoCase = 44; continue; }; if (yych >= '/') { gotoCase = 41; continue; }; } else { if (yych <= 'S') { if (yych >= 'S') { gotoCase = 42; continue; }; } else { if (yych == 's') { gotoCase = 42; continue; }; } } case 40: this.setLexCondition(this._lexConditions.TAG); { if (this._condition.parseCondition & (this._parseConditions.SCRIPT | this._parseConditions.STYLE)) { this.setLexCondition(this._lexConditions.INITIAL); this.tokenType = null; return cursor; } this._condition.parseCondition = this._parseConditions.INITIAL; this.tokenType = "html-tag"; return cursor; } case 41: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == 'S') { gotoCase = 73; continue; }; if (yych == 's') { gotoCase = 73; continue; }; { gotoCase = 40; continue; }; case 42: yych = this._charAt(++cursor); if (yych <= 'T') { if (yych == 'C') { gotoCase = 62; continue; }; if (yych >= 'T') { gotoCase = 63; continue; }; } else { if (yych <= 'c') { if (yych >= 'c') { gotoCase = 62; continue; }; } else { if (yych == 't') { gotoCase = 63; continue; }; } } case 43: cursor = YYMARKER; { gotoCase = 40; continue; }; case 44: yych = this._charAt(++cursor); if (yych <= 'C') { if (yych != '-') { gotoCase = 43; continue; }; } else { if (yych <= 'D') { gotoCase = 46; continue; }; if (yych == 'd') { gotoCase = 46; continue; }; { gotoCase = 43; continue; }; } yych = this._charAt(++cursor); if (yych == '-') { gotoCase = 54; continue; }; { gotoCase = 43; continue; }; case 46: yych = this._charAt(++cursor); if (yych == 'O') { gotoCase = 47; continue; }; if (yych != 'o') { gotoCase = 43; continue; }; case 47: yych = this._charAt(++cursor); if (yych == 'C') { gotoCase = 48; continue; }; if (yych != 'c') { gotoCase = 43; continue; }; case 48: yych = this._charAt(++cursor); if (yych == 'T') { gotoCase = 49; continue; }; if (yych != 't') { gotoCase = 43; continue; }; case 49: yych = this._charAt(++cursor); if (yych == 'Y') { gotoCase = 50; continue; }; if (yych != 'y') { gotoCase = 43; continue; }; case 50: yych = this._charAt(++cursor); if (yych == 'P') { gotoCase = 51; continue; }; if (yych != 'p') { gotoCase = 43; continue; }; case 51: yych = this._charAt(++cursor); if (yych == 'E') { gotoCase = 52; continue; }; if (yych != 'e') { gotoCase = 43; continue; }; case 52: ++cursor; this.setLexCondition(this._lexConditions.DOCTYPE); { this.tokenType = "html-doctype"; return cursor; } case 54: ++cursor; yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 57; continue; }; { gotoCase = 54; continue; }; } else { if (yych <= '\r') { gotoCase = 57; continue; }; if (yych != '-') { gotoCase = 54; continue; }; } ++cursor; yych = this._charAt(cursor); if (yych == '-') { gotoCase = 59; continue; }; { gotoCase = 43; continue; }; case 57: ++cursor; this.setLexCondition(this._lexConditions.COMMENT); { this.tokenType = "html-comment"; return cursor; } case 59: ++cursor; yych = this._charAt(cursor); if (yych != '>') { gotoCase = 54; continue; }; ++cursor; { this.tokenType = "html-comment"; return cursor; } case 62: yych = this._charAt(++cursor); if (yych == 'R') { gotoCase = 68; continue; }; if (yych == 'r') { gotoCase = 68; continue; }; { gotoCase = 43; continue; }; case 63: yych = this._charAt(++cursor); if (yych == 'Y') { gotoCase = 64; continue; }; if (yych != 'y') { gotoCase = 43; continue; }; case 64: yych = this._charAt(++cursor); if (yych == 'L') { gotoCase = 65; continue; }; if (yych != 'l') { gotoCase = 43; continue; }; case 65: yych = this._charAt(++cursor); if (yych == 'E') { gotoCase = 66; continue; }; if (yych != 'e') { gotoCase = 43; continue; }; case 66: ++cursor; this.setLexCondition(this._lexConditions.TAG); { if (this._condition.parseCondition & this._parseConditions.STYLE) { this.setLexCondition(this._lexConditions.INITIAL); this.tokenType = null; return cursor; } this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.STYLE; this._setExpectingAttribute(); return cursor; } case 68: yych = this._charAt(++cursor); if (yych == 'I') { gotoCase = 69; continue; }; if (yych != 'i') { gotoCase = 43; continue; }; case 69: yych = this._charAt(++cursor); if (yych == 'P') { gotoCase = 70; continue; }; if (yych != 'p') { gotoCase = 43; continue; }; case 70: yych = this._charAt(++cursor); if (yych == 'T') { gotoCase = 71; continue; }; if (yych != 't') { gotoCase = 43; continue; }; case 71: ++cursor; this.setLexCondition(this._lexConditions.TAG); { if (this._condition.parseCondition & this._parseConditions.SCRIPT) { this.setLexCondition(this._lexConditions.INITIAL); this.tokenType = null; return cursor; } this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.SCRIPT; this._setExpectingAttribute(); return cursor; } case 73: yych = this._charAt(++cursor); if (yych <= 'T') { if (yych == 'C') { gotoCase = 75; continue; }; if (yych <= 'S') { gotoCase = 43; continue; }; } else { if (yych <= 'c') { if (yych <= 'b') { gotoCase = 43; continue; }; { gotoCase = 75; continue; }; } else { if (yych != 't') { gotoCase = 43; continue; }; } } yych = this._charAt(++cursor); if (yych == 'Y') { gotoCase = 81; continue; }; if (yych == 'y') { gotoCase = 81; continue; }; { gotoCase = 43; continue; }; case 75: yych = this._charAt(++cursor); if (yych == 'R') { gotoCase = 76; continue; }; if (yych != 'r') { gotoCase = 43; continue; }; case 76: yych = this._charAt(++cursor); if (yych == 'I') { gotoCase = 77; continue; }; if (yych != 'i') { gotoCase = 43; continue; }; case 77: yych = this._charAt(++cursor); if (yych == 'P') { gotoCase = 78; continue; }; if (yych != 'p') { gotoCase = 43; continue; }; case 78: yych = this._charAt(++cursor); if (yych == 'T') { gotoCase = 79; continue; }; if (yych != 't') { gotoCase = 43; continue; }; case 79: ++cursor; this.setLexCondition(this._lexConditions.TAG); { this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.INITIAL; this.scriptEnded(cursor - 8); return cursor; } case 81: yych = this._charAt(++cursor); if (yych == 'L') { gotoCase = 82; continue; }; if (yych != 'l') { gotoCase = 43; continue; }; case 82: yych = this._charAt(++cursor); if (yych == 'E') { gotoCase = 83; continue; }; if (yych != 'e') { gotoCase = 43; continue; }; case 83: ++cursor; this.setLexCondition(this._lexConditions.TAG); { this.tokenType = "html-tag"; this._condition.parseCondition = this._parseConditions.INITIAL; this.styleSheetEnded(cursor - 7); return cursor; } case this.case_SSTRING: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 89; continue; }; { gotoCase = 88; continue; }; } else { if (yych <= '\r') { gotoCase = 89; continue; }; if (yych == '\'') { gotoCase = 91; continue; }; { gotoCase = 88; continue; }; } case 87: { return this._stringToken(cursor); } case 88: yych = this._charAt(++cursor); { gotoCase = 95; continue; }; case 89: ++cursor; { this.tokenType = null; return cursor; } case 91: ++cursor; case 92: this.setLexCondition(this._lexConditions.TAG); { return this._stringToken(cursor, true); } case 93: yych = this._charAt(++cursor); { gotoCase = 92; continue; }; case 94: ++cursor; yych = this._charAt(cursor); case 95: if (yych <= '\f') { if (yych == '\n') { gotoCase = 87; continue; }; { gotoCase = 94; continue; }; } else { if (yych <= '\r') { gotoCase = 87; continue; }; if (yych == '\'') { gotoCase = 93; continue; }; { gotoCase = 94; continue; }; } case this.case_TAG: yych = this._charAt(cursor); if (yych <= '&') { if (yych <= '\r') { if (yych == '\n') { gotoCase = 100; continue; }; if (yych >= '\r') { gotoCase = 100; continue; }; } else { if (yych <= ' ') { if (yych >= ' ') { gotoCase = 100; continue; }; } else { if (yych == '"') { gotoCase = 102; continue; }; } } } else { if (yych <= '>') { if (yych <= ';') { if (yych <= '\'') { gotoCase = 103; continue; }; } else { if (yych <= '<') { gotoCase = 100; continue; }; if (yych <= '=') { gotoCase = 104; continue; }; { gotoCase = 106; continue; }; } } else { if (yych <= '[') { if (yych >= '[') { gotoCase = 100; continue; }; } else { if (yych == ']') { gotoCase = 100; continue; }; } } } ++cursor; yych = this._charAt(cursor); { gotoCase = 119; continue; }; case 99: { if (this._condition.parseCondition === this._parseConditions.SCRIPT || this._condition.parseCondition === this._parseConditions.STYLE) { this.tokenType = null; return cursor; } if (this._condition.parseCondition === this._parseConditions.INITIAL) { this.tokenType = "html-tag"; this._setExpectingAttribute(); var token = this._line.substring(cursorOnEnter, cursor); if (token === "a") this._condition.parseCondition |= this._parseConditions.A_NODE; else if (this._condition.parseCondition & this._parseConditions.A_NODE) this._condition.parseCondition ^= this._parseConditions.A_NODE; } else if (this._isExpectingAttribute()) { var token = this._line.substring(cursorOnEnter, cursor); if (token === "href" || token === "src") this._condition.parseCondition |= this._parseConditions.LINKIFY; else if (this._condition.parseCondition |= this._parseConditions.LINKIFY) this._condition.parseCondition ^= this._parseConditions.LINKIFY; this.tokenType = "html-attribute-name"; } else if (this._isExpectingAttributeValue()) this.tokenType = this._attrValueTokenType(); else this.tokenType = null; return cursor; } case 100: ++cursor; { this.tokenType = null; return cursor; } case 102: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 115; continue; }; case 103: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 109; continue; }; case 104: ++cursor; { if (this._isExpectingAttribute()) this._setExpectingAttributeValue(); this.tokenType = null; return cursor; } case 106: ++cursor; this.setLexCondition(this._lexConditions.INITIAL); { this.tokenType = "html-tag"; if (this._condition.parseCondition & this._parseConditions.SCRIPT) { this.scriptStarted(cursor); return cursor; } if (this._condition.parseCondition & this._parseConditions.STYLE) { this.styleSheetStarted(cursor); return cursor; } this._condition.parseCondition = this._parseConditions.INITIAL; return cursor; } case 108: ++cursor; yych = this._charAt(cursor); case 109: if (yych <= '\f') { if (yych != '\n') { gotoCase = 108; continue; }; } else { if (yych <= '\r') { gotoCase = 110; continue; }; if (yych == '\'') { gotoCase = 112; continue; }; { gotoCase = 108; continue; }; } case 110: ++cursor; this.setLexCondition(this._lexConditions.SSTRING); { return this._stringToken(cursor); } case 112: ++cursor; { return this._stringToken(cursor, true); } case 114: ++cursor; yych = this._charAt(cursor); case 115: if (yych <= '\f') { if (yych != '\n') { gotoCase = 114; continue; }; } else { if (yych <= '\r') { gotoCase = 116; continue; }; if (yych == '"') { gotoCase = 112; continue; }; { gotoCase = 114; continue; }; } case 116: ++cursor; this.setLexCondition(this._lexConditions.DSTRING); { return this._stringToken(cursor); } case 118: ++cursor; yych = this._charAt(cursor); case 119: if (yych <= '"') { if (yych <= '\r') { if (yych == '\n') { gotoCase = 99; continue; }; if (yych <= '\f') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } else { if (yych == ' ') { gotoCase = 99; continue; }; if (yych <= '!') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } } else { if (yych <= '>') { if (yych == '\'') { gotoCase = 99; continue; }; if (yych <= ';') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } else { if (yych <= '[') { if (yych <= 'Z') { gotoCase = 118; continue; }; { gotoCase = 99; continue; }; } else { if (yych == ']') { gotoCase = 99; continue; }; { gotoCase = 118; continue; }; } } } } } }, __proto__: WebInspector.SourceTokenizer.prototype } WebInspector.SourceJavaScriptTokenizer = function() { WebInspector.SourceTokenizer.call(this); this._lexConditions = { DIV: 0, NODIV: 1, COMMENT: 2, DSTRING: 3, SSTRING: 4, REGEX: 5 }; this.case_DIV = 1000; this.case_NODIV = 1001; this.case_COMMENT = 1002; this.case_DSTRING = 1003; this.case_SSTRING = 1004; this.case_REGEX = 1005; this.condition = this.createInitialCondition(); } WebInspector.SourceJavaScriptTokenizer.Keywords = [ "null", "true", "false", "break", "case", "catch", "const", "default", "finally", "for", "instanceof", "new", "var", "continue", "function", "return", "void", "delete", "if", "this", "do", "while", "else", "in", "switch", "throw", "try", "typeof", "debugger", "class", "enum", "export", "extends", "import", "super", "get", "set", "with" ].keySet(); WebInspector.SourceJavaScriptTokenizer.prototype = { createInitialCondition: function() { return { lexCondition: this._lexConditions.NODIV }; }, nextToken: function(cursor) { var cursorOnEnter = cursor; var gotoCase = 1; var YYMARKER; while (1) { switch (gotoCase) { case 1: var yych; var yyaccept = 0; if (this.getLexCondition() < 3) { if (this.getLexCondition() < 1) { { gotoCase = this.case_DIV; continue; }; } else { if (this.getLexCondition() < 2) { { gotoCase = this.case_NODIV; continue; }; } else { { gotoCase = this.case_COMMENT; continue; }; } } } else { if (this.getLexCondition() < 4) { { gotoCase = this.case_DSTRING; continue; }; } else { if (this.getLexCondition() < 5) { { gotoCase = this.case_SSTRING; continue; }; } else { { gotoCase = this.case_REGEX; continue; }; } } } case this.case_COMMENT: yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 4; continue; }; { gotoCase = 3; continue; }; } else { if (yych <= '\r') { gotoCase = 4; continue; }; if (yych == '*') { gotoCase = 6; continue; }; { gotoCase = 3; continue; }; } case 2: { this.tokenType = "javascript-comment"; return cursor; } case 3: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 12; continue; }; case 4: ++cursor; { this.tokenType = null; return cursor; } case 6: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych == '*') { gotoCase = 9; continue; }; if (yych != '/') { gotoCase = 11; continue; }; case 7: ++cursor; this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-comment"; return cursor; } case 9: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 9; continue; }; if (yych == '/') { gotoCase = 7; continue; }; case 11: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 12: if (yych <= '\f') { if (yych == '\n') { gotoCase = 2; continue; }; { gotoCase = 11; continue; }; } else { if (yych <= '\r') { gotoCase = 2; continue; }; if (yych == '*') { gotoCase = 9; continue; }; { gotoCase = 11; continue; }; } case this.case_DIV: yych = this._charAt(cursor); if (yych <= '9') { if (yych <= '(') { if (yych <= '#') { if (yych <= ' ') { gotoCase = 15; continue; }; if (yych <= '!') { gotoCase = 17; continue; }; if (yych <= '"') { gotoCase = 19; continue; }; } else { if (yych <= '%') { if (yych <= '$') { gotoCase = 20; continue; }; { gotoCase = 22; continue; }; } else { if (yych <= '&') { gotoCase = 23; continue; }; if (yych <= '\'') { gotoCase = 24; continue; }; { gotoCase = 25; continue; }; } } } else { if (yych <= ',') { if (yych <= ')') { gotoCase = 26; continue; }; if (yych <= '*') { gotoCase = 28; continue; }; if (yych <= '+') { gotoCase = 29; continue; }; { gotoCase = 25; continue; }; } else { if (yych <= '.') { if (yych <= '-') { gotoCase = 30; continue; }; { gotoCase = 31; continue; }; } else { if (yych <= '/') { gotoCase = 32; continue; }; if (yych <= '0') { gotoCase = 34; continue; }; { gotoCase = 36; continue; }; } } } } else { if (yych <= '\\') { if (yych <= '>') { if (yych <= ';') { gotoCase = 25; continue; }; if (yych <= '<') { gotoCase = 37; continue; }; if (yych <= '=') { gotoCase = 38; continue; }; { gotoCase = 39; continue; }; } else { if (yych <= '@') { if (yych <= '?') { gotoCase = 25; continue; }; } else { if (yych <= 'Z') { gotoCase = 20; continue; }; if (yych <= '[') { gotoCase = 25; continue; }; { gotoCase = 40; continue; }; } } } else { if (yych <= 'z') { if (yych <= '^') { if (yych <= ']') { gotoCase = 25; continue; }; { gotoCase = 41; continue; }; } else { if (yych != '`') { gotoCase = 20; continue; }; } } else { if (yych <= '|') { if (yych <= '{') { gotoCase = 25; continue; }; { gotoCase = 42; continue; }; } else { if (yych <= '~') { gotoCase = 25; continue; }; if (yych >= 0x80) { gotoCase = 20; continue; }; } } } } case 15: ++cursor; case 16: { this.tokenType = null; return cursor; } case 17: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 115; continue; }; case 18: this.setLexCondition(this._lexConditions.NODIV); { var token = this._line.charAt(cursorOnEnter); if (token === "{") this.tokenType = "block-start"; else if (token === "}") this.tokenType = "block-end"; else this.tokenType = null; return cursor; } case 19: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 16; continue; }; if (yych == '\r') { gotoCase = 16; continue; }; { gotoCase = 107; continue; }; case 20: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 50; continue; }; case 21: { var token = this._line.substring(cursorOnEnter, cursor); if (WebInspector.SourceJavaScriptTokenizer.Keywords[token] === true && token !== "__proto__") this.tokenType = "javascript-keyword"; else this.tokenType = "javascript-ident"; return cursor; } case 22: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 23: yych = this._charAt(++cursor); if (yych == '&') { gotoCase = 43; continue; }; if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 24: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 16; continue; }; if (yych == '\r') { gotoCase = 16; continue; }; { gotoCase = 96; continue; }; case 25: yych = this._charAt(++cursor); { gotoCase = 18; continue; }; case 26: ++cursor; { this.tokenType = null; return cursor; } case 28: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 29: yych = this._charAt(++cursor); if (yych == '+') { gotoCase = 43; continue; }; if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 30: yych = this._charAt(++cursor); if (yych == '-') { gotoCase = 43; continue; }; if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 31: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 18; continue; }; if (yych <= '9') { gotoCase = 89; continue; }; { gotoCase = 18; continue; }; case 32: yyaccept = 2; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '.') { if (yych == '*') { gotoCase = 78; continue; }; } else { if (yych <= '/') { gotoCase = 80; continue; }; if (yych == '=') { gotoCase = 77; continue; }; } case 33: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = null; return cursor; } case 34: yyaccept = 3; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'E') { if (yych <= '/') { if (yych == '.') { gotoCase = 63; continue; }; } else { if (yych <= '7') { gotoCase = 72; continue; }; if (yych >= 'E') { gotoCase = 62; continue; }; } } else { if (yych <= 'd') { if (yych == 'X') { gotoCase = 74; continue; }; } else { if (yych <= 'e') { gotoCase = 62; continue; }; if (yych == 'x') { gotoCase = 74; continue; }; } } case 35: { this.tokenType = "javascript-number"; return cursor; } case 36: yyaccept = 3; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 63; continue; }; if (yych <= '/') { gotoCase = 35; continue; }; { gotoCase = 60; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 35; continue; }; { gotoCase = 62; continue; }; } else { if (yych == 'e') { gotoCase = 62; continue; }; { gotoCase = 35; continue; }; } } case 37: yych = this._charAt(++cursor); if (yych <= ';') { gotoCase = 18; continue; }; if (yych <= '<') { gotoCase = 59; continue; }; if (yych <= '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 38: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 58; continue; }; { gotoCase = 18; continue; }; case 39: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 18; continue; }; if (yych <= '=') { gotoCase = 43; continue; }; if (yych <= '>') { gotoCase = 56; continue; }; { gotoCase = 18; continue; }; case 40: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == 'u') { gotoCase = 44; continue; }; { gotoCase = 16; continue; }; case 41: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 42: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; if (yych != '|') { gotoCase = 18; continue; }; case 43: yych = this._charAt(++cursor); { gotoCase = 18; continue; }; case 44: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 46; continue; }; } else { if (yych <= 'F') { gotoCase = 46; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 46; continue; }; } case 45: cursor = YYMARKER; if (yyaccept <= 1) { if (yyaccept <= 0) { { gotoCase = 16; continue; }; } else { { gotoCase = 21; continue; }; } } else { if (yyaccept <= 2) { { gotoCase = 33; continue; }; } else { { gotoCase = 35; continue; }; } } case 46: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 47; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 47: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 48; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 48: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 49; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 49: yyaccept = 1; YYMARKER = ++cursor; yych = this._charAt(cursor); case 50: if (yych <= '[') { if (yych <= '/') { if (yych == '$') { gotoCase = 49; continue; }; { gotoCase = 21; continue; }; } else { if (yych <= '9') { gotoCase = 49; continue; }; if (yych <= '@') { gotoCase = 21; continue; }; if (yych <= 'Z') { gotoCase = 49; continue; }; { gotoCase = 21; continue; }; } } else { if (yych <= '_') { if (yych <= '\\') { gotoCase = 51; continue; }; if (yych <= '^') { gotoCase = 21; continue; }; { gotoCase = 49; continue; }; } else { if (yych <= '`') { gotoCase = 21; continue; }; if (yych <= 'z') { gotoCase = 49; continue; }; if (yych <= String.fromCharCode(0x7F)) { gotoCase = 21; continue; }; { gotoCase = 49; continue; }; } } case 51: ++cursor; yych = this._charAt(cursor); if (yych != 'u') { gotoCase = 45; continue; }; ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 53; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 53: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 54; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 54: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 55; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 55: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 49; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 49; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 49; continue; }; { gotoCase = 45; continue; }; } case 56: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 18; continue; }; if (yych <= '=') { gotoCase = 43; continue; }; if (yych >= '?') { gotoCase = 18; continue; }; yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 58: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 59: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case 60: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 63; continue; }; if (yych <= '/') { gotoCase = 35; continue; }; { gotoCase = 60; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 35; continue; }; } else { if (yych != 'e') { gotoCase = 35; continue; }; } } case 62: yych = this._charAt(++cursor); if (yych <= ',') { if (yych == '+') { gotoCase = 69; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= '-') { gotoCase = 69; continue; }; if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 70; continue; }; { gotoCase = 45; continue; }; } case 63: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 63; continue; }; { gotoCase = 35; continue; }; } else { if (yych <= 'E') { gotoCase = 65; continue; }; if (yych != 'e') { gotoCase = 35; continue; }; } case 65: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 45; continue; }; } else { if (yych <= '-') { gotoCase = 66; continue; }; if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 67; continue; }; { gotoCase = 45; continue; }; } case 66: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; case 67: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 67; continue; }; { gotoCase = 35; continue; }; case 69: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; case 70: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 70; continue; }; { gotoCase = 35; continue; }; case 72: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '7') { gotoCase = 72; continue; }; { gotoCase = 35; continue; }; case 74: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 75; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 75: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 75; continue; }; { gotoCase = 35; continue; }; } else { if (yych <= 'F') { gotoCase = 75; continue; }; if (yych <= '`') { gotoCase = 35; continue; }; if (yych <= 'f') { gotoCase = 75; continue; }; { gotoCase = 35; continue; }; } case 77: yych = this._charAt(++cursor); { gotoCase = 33; continue; }; case 78: ++cursor; yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 85; continue; }; { gotoCase = 78; continue; }; } else { if (yych <= '\r') { gotoCase = 85; continue; }; if (yych == '*') { gotoCase = 83; continue; }; { gotoCase = 78; continue; }; } case 80: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 82; continue; }; if (yych != '\r') { gotoCase = 80; continue; }; case 82: { this.tokenType = "javascript-comment"; return cursor; } case 83: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 83; continue; }; if (yych == '/') { gotoCase = 87; continue; }; { gotoCase = 78; continue; }; case 85: ++cursor; this.setLexCondition(this._lexConditions.COMMENT); { this.tokenType = "javascript-comment"; return cursor; } case 87: ++cursor; { this.tokenType = "javascript-comment"; return cursor; } case 89: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 89; continue; }; { gotoCase = 35; continue; }; } else { if (yych <= 'E') { gotoCase = 91; continue; }; if (yych != 'e') { gotoCase = 35; continue; }; } case 91: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 45; continue; }; } else { if (yych <= '-') { gotoCase = 92; continue; }; if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 93; continue; }; { gotoCase = 45; continue; }; } case 92: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; case 93: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 35; continue; }; if (yych <= '9') { gotoCase = 93; continue; }; { gotoCase = 35; continue; }; case 95: ++cursor; yych = this._charAt(cursor); case 96: if (yych <= '\r') { if (yych == '\n') { gotoCase = 45; continue; }; if (yych <= '\f') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 95; continue; }; { gotoCase = 98; continue; }; } else { if (yych != '\\') { gotoCase = 95; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 45; continue; }; { gotoCase = 101; continue; }; } else { if (yych == '\r') { gotoCase = 101; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 95; continue; }; if (yych <= '&') { gotoCase = 45; continue; }; { gotoCase = 95; continue; }; } else { if (yych == '\\') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 95; continue; }; if (yych <= 'e') { gotoCase = 45; continue; }; { gotoCase = 95; continue; }; } else { if (yych == 'n') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 45; continue; }; { gotoCase = 95; continue; }; } else { if (yych <= 'u') { gotoCase = 100; continue; }; if (yych <= 'v') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } } } case 98: ++cursor; { this.tokenType = "javascript-string"; return cursor; } case 100: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 103; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 103; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 103; continue; }; { gotoCase = 45; continue; }; } case 101: ++cursor; this.setLexCondition(this._lexConditions.SSTRING); { this.tokenType = "javascript-string"; return cursor; } case 103: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 104; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 104: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 105; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 105: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 95; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 95; continue; }; { gotoCase = 45; continue; }; } case 106: ++cursor; yych = this._charAt(cursor); case 107: if (yych <= '\r') { if (yych == '\n') { gotoCase = 45; continue; }; if (yych <= '\f') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 106; continue; }; { gotoCase = 98; continue; }; } else { if (yych != '\\') { gotoCase = 106; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 45; continue; }; { gotoCase = 110; continue; }; } else { if (yych == '\r') { gotoCase = 110; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 106; continue; }; if (yych <= '&') { gotoCase = 45; continue; }; { gotoCase = 106; continue; }; } else { if (yych == '\\') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 106; continue; }; if (yych <= 'e') { gotoCase = 45; continue; }; { gotoCase = 106; continue; }; } else { if (yych == 'n') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 45; continue; }; { gotoCase = 106; continue; }; } else { if (yych <= 'u') { gotoCase = 109; continue; }; if (yych <= 'v') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } } } case 109: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 112; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 112; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 112; continue; }; { gotoCase = 45; continue; }; } case 110: ++cursor; this.setLexCondition(this._lexConditions.DSTRING); { this.tokenType = "javascript-string"; return cursor; } case 112: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 113; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 113: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych >= ':') { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 114; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych >= 'g') { gotoCase = 45; continue; }; } case 114: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 45; continue; }; if (yych <= '9') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } else { if (yych <= 'F') { gotoCase = 106; continue; }; if (yych <= '`') { gotoCase = 45; continue; }; if (yych <= 'f') { gotoCase = 106; continue; }; { gotoCase = 45; continue; }; } case 115: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 43; continue; }; { gotoCase = 18; continue; }; case this.case_DSTRING: yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 120; continue; }; if (yych <= '\f') { gotoCase = 119; continue; }; { gotoCase = 120; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 119; continue; }; { gotoCase = 122; continue; }; } else { if (yych == '\\') { gotoCase = 124; continue; }; { gotoCase = 119; continue; }; } } case 118: { this.tokenType = "javascript-string"; return cursor; } case 119: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 126; continue; }; case 120: ++cursor; case 121: { this.tokenType = null; return cursor; } case 122: ++cursor; case 123: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-string"; return cursor; } case 124: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 125; continue; }; if (yych <= '&') { gotoCase = 121; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 121; continue; }; } else { if (yych != 'b') { gotoCase = 121; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych >= 'g') { gotoCase = 121; continue; }; } else { if (yych <= 'n') { gotoCase = 125; continue; }; if (yych <= 'q') { gotoCase = 121; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 121; continue; }; } else { if (yych <= 'u') { gotoCase = 127; continue; }; if (yych >= 'w') { gotoCase = 121; continue; }; } } } case 125: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 126: if (yych <= '\r') { if (yych == '\n') { gotoCase = 118; continue; }; if (yych <= '\f') { gotoCase = 125; continue; }; { gotoCase = 118; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 125; continue; }; { gotoCase = 133; continue; }; } else { if (yych == '\\') { gotoCase = 132; continue; }; { gotoCase = 125; continue; }; } } case 127: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych <= '9') { gotoCase = 129; continue; }; } else { if (yych <= 'F') { gotoCase = 129; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych <= 'f') { gotoCase = 129; continue; }; } case 128: cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 118; continue; }; } else { { gotoCase = 121; continue; }; } case 129: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych >= ':') { gotoCase = 128; continue; }; } else { if (yych <= 'F') { gotoCase = 130; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych >= 'g') { gotoCase = 128; continue; }; } case 130: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych >= ':') { gotoCase = 128; continue; }; } else { if (yych <= 'F') { gotoCase = 131; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych >= 'g') { gotoCase = 128; continue; }; } case 131: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 128; continue; }; if (yych <= '9') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } else { if (yych <= 'F') { gotoCase = 125; continue; }; if (yych <= '`') { gotoCase = 128; continue; }; if (yych <= 'f') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } case 132: ++cursor; yych = this._charAt(cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 125; continue; }; if (yych <= '&') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } else { if (yych == 'b') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych <= 'f') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } else { if (yych <= 'n') { gotoCase = 125; continue; }; if (yych <= 'q') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 128; continue; }; { gotoCase = 125; continue; }; } else { if (yych <= 'u') { gotoCase = 127; continue; }; if (yych <= 'v') { gotoCase = 125; continue; }; { gotoCase = 128; continue; }; } } } case 133: ++cursor; yych = this._charAt(cursor); { gotoCase = 123; continue; }; case this.case_NODIV: yych = this._charAt(cursor); if (yych <= '9') { if (yych <= '(') { if (yych <= '#') { if (yych <= ' ') { gotoCase = 136; continue; }; if (yych <= '!') { gotoCase = 138; continue; }; if (yych <= '"') { gotoCase = 140; continue; }; } else { if (yych <= '%') { if (yych <= '$') { gotoCase = 141; continue; }; { gotoCase = 143; continue; }; } else { if (yych <= '&') { gotoCase = 144; continue; }; if (yych <= '\'') { gotoCase = 145; continue; }; { gotoCase = 146; continue; }; } } } else { if (yych <= ',') { if (yych <= ')') { gotoCase = 147; continue; }; if (yych <= '*') { gotoCase = 149; continue; }; if (yych <= '+') { gotoCase = 150; continue; }; { gotoCase = 146; continue; }; } else { if (yych <= '.') { if (yych <= '-') { gotoCase = 151; continue; }; { gotoCase = 152; continue; }; } else { if (yych <= '/') { gotoCase = 153; continue; }; if (yych <= '0') { gotoCase = 154; continue; }; { gotoCase = 156; continue; }; } } } } else { if (yych <= '\\') { if (yych <= '>') { if (yych <= ';') { gotoCase = 146; continue; }; if (yych <= '<') { gotoCase = 157; continue; }; if (yych <= '=') { gotoCase = 158; continue; }; { gotoCase = 159; continue; }; } else { if (yych <= '@') { if (yych <= '?') { gotoCase = 146; continue; }; } else { if (yych <= 'Z') { gotoCase = 141; continue; }; if (yych <= '[') { gotoCase = 146; continue; }; { gotoCase = 160; continue; }; } } } else { if (yych <= 'z') { if (yych <= '^') { if (yych <= ']') { gotoCase = 146; continue; }; { gotoCase = 161; continue; }; } else { if (yych != '`') { gotoCase = 141; continue; }; } } else { if (yych <= '|') { if (yych <= '{') { gotoCase = 146; continue; }; { gotoCase = 162; continue; }; } else { if (yych <= '~') { gotoCase = 146; continue; }; if (yych >= 0x80) { gotoCase = 141; continue; }; } } } } case 136: ++cursor; case 137: { this.tokenType = null; return cursor; } case 138: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 260; continue; }; case 139: { var token = this._line.charAt(cursorOnEnter); if (token === "{") this.tokenType = "block-start"; else if (token === "}") this.tokenType = "block-end"; else this.tokenType = null; return cursor; } case 140: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 137; continue; }; if (yych == '\r') { gotoCase = 137; continue; }; { gotoCase = 252; continue; }; case 141: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 170; continue; }; case 142: this.setLexCondition(this._lexConditions.DIV); { var token = this._line.substring(cursorOnEnter, cursor); if (WebInspector.SourceJavaScriptTokenizer.Keywords[token] === true && token !== "__proto__") this.tokenType = "javascript-keyword"; else this.tokenType = "javascript-ident"; return cursor; } case 143: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 144: yych = this._charAt(++cursor); if (yych == '&') { gotoCase = 163; continue; }; if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 145: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == '\n') { gotoCase = 137; continue; }; if (yych == '\r') { gotoCase = 137; continue; }; { gotoCase = 241; continue; }; case 146: yych = this._charAt(++cursor); { gotoCase = 139; continue; }; case 147: ++cursor; this.setLexCondition(this._lexConditions.DIV); { this.tokenType = null; return cursor; } case 149: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 150: yych = this._charAt(++cursor); if (yych == '+') { gotoCase = 163; continue; }; if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 151: yych = this._charAt(++cursor); if (yych == '-') { gotoCase = 163; continue; }; if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 152: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 139; continue; }; if (yych <= '9') { gotoCase = 234; continue; }; { gotoCase = 139; continue; }; case 153: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 137; continue; }; { gotoCase = 197; continue; }; } else { if (yych <= '\r') { gotoCase = 137; continue; }; if (yych <= ')') { gotoCase = 197; continue; }; { gotoCase = 202; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 204; continue; }; { gotoCase = 197; continue; }; } else { if (yych <= '[') { gotoCase = 200; continue; }; if (yych <= '\\') { gotoCase = 199; continue; }; if (yych <= ']') { gotoCase = 137; continue; }; { gotoCase = 197; continue; }; } } case 154: yyaccept = 2; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'E') { if (yych <= '/') { if (yych == '.') { gotoCase = 183; continue; }; } else { if (yych <= '7') { gotoCase = 192; continue; }; if (yych >= 'E') { gotoCase = 182; continue; }; } } else { if (yych <= 'd') { if (yych == 'X') { gotoCase = 194; continue; }; } else { if (yych <= 'e') { gotoCase = 182; continue; }; if (yych == 'x') { gotoCase = 194; continue; }; } } case 155: this.setLexCondition(this._lexConditions.DIV); { this.tokenType = "javascript-number"; return cursor; } case 156: yyaccept = 2; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 183; continue; }; if (yych <= '/') { gotoCase = 155; continue; }; { gotoCase = 180; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 155; continue; }; { gotoCase = 182; continue; }; } else { if (yych == 'e') { gotoCase = 182; continue; }; { gotoCase = 155; continue; }; } } case 157: yych = this._charAt(++cursor); if (yych <= ';') { gotoCase = 139; continue; }; if (yych <= '<') { gotoCase = 179; continue; }; if (yych <= '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 158: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 178; continue; }; { gotoCase = 139; continue; }; case 159: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 139; continue; }; if (yych <= '=') { gotoCase = 163; continue; }; if (yych <= '>') { gotoCase = 176; continue; }; { gotoCase = 139; continue; }; case 160: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); if (yych == 'u') { gotoCase = 164; continue; }; { gotoCase = 137; continue; }; case 161: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 162: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; if (yych != '|') { gotoCase = 139; continue; }; case 163: yych = this._charAt(++cursor); { gotoCase = 139; continue; }; case 164: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 166; continue; }; } else { if (yych <= 'F') { gotoCase = 166; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 166; continue; }; } case 165: cursor = YYMARKER; if (yyaccept <= 1) { if (yyaccept <= 0) { { gotoCase = 137; continue; }; } else { { gotoCase = 142; continue; }; } } else { if (yyaccept <= 2) { { gotoCase = 155; continue; }; } else { { gotoCase = 217; continue; }; } } case 166: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 167; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 167: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 168; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 168: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 169; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 169: yyaccept = 1; YYMARKER = ++cursor; yych = this._charAt(cursor); case 170: if (yych <= '[') { if (yych <= '/') { if (yych == '$') { gotoCase = 169; continue; }; { gotoCase = 142; continue; }; } else { if (yych <= '9') { gotoCase = 169; continue; }; if (yych <= '@') { gotoCase = 142; continue; }; if (yych <= 'Z') { gotoCase = 169; continue; }; { gotoCase = 142; continue; }; } } else { if (yych <= '_') { if (yych <= '\\') { gotoCase = 171; continue; }; if (yych <= '^') { gotoCase = 142; continue; }; { gotoCase = 169; continue; }; } else { if (yych <= '`') { gotoCase = 142; continue; }; if (yych <= 'z') { gotoCase = 169; continue; }; if (yych <= String.fromCharCode(0x7F)) { gotoCase = 142; continue; }; { gotoCase = 169; continue; }; } } case 171: ++cursor; yych = this._charAt(cursor); if (yych != 'u') { gotoCase = 165; continue; }; ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 173; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 173: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 174; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 174: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 175; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 175: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 169; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 169; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 169; continue; }; { gotoCase = 165; continue; }; } case 176: yych = this._charAt(++cursor); if (yych <= '<') { gotoCase = 139; continue; }; if (yych <= '=') { gotoCase = 163; continue; }; if (yych >= '?') { gotoCase = 139; continue; }; yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 178: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 179: yych = this._charAt(++cursor); if (yych == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case 180: yyaccept = 2; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '9') { if (yych == '.') { gotoCase = 183; continue; }; if (yych <= '/') { gotoCase = 155; continue; }; { gotoCase = 180; continue; }; } else { if (yych <= 'E') { if (yych <= 'D') { gotoCase = 155; continue; }; } else { if (yych != 'e') { gotoCase = 155; continue; }; } } case 182: yych = this._charAt(++cursor); if (yych <= ',') { if (yych == '+') { gotoCase = 189; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= '-') { gotoCase = 189; continue; }; if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 190; continue; }; { gotoCase = 165; continue; }; } case 183: yyaccept = 2; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 183; continue; }; { gotoCase = 155; continue; }; } else { if (yych <= 'E') { gotoCase = 185; continue; }; if (yych != 'e') { gotoCase = 155; continue; }; } case 185: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 165; continue; }; } else { if (yych <= '-') { gotoCase = 186; continue; }; if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 187; continue; }; { gotoCase = 165; continue; }; } case 186: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; case 187: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 187; continue; }; { gotoCase = 155; continue; }; case 189: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; case 190: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 190; continue; }; { gotoCase = 155; continue; }; case 192: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '7') { gotoCase = 192; continue; }; { gotoCase = 155; continue; }; case 194: yych = this._charAt(++cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 195; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 195: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 195; continue; }; { gotoCase = 155; continue; }; } else { if (yych <= 'F') { gotoCase = 195; continue; }; if (yych <= '`') { gotoCase = 155; continue; }; if (yych <= 'f') { gotoCase = 195; continue; }; { gotoCase = 155; continue; }; } case 197: ++cursor; yych = this._charAt(cursor); if (yych <= '.') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 197; continue; }; { gotoCase = 165; continue; }; } else { if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= '[') { if (yych <= '/') { gotoCase = 220; continue; }; if (yych <= 'Z') { gotoCase = 197; continue; }; { gotoCase = 228; continue; }; } else { if (yych <= '\\') { gotoCase = 227; continue; }; if (yych <= ']') { gotoCase = 165; continue; }; { gotoCase = 197; continue; }; } } case 199: yych = this._charAt(++cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 197; continue; }; case 200: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 200; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 200; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 165; continue; }; { gotoCase = 200; continue; }; } else { if (yych <= '\\') { gotoCase = 215; continue; }; if (yych <= ']') { gotoCase = 213; continue; }; { gotoCase = 200; continue; }; } } case 202: ++cursor; yych = this._charAt(cursor); if (yych <= '\f') { if (yych == '\n') { gotoCase = 209; continue; }; { gotoCase = 202; continue; }; } else { if (yych <= '\r') { gotoCase = 209; continue; }; if (yych == '*') { gotoCase = 207; continue; }; { gotoCase = 202; continue; }; } case 204: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 206; continue; }; if (yych != '\r') { gotoCase = 204; continue; }; case 206: { this.tokenType = "javascript-comment"; return cursor; } case 207: ++cursor; yych = this._charAt(cursor); if (yych == '*') { gotoCase = 207; continue; }; if (yych == '/') { gotoCase = 211; continue; }; { gotoCase = 202; continue; }; case 209: ++cursor; this.setLexCondition(this._lexConditions.COMMENT); { this.tokenType = "javascript-comment"; return cursor; } case 211: ++cursor; { this.tokenType = "javascript-comment"; return cursor; } case 213: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 213; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 213; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 220; continue; }; { gotoCase = 213; continue; }; } else { if (yych <= '[') { gotoCase = 218; continue; }; if (yych <= '\\') { gotoCase = 216; continue; }; { gotoCase = 213; continue; }; } } case 215: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 200; continue; }; case 216: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych != '\r') { gotoCase = 213; continue; }; case 217: this.setLexCondition(this._lexConditions.REGEX); { this.tokenType = "javascript-regexp"; return cursor; } case 218: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 218; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 218; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 165; continue; }; { gotoCase = 218; continue; }; } else { if (yych <= '\\') { gotoCase = 225; continue; }; if (yych <= ']') { gotoCase = 223; continue; }; { gotoCase = 218; continue; }; } } case 220: ++cursor; yych = this._charAt(cursor); if (yych <= 'h') { if (yych == 'g') { gotoCase = 220; continue; }; } else { if (yych <= 'i') { gotoCase = 220; continue; }; if (yych == 'm') { gotoCase = 220; continue; }; } { this.tokenType = "javascript-regexp"; return cursor; } case 223: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 223; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 223; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 220; continue; }; { gotoCase = 223; continue; }; } else { if (yych <= '[') { gotoCase = 218; continue; }; if (yych <= '\\') { gotoCase = 226; continue; }; { gotoCase = 223; continue; }; } } case 225: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 218; continue; }; case 226: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych == '\r') { gotoCase = 217; continue; }; { gotoCase = 223; continue; }; case 227: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych == '\r') { gotoCase = 217; continue; }; { gotoCase = 197; continue; }; case 228: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 228; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 228; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 165; continue; }; { gotoCase = 228; continue; }; } else { if (yych <= '\\') { gotoCase = 232; continue; }; if (yych >= '^') { gotoCase = 228; continue; }; } } case 230: ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 165; continue; }; { gotoCase = 230; continue; }; } else { if (yych <= '\r') { gotoCase = 165; continue; }; if (yych <= ')') { gotoCase = 230; continue; }; { gotoCase = 197; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 220; continue; }; { gotoCase = 230; continue; }; } else { if (yych <= '[') { gotoCase = 228; continue; }; if (yych <= '\\') { gotoCase = 233; continue; }; { gotoCase = 230; continue; }; } } case 232: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 165; continue; }; if (yych == '\r') { gotoCase = 165; continue; }; { gotoCase = 228; continue; }; case 233: yyaccept = 3; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 217; continue; }; if (yych == '\r') { gotoCase = 217; continue; }; { gotoCase = 230; continue; }; case 234: yyaccept = 2; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= 'D') { if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 234; continue; }; { gotoCase = 155; continue; }; } else { if (yych <= 'E') { gotoCase = 236; continue; }; if (yych != 'e') { gotoCase = 155; continue; }; } case 236: yych = this._charAt(++cursor); if (yych <= ',') { if (yych != '+') { gotoCase = 165; continue; }; } else { if (yych <= '-') { gotoCase = 237; continue; }; if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 238; continue; }; { gotoCase = 165; continue; }; } case 237: yych = this._charAt(++cursor); if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; case 238: ++cursor; yych = this._charAt(cursor); if (yych <= '/') { gotoCase = 155; continue; }; if (yych <= '9') { gotoCase = 238; continue; }; { gotoCase = 155; continue; }; case 240: ++cursor; yych = this._charAt(cursor); case 241: if (yych <= '\r') { if (yych == '\n') { gotoCase = 165; continue; }; if (yych <= '\f') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 240; continue; }; { gotoCase = 243; continue; }; } else { if (yych != '\\') { gotoCase = 240; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 165; continue; }; { gotoCase = 246; continue; }; } else { if (yych == '\r') { gotoCase = 246; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 240; continue; }; if (yych <= '&') { gotoCase = 165; continue; }; { gotoCase = 240; continue; }; } else { if (yych == '\\') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 240; continue; }; if (yych <= 'e') { gotoCase = 165; continue; }; { gotoCase = 240; continue; }; } else { if (yych == 'n') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 165; continue; }; { gotoCase = 240; continue; }; } else { if (yych <= 'u') { gotoCase = 245; continue; }; if (yych <= 'v') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } } } case 243: ++cursor; { this.tokenType = "javascript-string"; return cursor; } case 245: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 248; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 248; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 248; continue; }; { gotoCase = 165; continue; }; } case 246: ++cursor; this.setLexCondition(this._lexConditions.SSTRING); { this.tokenType = "javascript-string"; return cursor; } case 248: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 249; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 249: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 250; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 250: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 240; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 240; continue; }; { gotoCase = 165; continue; }; } case 251: ++cursor; yych = this._charAt(cursor); case 252: if (yych <= '\r') { if (yych == '\n') { gotoCase = 165; continue; }; if (yych <= '\f') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= '"') { if (yych <= '!') { gotoCase = 251; continue; }; { gotoCase = 243; continue; }; } else { if (yych != '\\') { gotoCase = 251; continue; }; } } ++cursor; yych = this._charAt(cursor); if (yych <= 'a') { if (yych <= '!') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 165; continue; }; { gotoCase = 255; continue; }; } else { if (yych == '\r') { gotoCase = 255; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= '\'') { if (yych <= '"') { gotoCase = 251; continue; }; if (yych <= '&') { gotoCase = 165; continue; }; { gotoCase = 251; continue; }; } else { if (yych == '\\') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } } } else { if (yych <= 'q') { if (yych <= 'f') { if (yych <= 'b') { gotoCase = 251; continue; }; if (yych <= 'e') { gotoCase = 165; continue; }; { gotoCase = 251; continue; }; } else { if (yych == 'n') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } } else { if (yych <= 't') { if (yych == 's') { gotoCase = 165; continue; }; { gotoCase = 251; continue; }; } else { if (yych <= 'u') { gotoCase = 254; continue; }; if (yych <= 'v') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } } } case 254: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 257; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 257; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 257; continue; }; { gotoCase = 165; continue; }; } case 255: ++cursor; this.setLexCondition(this._lexConditions.DSTRING); { this.tokenType = "javascript-string"; return cursor; } case 257: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 258; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 258: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych >= ':') { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 259; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych >= 'g') { gotoCase = 165; continue; }; } case 259: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 165; continue; }; if (yych <= '9') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } else { if (yych <= 'F') { gotoCase = 251; continue; }; if (yych <= '`') { gotoCase = 165; continue; }; if (yych <= 'f') { gotoCase = 251; continue; }; { gotoCase = 165; continue; }; } case 260: ++cursor; if ((yych = this._charAt(cursor)) == '=') { gotoCase = 163; continue; }; { gotoCase = 139; continue; }; case this.case_REGEX: yych = this._charAt(cursor); if (yych <= '.') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 264; continue; }; { gotoCase = 265; continue; }; } else { if (yych == '\r') { gotoCase = 265; continue; }; { gotoCase = 264; continue; }; } } else { if (yych <= '[') { if (yych <= '/') { gotoCase = 267; continue; }; if (yych <= 'Z') { gotoCase = 264; continue; }; { gotoCase = 269; continue; }; } else { if (yych <= '\\') { gotoCase = 270; continue; }; if (yych <= ']') { gotoCase = 265; continue; }; { gotoCase = 264; continue; }; } } case 263: { this.tokenType = "javascript-regexp"; return cursor; } case 264: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 272; continue; }; case 265: ++cursor; case 266: { this.tokenType = null; return cursor; } case 267: ++cursor; yych = this._charAt(cursor); { gotoCase = 278; continue; }; case 268: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-regexp"; return cursor; } case 269: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 266; continue; }; if (yych <= '\f') { gotoCase = 276; continue; }; { gotoCase = 266; continue; }; } else { if (yych <= '*') { if (yych <= ')') { gotoCase = 276; continue; }; { gotoCase = 266; continue; }; } else { if (yych == '/') { gotoCase = 266; continue; }; { gotoCase = 276; continue; }; } } case 270: yych = this._charAt(++cursor); if (yych == '\n') { gotoCase = 266; continue; }; if (yych == '\r') { gotoCase = 266; continue; }; case 271: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 272: if (yych <= '.') { if (yych <= '\n') { if (yych <= '\t') { gotoCase = 271; continue; }; { gotoCase = 263; continue; }; } else { if (yych == '\r') { gotoCase = 263; continue; }; { gotoCase = 271; continue; }; } } else { if (yych <= '[') { if (yych <= '/') { gotoCase = 277; continue; }; if (yych <= 'Z') { gotoCase = 271; continue; }; { gotoCase = 275; continue; }; } else { if (yych <= '\\') { gotoCase = 273; continue; }; if (yych <= ']') { gotoCase = 263; continue; }; { gotoCase = 271; continue; }; } } case 273: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 274; continue; }; if (yych != '\r') { gotoCase = 271; continue; }; case 274: cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 263; continue; }; } else { { gotoCase = 266; continue; }; } case 275: ++cursor; yych = this._charAt(cursor); case 276: if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 274; continue; }; { gotoCase = 275; continue; }; } else { if (yych <= '\r') { gotoCase = 274; continue; }; if (yych <= ')') { gotoCase = 275; continue; }; { gotoCase = 274; continue; }; } } else { if (yych <= '[') { if (yych == '/') { gotoCase = 274; continue; }; { gotoCase = 275; continue; }; } else { if (yych <= '\\') { gotoCase = 281; continue; }; if (yych <= ']') { gotoCase = 279; continue; }; { gotoCase = 275; continue; }; } } case 277: ++cursor; yych = this._charAt(cursor); case 278: if (yych <= 'h') { if (yych == 'g') { gotoCase = 277; continue; }; { gotoCase = 268; continue; }; } else { if (yych <= 'i') { gotoCase = 277; continue; }; if (yych == 'm') { gotoCase = 277; continue; }; { gotoCase = 268; continue; }; } case 279: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); if (yych <= '*') { if (yych <= '\f') { if (yych == '\n') { gotoCase = 263; continue; }; { gotoCase = 279; continue; }; } else { if (yych <= '\r') { gotoCase = 263; continue; }; if (yych <= ')') { gotoCase = 279; continue; }; { gotoCase = 271; continue; }; } } else { if (yych <= 'Z') { if (yych == '/') { gotoCase = 277; continue; }; { gotoCase = 279; continue; }; } else { if (yych <= '[') { gotoCase = 275; continue; }; if (yych <= '\\') { gotoCase = 282; continue; }; { gotoCase = 279; continue; }; } } case 281: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 274; continue; }; if (yych == '\r') { gotoCase = 274; continue; }; { gotoCase = 275; continue; }; case 282: ++cursor; yych = this._charAt(cursor); if (yych == '\n') { gotoCase = 274; continue; }; if (yych == '\r') { gotoCase = 274; continue; }; { gotoCase = 279; continue; }; case this.case_SSTRING: yych = this._charAt(cursor); if (yych <= '\r') { if (yych == '\n') { gotoCase = 287; continue; }; if (yych <= '\f') { gotoCase = 286; continue; }; { gotoCase = 287; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 286; continue; }; { gotoCase = 289; continue; }; } else { if (yych == '\\') { gotoCase = 291; continue; }; { gotoCase = 286; continue; }; } } case 285: { this.tokenType = "javascript-string"; return cursor; } case 286: yyaccept = 0; yych = this._charAt(YYMARKER = ++cursor); { gotoCase = 293; continue; }; case 287: ++cursor; case 288: { this.tokenType = null; return cursor; } case 289: ++cursor; case 290: this.setLexCondition(this._lexConditions.NODIV); { this.tokenType = "javascript-string"; return cursor; } case 291: yyaccept = 1; yych = this._charAt(YYMARKER = ++cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 292; continue; }; if (yych <= '&') { gotoCase = 288; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 288; continue; }; } else { if (yych != 'b') { gotoCase = 288; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych >= 'g') { gotoCase = 288; continue; }; } else { if (yych <= 'n') { gotoCase = 292; continue; }; if (yych <= 'q') { gotoCase = 288; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 288; continue; }; } else { if (yych <= 'u') { gotoCase = 294; continue; }; if (yych >= 'w') { gotoCase = 288; continue; }; } } } case 292: yyaccept = 0; YYMARKER = ++cursor; yych = this._charAt(cursor); case 293: if (yych <= '\r') { if (yych == '\n') { gotoCase = 285; continue; }; if (yych <= '\f') { gotoCase = 292; continue; }; { gotoCase = 285; continue; }; } else { if (yych <= '\'') { if (yych <= '&') { gotoCase = 292; continue; }; { gotoCase = 300; continue; }; } else { if (yych == '\\') { gotoCase = 299; continue; }; { gotoCase = 292; continue; }; } } case 294: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych <= '9') { gotoCase = 296; continue; }; } else { if (yych <= 'F') { gotoCase = 296; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych <= 'f') { gotoCase = 296; continue; }; } case 295: cursor = YYMARKER; if (yyaccept <= 0) { { gotoCase = 285; continue; }; } else { { gotoCase = 288; continue; }; } case 296: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych >= ':') { gotoCase = 295; continue; }; } else { if (yych <= 'F') { gotoCase = 297; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych >= 'g') { gotoCase = 295; continue; }; } case 297: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych >= ':') { gotoCase = 295; continue; }; } else { if (yych <= 'F') { gotoCase = 298; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych >= 'g') { gotoCase = 295; continue; }; } case 298: ++cursor; yych = this._charAt(cursor); if (yych <= '@') { if (yych <= '/') { gotoCase = 295; continue; }; if (yych <= '9') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } else { if (yych <= 'F') { gotoCase = 292; continue; }; if (yych <= '`') { gotoCase = 295; continue; }; if (yych <= 'f') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } case 299: ++cursor; yych = this._charAt(cursor); if (yych <= 'e') { if (yych <= '\'') { if (yych == '"') { gotoCase = 292; continue; }; if (yych <= '&') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } else { if (yych <= '\\') { if (yych <= '[') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } else { if (yych == 'b') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } } } else { if (yych <= 'r') { if (yych <= 'm') { if (yych <= 'f') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } else { if (yych <= 'n') { gotoCase = 292; continue; }; if (yych <= 'q') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } } else { if (yych <= 't') { if (yych <= 's') { gotoCase = 295; continue; }; { gotoCase = 292; continue; }; } else { if (yych <= 'u') { gotoCase = 294; continue; }; if (yych <= 'v') { gotoCase = 292; continue; }; { gotoCase = 295; continue; }; } } } case 300: ++cursor; yych = this._charAt(cursor); { gotoCase = 290; continue; }; } } }, __proto__: WebInspector.SourceTokenizer.prototype } WebInspector.FileSystemModel = function() { WebInspector.Object.call(this); this._originForFrameId = {}; this._frameIdsForOrigin = {}; this._fileSystemsForOrigin = {}; WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this); FileSystemAgent.enable(); if (WebInspector.resourceTreeModel.mainFrame) this._attachFrameRecursively(WebInspector.resourceTreeModel.mainFrame); } WebInspector.FileSystemModel.prototype = { _frameAdded: function(event) { var frame = (event.data); this._attachFrameRecursively(frame); }, _frameNavigated: function(event) { var frame = (event.data); this._attachFrameRecursively(frame); }, _frameDetached: function(event) { var frame = (event.data); this._detachFrameRecursively(frame); }, _attachFrame: function(frame) { if (this._originForFrameId[frame.id]) this._detachFrameRecursively(frame); if (frame.securityOrigin === "null") return; this._originForFrameId[frame.id] = frame.securityOrigin; var newOrigin = false; if (!this._frameIdsForOrigin[frame.securityOrigin]) { this._frameIdsForOrigin[frame.securityOrigin] = {}; newOrigin = true; } this._frameIdsForOrigin[frame.securityOrigin][frame.id] = frame.id; if (newOrigin) this._originAdded(frame.securityOrigin); }, _attachFrameRecursively: function(frame) { this._attachFrame(frame); for (var i = 0; i < frame.childFrames.length; ++i) this._attachFrameRecursively(frame.childFrames[i]); }, _detachFrame: function(frame) { if (!this._originForFrameId[frame.id]) return; var origin = this._originForFrameId[frame.id]; delete this._originForFrameId[frame.id]; delete this._frameIdsForOrigin[origin][frame.id]; var lastOrigin = Object.isEmpty(this._frameIdsForOrigin[origin]); if (lastOrigin) { delete this._frameIdsForOrigin[origin]; this._originRemoved(origin); } }, _detachFrameRecursively: function(frame) { for (var i = 0; i < frame.childFrames.length; ++i) this._detachFrameRecursively(frame.childFrames[i]); this._detachFrame(frame); }, _originAdded: function(origin) { this._fileSystemsForOrigin[origin] = {}; var types = ["persistent", "temporary"]; for (var i = 0; i < types.length; ++i) this._requestFileSystemRoot(origin, types[i], this._fileSystemRootReceived.bind(this, origin, types[i], this._fileSystemsForOrigin[origin])); }, _requestFileSystemRoot: function(origin, type, callback) { function innerCallback(error, errorCode, backendRootEntry) { if (error) { callback(FileError.SECURITY_ERR); return; } callback(errorCode, backendRootEntry); } FileSystemAgent.requestFileSystemRoot(origin, type, innerCallback.bind(this)); }, _originRemoved: function(origin) { for (var type in this._fileSystemsForOrigin[origin]) { var fileSystem = this._fileSystemsForOrigin[origin][type]; delete this._fileSystemsForOrigin[origin][type]; this._fileSystemRemoved(fileSystem); } delete this._fileSystemsForOrigin[origin]; }, _fileSystemAdded: function(fileSystem) { this.dispatchEventToListeners(WebInspector.FileSystemModel.EventTypes.FileSystemAdded, fileSystem); }, _fileSystemRemoved: function(fileSystem) { this.dispatchEventToListeners(WebInspector.FileSystemModel.EventTypes.FileSystemRemoved, fileSystem); }, refreshFileSystemList: function() { if (WebInspector.resourceTreeModel.mainFrame) { this._detachFrameRecursively(WebInspector.resourceTreeModel.mainFrame); this._attachFrameRecursively(WebInspector.resourceTreeModel.mainFrame); } }, _fileSystemRootReceived: function(origin, type, store, errorCode, backendRootEntry) { if (!errorCode && backendRootEntry && this._fileSystemsForOrigin[origin] === store) { var fileSystem = new WebInspector.FileSystemModel.FileSystem(this, origin, type, backendRootEntry); store[type] = fileSystem; this._fileSystemAdded(fileSystem); } }, requestDirectoryContent: function(directory, callback) { this._requestDirectoryContent(directory.url, this._directoryContentReceived.bind(this, directory, callback)); }, _requestDirectoryContent: function(url, callback) { function innerCallback(error, errorCode, backendEntries) { if (error) { callback(FileError.SECURITY_ERR); return; } if (errorCode !== 0) { callback(errorCode, null); return; } callback(errorCode, backendEntries); } FileSystemAgent.requestDirectoryContent(url, innerCallback.bind(this)); }, _directoryContentReceived: function(parentDirectory, callback, errorCode, backendEntries) { var entries = []; for (var i = 0; i < backendEntries.length; ++i) { if (backendEntries[i].isDirectory) entries.push(new WebInspector.FileSystemModel.Directory(this, parentDirectory.fileSystem, backendEntries[i])); else entries.push(new WebInspector.FileSystemModel.File(this, parentDirectory.fileSystem, backendEntries[i])); } callback(errorCode, entries); }, requestMetadata: function(entry, callback) { function innerCallback(error, errorCode, metadata) { if (error) { callback(FileError.SECURITY_ERR); return; } callback(errorCode, metadata); } FileSystemAgent.requestMetadata(entry.url, innerCallback.bind(this)); }, requestFileContent: function(file, readAsText, start, end, charset, callback) { this._requestFileContent(file.url, readAsText, start, end, charset, callback); }, _requestFileContent: function(url, readAsText, start, end, charset, callback) { function innerCallback(error, errorCode, content, charset) { if (error) { if (callback) callback(FileError.SECURITY_ERR); return; } if (callback) callback(errorCode, content, charset); } FileSystemAgent.requestFileContent(url, readAsText, start, end, charset, innerCallback.bind(this)); }, deleteEntry: function(entry, callback) { var fileSystemModel = this; if (entry === entry.fileSystem.root) this._deleteEntry(entry.url, hookFileSystemDeletion); else this._deleteEntry(entry.url, callback); function hookFileSystemDeletion(errorCode) { callback(errorCode); if (!errorCode) fileSystemModel._removeFileSystem(entry.fileSystem); } }, _deleteEntry: function(url, callback) { function innerCallback(error, errorCode) { if (error) { if (callback) callback(FileError.SECURITY_ERR); return; } if (callback) callback(errorCode); } FileSystemAgent.deleteEntry(url, innerCallback.bind(this)); }, _removeFileSystem: function(fileSystem) { var origin = fileSystem.origin; var type = fileSystem.type; if (this._fileSystemsForOrigin[origin] && this._fileSystemsForOrigin[origin][type]) { delete this._fileSystemsForOrigin[origin][type]; this._fileSystemRemoved(fileSystem); if (Object.isEmpty(this._fileSystemsForOrigin[origin])) delete this._fileSystemsForOrigin[origin]; } }, __proto__: WebInspector.Object.prototype } WebInspector.FileSystemModel.EventTypes = { FileSystemAdded: "FileSystemAdded", FileSystemRemoved: "FileSystemRemoved" } WebInspector.FileSystemModel.FileSystem = function(fileSystemModel, origin, type, backendRootEntry) { this.origin = origin; this.type = type; this.root = new WebInspector.FileSystemModel.Directory(fileSystemModel, this, backendRootEntry); } WebInspector.FileSystemModel.FileSystem.prototype = { get name() { return "filesystem:" + this.origin + "/" + this.type; } } WebInspector.FileSystemModel.Entry = function(fileSystemModel, fileSystem, backendEntry) { this._fileSystemModel = fileSystemModel; this._fileSystem = fileSystem; this._url = backendEntry.url; this._name = backendEntry.name; this._isDirectory = backendEntry.isDirectory; } WebInspector.FileSystemModel.Entry.compare = function(x, y) { if (x.isDirectory != y.isDirectory) return y.isDirectory ? 1 : -1; return x.name.localeCompare(y.name); } WebInspector.FileSystemModel.Entry.prototype = { get fileSystemModel() { return this._fileSystemModel; }, get fileSystem() { return this._fileSystem; }, get url() { return this._url; }, get name() { return this._name; }, get isDirectory() { return this._isDirectory; }, requestMetadata: function(callback) { this.fileSystemModel.requestMetadata(this, callback); }, deleteEntry: function(callback) { this.fileSystemModel.deleteEntry(this, callback); } } WebInspector.FileSystemModel.Directory = function(fileSystemModel, fileSystem, backendEntry) { WebInspector.FileSystemModel.Entry.call(this, fileSystemModel, fileSystem, backendEntry); } WebInspector.FileSystemModel.Directory.prototype = { requestDirectoryContent: function(callback) { this.fileSystemModel.requestDirectoryContent(this, callback); }, __proto__: WebInspector.FileSystemModel.Entry.prototype } WebInspector.FileSystemModel.File = function(fileSystemModel, fileSystem, backendEntry) { WebInspector.FileSystemModel.Entry.call(this, fileSystemModel, fileSystem, backendEntry); this._mimeType = backendEntry.mimeType; this._resourceType = WebInspector.resourceTypes[backendEntry.resourceType]; this._isTextFile = backendEntry.isTextFile; } WebInspector.FileSystemModel.File.prototype = { get mimeType() { return this._mimeType; }, get resourceType() { return this._resourceType; }, get isTextFile() { return this._isTextFile; }, requestFileContent: function(readAsText, start, end, charset, callback) { this.fileSystemModel.requestFileContent(this, readAsText, start, end, charset, callback); }, __proto__: WebInspector.FileSystemModel.Entry.prototype } WebInspector.OutputStreamDelegate = function() { } WebInspector.OutputStreamDelegate.prototype = { onTransferStarted: function() { }, onTransferFinished: function() { }, onChunkTransferred: function(reader) { }, onError: function(reader, event) { }, } WebInspector.OutputStream = function() { } WebInspector.OutputStream.prototype = { write: function(data, callback) { }, close: function() { } } WebInspector.ChunkedReader = function() { } WebInspector.ChunkedReader.prototype = { fileSize: function() { }, loadedSize: function() { }, fileName: function() { }, cancel: function() { } } WebInspector.ChunkedFileReader = function(file, chunkSize, delegate) { this._file = file; this._fileSize = file.size; this._loadedSize = 0; this._chunkSize = chunkSize; this._delegate = delegate; this._isCanceled = false; } WebInspector.ChunkedFileReader.prototype = { start: function(output) { this._output = output; this._reader = new FileReader(); this._reader.onload = this._onChunkLoaded.bind(this); this._reader.onerror = this._delegate.onError.bind(this._delegate, this); this._delegate.onTransferStarted(); this._loadChunk(); }, cancel: function() { this._isCanceled = true; }, loadedSize: function() { return this._loadedSize; }, fileSize: function() { return this._fileSize; }, fileName: function() { return this._file.name; }, _onChunkLoaded: function(event) { if (this._isCanceled) return; if (event.target.readyState !== FileReader.DONE) return; var data = event.target.result; this._loadedSize += data.length; this._output.write(data); if (this._isCanceled) return; this._delegate.onChunkTransferred(this); if (this._loadedSize === this._fileSize) { this._file = null; this._reader = null; this._output.close(); this._delegate.onTransferFinished(); return; } this._loadChunk(); }, _loadChunk: function() { var chunkStart = this._loadedSize; var chunkEnd = Math.min(this._fileSize, chunkStart + this._chunkSize) var nextPart = this._file.slice(chunkStart, chunkEnd); this._reader.readAsText(nextPart); } } WebInspector.ChunkedXHRReader = function(url, delegate) { this._url = url; this._delegate = delegate; this._fileSize = 0; this._loadedSize = 0; this._isCanceled = false; } WebInspector.ChunkedXHRReader.prototype = { start: function(output) { this._output = output; this._xhr = new XMLHttpRequest(); this._xhr.open("GET", this._url, true); this._xhr.onload = this._onLoad.bind(this); this._xhr.onprogress = this._onProgress.bind(this); this._xhr.onerror = this._delegate.onError.bind(this._delegate, this); this._xhr.send(null); this._delegate.onTransferStarted(); }, cancel: function() { this._isCanceled = true; this._xhr.abort(); }, loadedSize: function() { return this._loadedSize; }, fileSize: function() { return this._fileSize; }, fileName: function() { return this._url; }, _onProgress: function(event) { if (this._isCanceled) return; if (event.lengthComputable) this._fileSize = event.total; var data = this._xhr.responseText.substring(this._loadedSize); if (!data.length) return; this._loadedSize += data.length; this._output.write(data); if (this._isCanceled) return; this._delegate.onChunkTransferred(this); }, _onLoad: function(event) { this._onProgress(event); if (this._isCanceled) return; this._output.close(); this._delegate.onTransferFinished(); } } WebInspector.createFileSelectorElement = function(callback) { var fileSelectorElement = document.createElement("input"); fileSelectorElement.type = "file"; fileSelectorElement.style.zIndex = -1; fileSelectorElement.style.position = "absolute"; fileSelectorElement.onchange = function(event) { callback(fileSelectorElement.files[0]); }; return fileSelectorElement; } WebInspector.findBalancedCurlyBrackets = function(source, startIndex, lastIndex) { lastIndex = lastIndex || source.length; startIndex = startIndex || 0; var counter = 0; var inString = false; for (var index = startIndex; index < lastIndex; ++index) { var character = source[index]; if (inString) { if (character === "\\") ++index; else if (character === "\"") inString = false; } else { if (character === "\"") inString = true; else if (character === "{") ++counter; else if (character === "}") { if (--counter === 0) return index + 1; } } } return -1; } WebInspector.FileOutputStream = function() { } WebInspector.FileOutputStream.prototype = { open: function(fileName, callback) { this._closed = false; this._writeCallbacks = []; this._fileName = fileName; function callbackWrapper() { WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.SavedURL, callbackWrapper, this); WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); callback(this); } WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, callbackWrapper, this); WebInspector.fileManager.save(this._fileName, "", true); }, write: function(data, callback) { this._writeCallbacks.push(callback); WebInspector.fileManager.append(this._fileName, data); }, close: function() { this._closed = true; if (this._writeCallbacks.length) return; WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); WebInspector.fileManager.close(this._fileName); }, _onAppendDone: function(event) { if (event.data !== this._fileName) return; if (!this._writeCallbacks.length) { if (this._closed) { WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); WebInspector.fileManager.close(this._fileName); } return; } var callback = this._writeCallbacks.shift(); if (callback) callback(this); } } WebInspector.DebuggerModel = function() { InspectorBackend.registerDebuggerDispatcher(new WebInspector.DebuggerDispatcher(this)); this._debuggerPausedDetails = null; this._scripts = {}; this._scriptsBySourceURL = {}; this._canSetScriptSource = false; this._breakpointsActive = true; WebInspector.settings.pauseOnExceptionStateString = WebInspector.settings.createSetting("pauseOnExceptionStateString", WebInspector.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions); WebInspector.settings.pauseOnExceptionStateString.addChangeListener(this._pauseOnExceptionStateChanged, this); if (!Capabilities.debuggerCausesRecompilation || WebInspector.settings.debuggerEnabled.get()) this.enableDebugger(); } WebInspector.DebuggerModel.PauseOnExceptionsState = { DontPauseOnExceptions : "none", PauseOnAllExceptions : "all", PauseOnUncaughtExceptions: "uncaught" }; WebInspector.DebuggerModel.Location = function(scriptId, lineNumber, columnNumber) { this.scriptId = scriptId; this.lineNumber = lineNumber; this.columnNumber = columnNumber; } WebInspector.DebuggerModel.Events = { DebuggerWasEnabled: "DebuggerWasEnabled", DebuggerWasDisabled: "DebuggerWasDisabled", DebuggerPaused: "DebuggerPaused", DebuggerResumed: "DebuggerResumed", ParsedScriptSource: "ParsedScriptSource", FailedToParseScriptSource: "FailedToParseScriptSource", BreakpointResolved: "BreakpointResolved", GlobalObjectCleared: "GlobalObjectCleared", CallFrameSelected: "CallFrameSelected", ExecutionLineChanged: "ExecutionLineChanged", ConsoleCommandEvaluatedInSelectedCallFrame: "ConsoleCommandEvaluatedInSelectedCallFrame", BreakpointsActiveStateChanged: "BreakpointsActiveStateChanged" } WebInspector.DebuggerModel.BreakReason = { DOM: "DOM", EventListener: "EventListener", XHR: "XHR", Exception: "exception", Assert: "assert", CSPViolation: "CSPViolation" } WebInspector.DebuggerModel.prototype = { debuggerEnabled: function() { return !!this._debuggerEnabled; }, enableDebugger: function() { if (this._debuggerEnabled) return; function callback(error, result) { this._canSetScriptSource = result; } DebuggerAgent.canSetScriptSource(callback.bind(this)); DebuggerAgent.enable(this._debuggerWasEnabled.bind(this)); }, disableDebugger: function() { if (!this._debuggerEnabled) return; DebuggerAgent.disable(this._debuggerWasDisabled.bind(this)); }, canSetScriptSource: function() { return this._canSetScriptSource; }, _debuggerWasEnabled: function() { this._debuggerEnabled = true; this._pauseOnExceptionStateChanged(); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasEnabled); }, _pauseOnExceptionStateChanged: function() { DebuggerAgent.setPauseOnExceptions(WebInspector.settings.pauseOnExceptionStateString.get()); }, _debuggerWasDisabled: function() { this._debuggerEnabled = false; this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasDisabled); }, continueToLocation: function(rawLocation) { DebuggerAgent.continueToLocation(rawLocation); }, setBreakpointByScriptLocation: function(rawLocation, condition, callback) { var script = this.scriptForId(rawLocation.scriptId); if (script.sourceURL) this.setBreakpointByURL(script.sourceURL, rawLocation.lineNumber, rawLocation.columnNumber, condition, callback); else this.setBreakpointBySourceId(rawLocation, condition, callback); }, setBreakpointByURL: function(url, lineNumber, columnNumber, condition, callback) { var minColumnNumber = 0; var scripts = this._scriptsBySourceURL[url] || []; for (var i = 0, l = scripts.length; i < l; ++i) { var script = scripts[i]; if (lineNumber === script.lineOffset) minColumnNumber = minColumnNumber ? Math.min(minColumnNumber, script.columnOffset) : script.columnOffset; } columnNumber = Math.max(columnNumber, minColumnNumber); function didSetBreakpoint(error, breakpointId, locations) { if (callback) { var rawLocations = (locations); callback(error ? null : breakpointId, rawLocations); } } DebuggerAgent.setBreakpointByUrl(lineNumber, url, undefined, columnNumber, condition, didSetBreakpoint.bind(this)); WebInspector.userMetrics.ScriptsBreakpointSet.record(); }, setBreakpointBySourceId: function(rawLocation, condition, callback) { function didSetBreakpoint(error, breakpointId, actualLocation) { if (callback) { var rawLocation = (actualLocation); callback(error ? null : breakpointId, [rawLocation]); } } DebuggerAgent.setBreakpoint(rawLocation, condition, didSetBreakpoint.bind(this)); WebInspector.userMetrics.ScriptsBreakpointSet.record(); }, removeBreakpoint: function(breakpointId, callback) { DebuggerAgent.removeBreakpoint(breakpointId, callback); }, _breakpointResolved: function(breakpointId, location) { this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.BreakpointResolved, {breakpointId: breakpointId, location: location}); }, _globalObjectCleared: function() { this._setDebuggerPausedDetails(null); this._reset(); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.GlobalObjectCleared); }, _reset: function() { this._scripts = {}; this._scriptsBySourceURL = {}; }, get scripts() { return this._scripts; }, scriptForId: function(scriptId) { return this._scripts[scriptId] || null; }, setScriptSource: function(scriptId, newSource, callback) { this._scripts[scriptId].editSource(newSource, this._didEditScriptSource.bind(this, scriptId, newSource, callback)); }, _didEditScriptSource: function(scriptId, newSource, callback, error, callFrames) { callback(error); if (!error && callFrames && callFrames.length) this._pausedScript(callFrames, this._debuggerPausedDetails.reason, this._debuggerPausedDetails.auxData); }, get callFrames() { return this._debuggerPausedDetails ? this._debuggerPausedDetails.callFrames : null; }, debuggerPausedDetails: function() { return this._debuggerPausedDetails; }, _setDebuggerPausedDetails: function(debuggerPausedDetails) { if (this._debuggerPausedDetails) this._debuggerPausedDetails.dispose(); this._debuggerPausedDetails = debuggerPausedDetails; if (this._debuggerPausedDetails) this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPausedDetails); if (debuggerPausedDetails) { this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]); DebuggerAgent.setOverlayMessage(WebInspector.UIString("Paused in debugger")); } else { this.setSelectedCallFrame(null); DebuggerAgent.setOverlayMessage(); } }, _pausedScript: function(callFrames, reason, auxData) { this._setDebuggerPausedDetails(new WebInspector.DebuggerPausedDetails(this, callFrames, reason, auxData)); }, _resumedScript: function() { this._setDebuggerPausedDetails(null); if (this._executionLineLiveLocation) this._executionLineLiveLocation.dispose(); this._executionLineLiveLocation = null; this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerResumed); }, _parsedScriptSource: function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL) { var script = new WebInspector.Script(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL); this._registerScript(script); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ParsedScriptSource, script); }, _registerScript: function(script) { this._scripts[script.scriptId] = script; if (script.sourceURL) { var scripts = this._scriptsBySourceURL[script.sourceURL]; if (!scripts) { scripts = []; this._scriptsBySourceURL[script.sourceURL] = scripts; } scripts.push(script); } }, createRawLocation: function(script, lineNumber, columnNumber) { if (script.sourceURL) return this.createRawLocationByURL(script.sourceURL, lineNumber, columnNumber) return new WebInspector.DebuggerModel.Location(script.scriptId, lineNumber, columnNumber); }, createRawLocationByURL: function(sourceURL, lineNumber, columnNumber) { var closestScript = null; var scripts = this._scriptsBySourceURL[sourceURL] || []; for (var i = 0, l = scripts.length; i < l; ++i) { var script = scripts[i]; if (!closestScript) closestScript = script; if (script.lineOffset > lineNumber || (script.lineOffset === lineNumber && script.columnOffset > columnNumber)) continue; if (script.endLine < lineNumber || (script.endLine === lineNumber && script.endColumn <= columnNumber)) continue; closestScript = script; break; } return closestScript ? new WebInspector.DebuggerModel.Location(closestScript.scriptId, lineNumber, columnNumber) : null; }, isPaused: function() { return !!this.debuggerPausedDetails(); }, setSelectedCallFrame: function(callFrame) { if (this._executionLineLiveLocation) this._executionLineLiveLocation.dispose(); delete this._executionLineLiveLocation; this._selectedCallFrame = callFrame; if (!this._selectedCallFrame) return; this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.CallFrameSelected, callFrame); function updateExecutionLine(uiLocation) { this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ExecutionLineChanged, uiLocation); } this._executionLineLiveLocation = callFrame.script.createLiveLocation(callFrame.location, updateExecutionLine.bind(this)); }, selectedCallFrame: function() { return this._selectedCallFrame; }, evaluateOnSelectedCallFrame: function(code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback) { function didEvaluate(result, wasThrown) { if (returnByValue) callback(null, !!wasThrown, wasThrown ? null : result); else callback(WebInspector.RemoteObject.fromPayload(result), !!wasThrown); if (objectGroup === "console") this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ConsoleCommandEvaluatedInSelectedCallFrame); } this.selectedCallFrame().evaluate(code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, didEvaluate.bind(this)); }, getSelectedCallFrameVariables: function(callback) { var result = { this: true }; var selectedCallFrame = this._selectedCallFrame; if (!selectedCallFrame) callback(result); var pendingRequests = 0; function propertiesCollected(properties) { for (var i = 0; properties && i < properties.length; ++i) result[properties[i].name] = true; if (--pendingRequests == 0) callback(result); } for (var i = 0; i < selectedCallFrame.scopeChain.length; ++i) { var scope = selectedCallFrame.scopeChain[i]; var object = WebInspector.RemoteObject.fromPayload(scope.object); pendingRequests++; object.getAllProperties(propertiesCollected); } }, setBreakpointsActive: function(active) { if (this._breakpointsActive === active) return; this._breakpointsActive = active; DebuggerAgent.setBreakpointsActive(active); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.BreakpointsActiveStateChanged, active); }, breakpointsActive: function() { return this._breakpointsActive; }, createLiveLocation: function(rawLocation, updateDelegate) { var script = this._scripts[rawLocation.scriptId]; return script.createLiveLocation(rawLocation, updateDelegate); }, rawLocationToUILocation: function(rawLocation) { var script = this._scripts[rawLocation.scriptId]; if (!script) return null; return script.rawLocationToUILocation(rawLocation.lineNumber, rawLocation.columnNumber); }, callStackModified: function(newCallFrames, details) { if (details && details["stack_update_needs_step_in"]) DebuggerAgent.stepInto(); else { if (newCallFrames && newCallFrames.length) this._pausedScript(newCallFrames, this._debuggerPausedDetails.reason, this._debuggerPausedDetails.auxData); } }, __proto__: WebInspector.Object.prototype } WebInspector.DebuggerEventTypes = { JavaScriptPause: 0, JavaScriptBreakpoint: 1, NativeBreakpoint: 2 }; WebInspector.DebuggerDispatcher = function(debuggerModel) { this._debuggerModel = debuggerModel; } WebInspector.DebuggerDispatcher.prototype = { paused: function(callFrames, reason, auxData) { this._debuggerModel._pausedScript(callFrames, reason, auxData); }, resumed: function() { this._debuggerModel._resumedScript(); }, globalObjectCleared: function() { this._debuggerModel._globalObjectCleared(); }, scriptParsed: function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL) { this._debuggerModel._parsedScriptSource(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, !!isContentScript, sourceMapURL, hasSourceURL); }, scriptFailedToParse: function(sourceURL, source, startingLine, errorLine, errorMessage) { }, breakpointResolved: function(breakpointId, location) { this._debuggerModel._breakpointResolved(breakpointId, location); } } WebInspector.DebuggerModel.CallFrame = function(script, payload) { this._script = script; this._payload = payload; this._locations = []; } WebInspector.DebuggerModel.CallFrame.prototype = { get script() { return this._script; }, get type() { return this._payload.type; }, get scopeChain() { return this._payload.scopeChain; }, get this() { return this._payload.this; }, get functionName() { return this._payload.functionName; }, get location() { var rawLocation = (this._payload.location); return rawLocation; }, evaluate: function(code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback) { function didEvaluateOnCallFrame(error, result, wasThrown) { if (error) { console.error(error); callback(null, false); return; } callback(result, wasThrown); } DebuggerAgent.evaluateOnCallFrame(this._payload.callFrameId, code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, didEvaluateOnCallFrame.bind(this)); }, restart: function(callback) { function protocolCallback(error, callFrames, details) { if (!error) WebInspector.debuggerModel.callStackModified(callFrames, details); if (callback) callback(error); } DebuggerAgent.restartFrame(this._payload.callFrameId, protocolCallback); }, createLiveLocation: function(updateDelegate) { var location = this._script.createLiveLocation(this.location, updateDelegate); this._locations.push(location); return location; }, dispose: function(updateDelegate) { for (var i = 0; i < this._locations.length; ++i) this._locations[i].dispose(); this._locations = []; } } WebInspector.DebuggerPausedDetails = function(model, callFrames, reason, auxData) { this.callFrames = []; for (var i = 0; i < callFrames.length; ++i) { var callFrame = callFrames[i]; var script = model.scriptForId(callFrame.location.scriptId); if (script) this.callFrames.push(new WebInspector.DebuggerModel.CallFrame(script, callFrame)); } this.reason = reason; this.auxData = auxData; } WebInspector.DebuggerPausedDetails.prototype = { dispose: function() { for (var i = 0; i < this.callFrames.length; ++i) { var callFrame = this.callFrames[i]; callFrame.dispose(); } } } WebInspector.debuggerModel = null; WebInspector.SourceMapping = function() { } WebInspector.SourceMapping.prototype = { rawLocationToUILocation: function(rawLocation) { }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { } } WebInspector.ScriptSourceMapping = function() { } WebInspector.ScriptSourceMapping.prototype = { addScript: function(script) { } } WebInspector.Script = function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL) { this.scriptId = scriptId; this.sourceURL = sourceURL; this.lineOffset = startLine; this.columnOffset = startColumn; this.endLine = endLine; this.endColumn = endColumn; this.isContentScript = isContentScript; this.sourceMapURL = sourceMapURL; this.hasSourceURL = hasSourceURL; this._locations = []; } WebInspector.Script.snippetSourceURLPrefix = "snippets:///"; WebInspector.Script.prototype = { contentURL: function() { return this.sourceURL; }, contentType: function() { return WebInspector.resourceTypes.Script; }, requestContent: function(callback) { if (this._source) { callback(this._source, false, "text/javascript"); return; } function didGetScriptSource(error, source) { this._source = error ? "" : source; callback(this._source, false, "text/javascript"); } if (this.scriptId) { DebuggerAgent.getScriptSource(this.scriptId, didGetScriptSource.bind(this)); } else callback("", false, "text/javascript"); }, searchInContent: function(query, caseSensitive, isRegex, callback) { function innerCallback(error, searchMatches) { if (error) console.error(error); var result = []; for (var i = 0; i < searchMatches.length; ++i) { var searchMatch = new WebInspector.ContentProvider.SearchMatch(searchMatches[i].lineNumber, searchMatches[i].lineContent); result.push(searchMatch); } callback(result || []); } if (this.scriptId) { DebuggerAgent.searchInContent(this.scriptId, query, caseSensitive, isRegex, innerCallback.bind(this)); } else callback([]); }, editSource: function(newSource, callback) { function didEditScriptSource(error, callFrames, debugData) { if (!error) this._source = newSource; callback(error, callFrames); } if (this.scriptId) { DebuggerAgent.setScriptSource(this.scriptId, newSource, undefined, didEditScriptSource.bind(this)); } else callback("Script failed to parse"); }, isInlineScript: function() { var startsAtZero = !this.lineOffset && !this.columnOffset; return !!this.sourceURL && !startsAtZero; }, isAnonymousScript: function() { return !this.sourceURL; }, isSnippet: function() { return this.sourceURL && this.sourceURL.startsWith(WebInspector.Script.snippetSourceURLPrefix); }, rawLocationToUILocation: function(lineNumber, columnNumber) { var uiLocation = this._sourceMapping.rawLocationToUILocation(new WebInspector.DebuggerModel.Location(this.scriptId, lineNumber, columnNumber || 0)); return uiLocation.uiSourceCode.overrideLocation(uiLocation); }, setSourceMapping: function(sourceMapping) { this._sourceMapping = sourceMapping; for (var i = 0; i < this._locations.length; ++i) this._locations[i].update(); }, createLiveLocation: function(rawLocation, updateDelegate) { console.assert(rawLocation.scriptId === this.scriptId); var location = new WebInspector.Script.Location(this, rawLocation, updateDelegate); this._locations.push(location); location.update(); return location; } } WebInspector.Script.Location = function(script, rawLocation, updateDelegate) { WebInspector.LiveLocation.call(this, rawLocation, updateDelegate); this._script = script; } WebInspector.Script.Location.prototype = { uiLocation: function() { var debuggerModelLocation = (this.rawLocation()); return this._script.rawLocationToUILocation(debuggerModelLocation.lineNumber, debuggerModelLocation.columnNumber); }, dispose: function() { WebInspector.LiveLocation.prototype.dispose.call(this); this._script._locations.remove(this); }, __proto__: WebInspector.LiveLocation.prototype } WebInspector.LinkifierFormatter = function() { } WebInspector.LinkifierFormatter.prototype = { formatLiveAnchor: function(anchor, uiLocation) { } } WebInspector.Linkifier = function(formatter) { this._formatter = formatter || new WebInspector.Linkifier.DefaultFormatter(WebInspector.Linkifier.MaxLengthForDisplayedURLs); this._liveLocations = []; } WebInspector.Linkifier.prototype = { linkifyLocation: function(sourceURL, lineNumber, columnNumber, classes) { var rawLocation = WebInspector.debuggerModel.createRawLocationByURL(sourceURL, lineNumber, columnNumber || 0); if (!rawLocation) return WebInspector.linkifyResourceAsNode(sourceURL, lineNumber, classes); return this.linkifyRawLocation(rawLocation, classes); }, linkifyRawLocation: function(rawLocation, classes) { var script = WebInspector.debuggerModel.scriptForId(rawLocation.scriptId); if (!script) return null; var anchor = WebInspector.linkifyURLAsNode("", "", classes, false); var liveLocation = script.createLiveLocation(rawLocation, this._updateAnchor.bind(this, anchor)); this._liveLocations.push(liveLocation); return anchor; }, linkifyCSSRuleLocation: function(rule) { var anchor = WebInspector.linkifyURLAsNode("", "", "", false); var liveLocation = WebInspector.cssModel.createLiveLocation(rule, this._updateAnchor.bind(this, anchor)); if (!liveLocation) return null; this._liveLocations.push(liveLocation); return anchor; }, reset: function() { for (var i = 0; i < this._liveLocations.length; ++i) this._liveLocations[i].dispose(); this._liveLocations = []; }, _updateAnchor: function(anchor, uiLocation) { anchor.preferredPanel = "scripts"; anchor.href = sanitizeHref(uiLocation.uiSourceCode.url); anchor.uiSourceCode = uiLocation.uiSourceCode; anchor.lineNumber = uiLocation.lineNumber; this._formatter.formatLiveAnchor(anchor, uiLocation); } } WebInspector.Linkifier.DefaultFormatter = function(maxLength) { this._maxLength = maxLength; } WebInspector.Linkifier.DefaultFormatter.prototype = { formatLiveAnchor: function(anchor, uiLocation) { var text = WebInspector.formatLinkText(uiLocation.uiSourceCode.url, uiLocation.lineNumber); if (this._maxLength) text = text.trimMiddle(this._maxLength); anchor.textContent = text; var titleText = uiLocation.uiSourceCode.url; if (typeof uiLocation.lineNumber === "number") titleText += ":" + (uiLocation.lineNumber + 1); anchor.title = titleText; }, __proto__: WebInspector.LinkifierFormatter.prototype } WebInspector.Linkifier.DefaultCSSFormatter = function() { WebInspector.Linkifier.DefaultFormatter.call(this); } WebInspector.Linkifier.DefaultCSSFormatter.prototype = { formatLiveAnchor: function(anchor, uiLocation) { WebInspector.Linkifier.DefaultFormatter.prototype.formatLiveAnchor.call(this, anchor, uiLocation); anchor.classList.add("webkit-html-resource-link"); anchor.setAttribute("data-uncopyable", anchor.textContent); anchor.textContent = ""; }, __proto__: WebInspector.Linkifier.DefaultFormatter.prototype } WebInspector.Linkifier.MaxLengthForDisplayedURLs = 150; WebInspector.DebuggerScriptMapping = function(workspace, networkWorkspaceProvider) { this._resourceMapping = new WebInspector.ResourceScriptMapping(workspace); this._compilerMapping = new WebInspector.CompilerScriptMapping(workspace, networkWorkspaceProvider); this._snippetMapping = WebInspector.scriptSnippetModel.scriptMapping; WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this); } WebInspector.DebuggerScriptMapping.prototype = { _parsedScriptSource: function(event) { var script = (event.data); var mapping = this._mappingForScript(script); mapping.addScript(script); }, _mappingForScript: function(script) { if (WebInspector.experimentsSettings.snippetsSupport.isEnabled() && script.isSnippet()) return this._snippetMapping; if (WebInspector.settings.sourceMapsEnabled.get() && script.sourceMapURL) { if (this._compilerMapping.loadSourceMapForScript(script)) return this._compilerMapping; } return this._resourceMapping; } } WebInspector.PresentationConsoleMessageHelper = function(uiSourceCodeProvider) { this._pendingConsoleMessages = {}; this._presentationConsoleMessages = []; this._uiSourceCodeProvider = uiSourceCodeProvider; WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._consoleMessageAdded, this); WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.RepeatCountUpdated, this._consoleMessageAdded, this); WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this); } WebInspector.PresentationConsoleMessageHelper.prototype = { _consoleMessageAdded: function(event) { var message = (event.data); if (!message.url || !message.isErrorOrWarning()) return; var rawLocation = message.location(); if (rawLocation) this._addConsoleMessageToScript(message, rawLocation); else this._addPendingConsoleMessage(message); }, _addConsoleMessageToScript: function(message, rawLocation) { this._presentationConsoleMessages.push(new WebInspector.PresentationConsoleMessage(message, rawLocation)); }, _addPendingConsoleMessage: function(message) { if (!message.url) return; if (!this._pendingConsoleMessages[message.url]) this._pendingConsoleMessages[message.url] = []; this._pendingConsoleMessages[message.url].push(message); }, _parsedScriptSource: function(event) { var script = (event.data); var messages = this._pendingConsoleMessages[script.sourceURL]; if (!messages) return; var pendingMessages = []; for (var i = 0; i < messages.length; i++) { var message = messages[i]; var rawLocation = (message.location()); if (script.scriptId === rawLocation.scriptId) this._addConsoleMessageToScript(message, rawLocation); else pendingMessages.push(message); } if (pendingMessages.length) this._pendingConsoleMessages[script.sourceURL] = pendingMessages; else delete this._pendingConsoleMessages[script.sourceURL]; }, _consoleCleared: function() { this._pendingConsoleMessages = {}; for (var i = 0; i < this._presentationConsoleMessages.length; ++i) this._presentationConsoleMessages[i].dispose(); this._presentationConsoleMessages = []; var uiSourceCodes = this._uiSourceCodeProvider.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) uiSourceCodes[i].consoleMessagesCleared(); }, _debuggerReset: function() { this._pendingConsoleMessages = {}; this._presentationConsoleMessages = []; } } WebInspector.PresentationConsoleMessage = function(message, rawLocation) { this.originalMessage = message; this._liveLocation = WebInspector.debuggerModel.createLiveLocation(rawLocation, this._updateLocation.bind(this)); } WebInspector.PresentationConsoleMessage.prototype = { _updateLocation: function(uiLocation) { if (this._uiLocation) this._uiLocation.uiSourceCode.consoleMessageRemoved(this); this._uiLocation = uiLocation; this._uiLocation.uiSourceCode.consoleMessageAdded(this); }, get lineNumber() { return this._uiLocation.lineNumber; }, dispose: function() { this._liveLocation.dispose(); } } WebInspector.NetworkWorkspaceProvider = function() { this._contentProviders = {}; } WebInspector.NetworkWorkspaceProvider.prototype = { requestFileContent: function(uri, callback) { var contentProvider = this._contentProviders[uri]; contentProvider.requestContent(callback); }, setFileContent: function(uri, newContent, callback) { callback(null); }, searchInFileContent: function(uri, query, caseSensitive, isRegex, callback) { var contentProvider = this._contentProviders[uri]; contentProvider.searchInContent(query, caseSensitive, isRegex, callback); }, addFile: function(uri, contentProvider, isEditable, isContentScript, isSnippet) { var fileDescriptor = new WebInspector.FileDescriptor(uri, contentProvider.contentType(), isEditable, isContentScript, isSnippet); this._contentProviders[uri] = contentProvider; this.dispatchEventToListeners(WebInspector.WorkspaceProvider.Events.FileAdded, fileDescriptor); }, removeFile: function(uri) { delete this._contentProviders[uri]; this.dispatchEventToListeners(WebInspector.WorkspaceProvider.Events.FileRemoved, uri); }, reset: function() { this._contentProviders = {}; }, __proto__: WebInspector.Object.prototype } WebInspector.networkWorkspaceProvider = null; WebInspector.WorkspaceController = function(workspace) { this._workspace = workspace; WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this); } WebInspector.WorkspaceController.prototype = { _mainFrameNavigated: function() { WebInspector.Revision.filterOutStaleRevisions(); this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.ProjectWillReset, this._workspace.project()); this._workspace.project().reset(); this._workspace.reset(); this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.ProjectDidReset, this._workspace.project()); }, _frameAdded: function(event) { var frame = (event.data); if (frame.isMainFrame()) WebInspector.Revision.filterOutStaleRevisions(); } } WebInspector.FileDescriptor = function(uri, contentType, isEditable, isContentScript, isSnippet) { this.uri = uri; this.contentType = contentType; this.isEditable = isEditable; this.isContentScript = isContentScript || false; this.isSnippet = isSnippet || false; } WebInspector.WorkspaceProvider = function() { } WebInspector.WorkspaceProvider.Events = { FileAdded: "FileAdded", FileRemoved: "FileRemoved" } WebInspector.WorkspaceProvider.prototype = { requestFileContent: function(uri, callback) { }, setFileContent: function(uri, newContent, callback) { }, searchInFileContent: function(uri, query, caseSensitive, isRegex, callback) { }, addEventListener: function(eventType, listener, thisObject) { }, removeEventListener: function(eventType, listener, thisObject) { } } WebInspector.workspaceController = null; WebInspector.Project = function(workspace, workspaceProvider) { this._uiSourceCodes = []; this._workspace = workspace; this._workspaceProvider = workspaceProvider; this._workspaceProvider.addEventListener(WebInspector.WorkspaceProvider.Events.FileAdded, this._fileAdded, this); this._workspaceProvider.addEventListener(WebInspector.WorkspaceProvider.Events.FileRemoved, this._fileRemoved, this); } WebInspector.Project.prototype = { reset: function() { this._workspaceProvider.reset(); this._uiSourceCodes = []; }, _fileAdded: function(event) { var fileDescriptor = (event.data); var uiSourceCode = this.uiSourceCodeForURL(fileDescriptor.uri); if (uiSourceCode) { return; } uiSourceCode = new WebInspector.UISourceCode(this._workspace, fileDescriptor.uri, fileDescriptor.contentType, fileDescriptor.isEditable); uiSourceCode.isContentScript = fileDescriptor.isContentScript; uiSourceCode.isSnippet = fileDescriptor.isSnippet; this._uiSourceCodes.push(uiSourceCode); this._workspace.dispatchEventToListeners(WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, uiSourceCode); }, _fileRemoved: function(event) { var uri = (event.data); var uiSourceCode = this.uiSourceCodeForURL(uri); if (!uiSourceCode) return; this._uiSourceCodes.splice(this._uiSourceCodes.indexOf(uiSourceCode), 1); this._workspace.dispatchEventToListeners(WebInspector.UISourceCodeProvider.Events.UISourceCodeRemoved, uiSourceCode); }, uiSourceCodeForURL: function(url) { for (var i = 0; i < this._uiSourceCodes.length; ++i) { if (this._uiSourceCodes[i].url === url) return this._uiSourceCodes[i]; } return null; }, uiSourceCodes: function() { return this._uiSourceCodes; }, requestFileContent: function(uri, callback) { this._workspaceProvider.requestFileContent(uri, callback); }, setFileContent: function(uri, newContent, callback) { this._workspaceProvider.setFileContent(uri, newContent, callback); }, searchInFileContent: function(uri, query, caseSensitive, isRegex, callback) { this._workspaceProvider.searchInFileContent(uri, query, caseSensitive, isRegex, callback); } } WebInspector.Workspace = function() { this._temporaryContentProviders = new Map(); } WebInspector.Workspace.Events = { UISourceCodeContentCommitted: "UISourceCodeContentCommitted", ProjectWillReset: "ProjectWillReset", ProjectDidReset: "ProjectDidReset" } WebInspector.Workspace.prototype = { uiSourceCodeForURL: function(url) { return this._project.uiSourceCodeForURL(url); }, addProject: function(projectName, workspaceProvider) { this._project = new WebInspector.Project(this, workspaceProvider); }, project: function() { return this._project; }, uiSourceCodes: function() { return this._project.uiSourceCodes(); }, addTemporaryUISourceCode: function(uri, contentProvider, isEditable, isContentScript, isSnippet) { var uiSourceCode = new WebInspector.UISourceCode(this, uri, contentProvider.contentType(), isEditable); this._temporaryContentProviders.put(uiSourceCode, contentProvider); uiSourceCode.isContentScript = isContentScript; uiSourceCode.isSnippet = isSnippet; uiSourceCode.isTemporary = true; this.dispatchEventToListeners(WebInspector.UISourceCodeProvider.Events.TemporaryUISourceCodeAdded, uiSourceCode); return uiSourceCode; }, removeTemporaryUISourceCode: function(uiSourceCode) { this._temporaryContentProviders.remove(uiSourceCode.url); this.dispatchEventToListeners(WebInspector.UISourceCodeProvider.Events.TemporaryUISourceCodeRemoved, uiSourceCode); }, requestFileContent: function(uiSourceCode, callback) { if (this._temporaryContentProviders.get(uiSourceCode)) { this._temporaryContentProviders.get(uiSourceCode).requestContent(callback); return; } this._project.requestFileContent(uiSourceCode.url, callback); }, setFileContent: function(uiSourceCode, newContent, callback) { if (this._temporaryContentProviders.get(uiSourceCode)) return; this._project.setFileContent(uiSourceCode.url, newContent, callback); }, searchInFileContent: function(uiSourceCode, query, caseSensitive, isRegex, callback) { if (this._temporaryContentProviders.get(uiSourceCode)) { this._temporaryContentProviders.get(uiSourceCode).searchInContent(query, caseSensitive, isRegex, callback); return; } this._project.searchInFileContent(uiSourceCode.url, query, caseSensitive, isRegex, callback); }, reset: function() { this._temporaryContentProviders = new Map(); }, __proto__: WebInspector.Object.prototype } WebInspector.workspace = null; WebInspector.BreakpointManager = function(breakpointStorage, debuggerModel, workspace) { this._storage = new WebInspector.BreakpointManager.Storage(this, breakpointStorage); this._debuggerModel = debuggerModel; this._workspace = workspace; this._breakpoints = []; this._breakpointForDebuggerId = {}; this._breakpointsForUISourceCode = new Map(); this._sourceFilesWithRestoredBreakpoints = {}; this._debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.BreakpointResolved, this._breakpointResolved, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._workspaceReset, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.TemporaryUISourceCodeAdded, this._uiSourceCodeAdded, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.TemporaryUISourceCodeRemoved, this._uiSourceCodeRemoved, this); } WebInspector.BreakpointManager.Events = { BreakpointAdded: "breakpoint-added", BreakpointRemoved: "breakpoint-removed" } WebInspector.BreakpointManager.sourceFileId = function(uiSourceCode) { return uiSourceCode.formatted() ? "deobfuscated:" + uiSourceCode.url : uiSourceCode.url; } WebInspector.BreakpointManager.prototype = { _restoreBreakpoints: function(uiSourceCode) { var sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); if (!sourceFileId || this._sourceFilesWithRestoredBreakpoints[sourceFileId]) return; this._sourceFilesWithRestoredBreakpoints[sourceFileId] = true; for (var debuggerId in this._breakpointForDebuggerId) { var breakpoint = this._breakpointForDebuggerId[debuggerId]; if (breakpoint._sourceFileId !== sourceFileId) continue; this._debuggerModel.removeBreakpoint(debuggerId); delete this._breakpointForDebuggerId[debuggerId]; delete breakpoint._debuggerId; } this._storage._restoreBreakpoints(uiSourceCode); }, _uiSourceCodeAdded: function(event) { var uiSourceCode = (event.data); if (uiSourceCode.contentType() === WebInspector.resourceTypes.Script || uiSourceCode.contentType() === WebInspector.resourceTypes.Document) { this._restoreBreakpoints(uiSourceCode); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._uiSourceCodeFormatted, this); } }, _uiSourceCodeFormatted: function(event) { var uiSourceCode = (event.target); this._restoreBreakpoints(uiSourceCode); }, _uiSourceCodeRemoved: function(event) { var uiSourceCode = (event.data); if (uiSourceCode.contentType() !== WebInspector.resourceTypes.Script && uiSourceCode.contentType() !== WebInspector.resourceTypes.Document) return; if (uiSourceCode.divergedVersion) return; var sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); if (!sourceFileId) return; var breakpoints = this._breakpoints.slice(); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; for (var stringifiedLocation in breakpoint._uiLocations) { var uiLocation = breakpoint._uiLocations[stringifiedLocation]; if (uiLocation.uiSourceCode === uiSourceCode) breakpoint.remove(true); } } delete this._sourceFilesWithRestoredBreakpoints[sourceFileId]; var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) this._restoreBreakpoints(uiSourceCodes[i]); }, setBreakpoint: function(uiSourceCode, lineNumber, condition, enabled) { this._debuggerModel.setBreakpointsActive(true); return this._innerSetBreakpoint(uiSourceCode, lineNumber, condition, enabled); }, _innerSetBreakpoint: function(uiSourceCode, lineNumber, condition, enabled) { var breakpoint = this.findBreakpoint(uiSourceCode, lineNumber); if (breakpoint) { breakpoint._updateBreakpoint(condition, enabled); return breakpoint; } breakpoint = new WebInspector.BreakpointManager.Breakpoint(this, uiSourceCode, lineNumber, condition, enabled); this._breakpoints.push(breakpoint); return breakpoint; }, findBreakpoint: function(uiSourceCode, lineNumber) { var breakpoints = this._breakpointsForUISourceCode.get(uiSourceCode); var lineBreakpoints = breakpoints ? breakpoints[lineNumber] : null; return lineBreakpoints ? lineBreakpoints[0] : null; }, _filteredBreakpointLocations: function(filter) { var result = []; for (var i = 0; i < this._breakpoints.length; ++i) { var breakpoint = this._breakpoints[i]; for (var stringifiedLocation in breakpoint._uiLocations) { var uiLocation = breakpoint._uiLocations[stringifiedLocation]; if (filter(breakpoint, uiLocation)) result.push({breakpoint: breakpoint, uiLocation: uiLocation}); } } return result; }, breakpointLocationsForUISourceCode: function(uiSourceCode) { function filter(breakpoint, uiLocation) { return uiLocation.uiSourceCode === uiSourceCode; } return this._filteredBreakpointLocations(filter); }, allBreakpointLocations: function() { return this._filteredBreakpointLocations(function(breakpoint, uiLocation) { return true; }); }, toggleAllBreakpoints: function(toggleState) { for (var i = 0; i < this._breakpoints.length; ++i) { var breakpoint = this._breakpoints[i]; if (breakpoint.enabled() != toggleState) breakpoint.setEnabled(toggleState); } }, removeAllBreakpoints: function() { var breakpoints = this._breakpoints.slice(); for (var i = 0; i < breakpoints.length; ++i) breakpoints[i].remove(); }, reset: function() { this._storage._muted = true; this.removeAllBreakpoints(); delete this._storage._muted; for (var debuggerId in this._breakpointForDebuggerId) this._debuggerModel.removeBreakpoint(debuggerId); this._breakpointForDebuggerId = {}; this._sourceFilesWithRestoredBreakpoints = {}; }, _workspaceReset: function() { var breakpoints = this._breakpoints.slice(); for (var i = 0; i < breakpoints.length; ++i) { breakpoints[i]._resetLocations(); breakpoints[i]._isProvisional = true; } this._breakpoints = []; this._breakpointsForUISourceCode.clear(); this._sourceFilesWithRestoredBreakpoints = {}; }, _breakpointResolved: function(event) { var breakpointId = (event.data.breakpointId); var location = (event.data.location); var breakpoint = this._breakpointForDebuggerId[breakpointId]; if (!breakpoint || breakpoint._isProvisional) return; breakpoint._addResolvedLocation(location); }, _removeBreakpoint: function(breakpoint, removeFromStorage) { console.assert(!breakpoint._debuggerId) this._breakpoints.remove(breakpoint); if (removeFromStorage) this._storage._removeBreakpoint(breakpoint); }, _uiLocationAdded: function(breakpoint, uiLocation) { var breakpoints = this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode); if (!breakpoints) { breakpoints = {}; this._breakpointsForUISourceCode.put(uiLocation.uiSourceCode, breakpoints); } var lineBreakpoints = breakpoints[uiLocation.lineNumber]; if (!lineBreakpoints) { lineBreakpoints = []; breakpoints[uiLocation.lineNumber] = lineBreakpoints; } lineBreakpoints.push(breakpoint); this.dispatchEventToListeners(WebInspector.BreakpointManager.Events.BreakpointAdded, {breakpoint: breakpoint, uiLocation: uiLocation}); }, _uiLocationRemoved: function(breakpoint, uiLocation) { var breakpoints = this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode); if (!breakpoints) return; var lineBreakpoints = breakpoints[uiLocation.lineNumber]; if (!lineBreakpoints) return; lineBreakpoints.remove(breakpoint); if (!lineBreakpoints.length) delete breakpoints[uiLocation.lineNumber]; this.dispatchEventToListeners(WebInspector.BreakpointManager.Events.BreakpointRemoved, {breakpoint: breakpoint, uiLocation: uiLocation}); }, __proto__: WebInspector.Object.prototype } WebInspector.BreakpointManager.Breakpoint = function(breakpointManager, uiSourceCode, lineNumber, condition, enabled) { this._breakpointManager = breakpointManager; this._primaryUILocation = new WebInspector.UILocation(uiSourceCode, lineNumber, 0); this._sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); this._liveLocations = []; this._uiLocations = {}; this._condition; this._enabled; this._updateBreakpoint(condition, enabled); } WebInspector.BreakpointManager.Breakpoint.prototype = { primaryUILocation: function() { return this._primaryUILocation; }, _addResolvedLocation: function(location) { this._liveLocations.push(this._breakpointManager._debuggerModel.createLiveLocation(location, this._locationUpdated.bind(this, location))); }, _locationUpdated: function(location, uiLocation) { var stringifiedLocation = location.scriptId + ":" + location.lineNumber + ":" + location.columnNumber; var oldUILocation = (this._uiLocations[stringifiedLocation]); if (oldUILocation) this._breakpointManager._uiLocationRemoved(this, oldUILocation); if (this._uiLocations[""]) { delete this._uiLocations[""]; this._breakpointManager._uiLocationRemoved(this, this._primaryUILocation); } this._uiLocations[stringifiedLocation] = uiLocation; this._breakpointManager._uiLocationAdded(this, uiLocation); }, enabled: function() { return this._enabled; }, setEnabled: function(enabled) { this._updateBreakpoint(this._condition, enabled); }, condition: function() { return this._condition; }, setCondition: function(condition) { this._updateBreakpoint(condition, this._enabled); }, _updateBreakpoint: function(condition, enabled) { if (this._enabled === enabled && this._condition === condition) return; if (this._enabled) this._removeFromDebugger(); this._enabled = enabled; this._condition = condition; this._breakpointManager._storage._updateBreakpoint(this); var scriptFile = this._primaryUILocation.uiSourceCode.scriptFile(); if (this._enabled && !(scriptFile && scriptFile.hasDivergedFromVM())) { this._setInDebugger(); return; } this._fakeBreakpointAtPrimaryLocation(); }, remove: function(keepInStorage) { var removeFromStorage = !keepInStorage; this._resetLocations(); this._removeFromDebugger(); this._breakpointManager._removeBreakpoint(this, removeFromStorage); }, _setInDebugger: function() { var rawLocation = this._primaryUILocation.uiLocationToRawLocation(); var debuggerModelLocation = (rawLocation); if (debuggerModelLocation) this._breakpointManager._debuggerModel.setBreakpointByScriptLocation(debuggerModelLocation, this._condition, didSetBreakpoint.bind(this)); else this._breakpointManager._debuggerModel.setBreakpointByURL(this._primaryUILocation.uiSourceCode.url, this._primaryUILocation.lineNumber, 0, this._condition, didSetBreakpoint.bind(this)); function didSetBreakpoint(breakpointId, locations) { if (!breakpointId) { this._resetLocations(); this._breakpointManager._removeBreakpoint(this, false); return; } this._debuggerId = breakpointId; this._breakpointManager._breakpointForDebuggerId[breakpointId] = this; if (!locations.length) { this._fakeBreakpointAtPrimaryLocation(); return; } this._resetLocations(); for (var i = 0; i < locations.length; ++i) { var script = this._breakpointManager._debuggerModel.scriptForId(locations[i].scriptId); var uiLocation = script.rawLocationToUILocation(locations[i].lineNumber, locations[i].columnNumber); if (this._breakpointManager.findBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber)) { this.remove(); return; } } for (var i = 0; i < locations.length; ++i) this._addResolvedLocation(locations[i]); } }, _removeFromDebugger: function() { if (this._debuggerId) { this._breakpointManager._debuggerModel.removeBreakpoint(this._debuggerId); delete this._breakpointManager._breakpointForDebuggerId[this._debuggerId]; delete this._debuggerId; } }, _resetLocations: function() { for (var stringifiedLocation in this._uiLocations) this._breakpointManager._uiLocationRemoved(this, this._uiLocations[stringifiedLocation]); for (var i = 0; i < this._liveLocations.length; ++i) this._liveLocations[i].dispose(); this._liveLocations = []; this._uiLocations = {}; }, _breakpointStorageId: function() { return this._sourceFileId + ":" + this._primaryUILocation.lineNumber; }, _fakeBreakpointAtPrimaryLocation: function() { this._resetLocations(); this._uiLocations[""] = this._primaryUILocation; this._breakpointManager._uiLocationAdded(this, this._primaryUILocation); } } WebInspector.BreakpointManager.Storage = function(breakpointManager, setting) { this._breakpointManager = breakpointManager; this._setting = setting; var breakpoints = this._setting.get(); this._breakpoints = {}; for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = (breakpoints[i]); this._breakpoints[breakpoint.sourceFileId + ":" + breakpoint.lineNumber] = breakpoint; } } WebInspector.BreakpointManager.Storage.prototype = { _restoreBreakpoints: function(uiSourceCode) { this._muted = true; var sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); for (var id in this._breakpoints) { var breakpoint = this._breakpoints[id]; if (breakpoint.sourceFileId === sourceFileId) this._breakpointManager._innerSetBreakpoint(uiSourceCode, breakpoint.lineNumber, breakpoint.condition, breakpoint.enabled); } delete this._muted; }, _updateBreakpoint: function(breakpoint) { if (this._muted || !breakpoint._breakpointStorageId()) return; this._breakpoints[breakpoint._breakpointStorageId()] = new WebInspector.BreakpointManager.Storage.Item(breakpoint); this._save(); }, _removeBreakpoint: function(breakpoint) { if (this._muted) return; delete this._breakpoints[breakpoint._breakpointStorageId()]; this._save(); }, _save: function() { var breakpointsArray = []; for (var id in this._breakpoints) breakpointsArray.push(this._breakpoints[id]); this._setting.set(breakpointsArray); } } WebInspector.BreakpointManager.Storage.Item = function(breakpoint) { var primaryUILocation = breakpoint.primaryUILocation(); this.sourceFileId = breakpoint._sourceFileId; this.lineNumber = primaryUILocation.lineNumber; this.condition = breakpoint.condition(); this.enabled = breakpoint.enabled(); } WebInspector.breakpointManager = null; WebInspector.ConcatenatedScriptsContentProvider = function(scripts) { this._mimeType = "text/html"; this._scripts = scripts; } WebInspector.ConcatenatedScriptsContentProvider.scriptOpenTag = "<script>"; WebInspector.ConcatenatedScriptsContentProvider.scriptCloseTag = "</script>"; WebInspector.ConcatenatedScriptsContentProvider.prototype = { _sortedScripts: function() { if (this._sortedScriptsArray) return this._sortedScriptsArray; this._sortedScriptsArray = []; var scripts = this._scripts.slice(); scripts.sort(function(x, y) { return x.lineOffset - y.lineOffset || x.columnOffset - y.columnOffset; }); var scriptOpenTagLength = WebInspector.ConcatenatedScriptsContentProvider.scriptOpenTag.length; var scriptCloseTagLength = WebInspector.ConcatenatedScriptsContentProvider.scriptCloseTag.length; this._sortedScriptsArray.push(scripts[0]); for (var i = 1; i < scripts.length; ++i) { var previousScript = this._sortedScriptsArray[this._sortedScriptsArray.length - 1]; var lineNumber = previousScript.endLine; var columnNumber = previousScript.endColumn + scriptCloseTagLength + scriptOpenTagLength; if (lineNumber < scripts[i].lineOffset || (lineNumber === scripts[i].lineOffset && columnNumber <= scripts[i].columnOffset)) this._sortedScriptsArray.push(scripts[i]); } return this._sortedScriptsArray; }, contentURL: function() { return ""; }, contentType: function() { return WebInspector.resourceTypes.Document; }, requestContent: function(callback) { var scripts = this._sortedScripts(); var sources = []; function didRequestSource(content, contentEncoded, mimeType) { sources.push(content); if (sources.length == scripts.length) callback(this._concatenateScriptsContent(scripts, sources), false, this._mimeType); } for (var i = 0; i < scripts.length; ++i) scripts[i].requestContent(didRequestSource.bind(this)); }, searchInContent: function(query, caseSensitive, isRegex, callback) { var results = {}; var scripts = this._sortedScripts(); var scriptsLeft = scripts.length; function maybeCallback() { if (scriptsLeft) return; var result = []; for (var i = 0; i < scripts.length; ++i) result = result.concat(results[scripts[i].scriptId]); callback(result); } function searchCallback(script, searchMatches) { results[script.scriptId] = []; for (var i = 0; i < searchMatches.length; ++i) { var searchMatch = new WebInspector.ContentProvider.SearchMatch(searchMatches[i].lineNumber + script.lineOffset, searchMatches[i].lineContent); results[script.scriptId].push(searchMatch); } scriptsLeft--; maybeCallback.call(this); } maybeCallback(); for (var i = 0; i < scripts.length; ++i) scripts[i].searchInContent(query, caseSensitive, isRegex, searchCallback.bind(this, scripts[i])); }, _concatenateScriptsContent: function(scripts, sources) { var content = ""; var lineNumber = 0; var columnNumber = 0; var scriptOpenTag = WebInspector.ConcatenatedScriptsContentProvider.scriptOpenTag; var scriptCloseTag = WebInspector.ConcatenatedScriptsContentProvider.scriptCloseTag; for (var i = 0; i < scripts.length; ++i) { for (var newLinesCount = scripts[i].lineOffset - lineNumber; newLinesCount > 0; --newLinesCount) { columnNumber = 0; content += "\n"; } for (var spacesCount = scripts[i].columnOffset - columnNumber - scriptOpenTag.length; spacesCount > 0; --spacesCount) content += " "; content += scriptOpenTag; content += sources[i]; content += scriptCloseTag; lineNumber = scripts[i].endLine; columnNumber = scripts[i].endColumn + scriptCloseTag.length; } return content; }, __proto__: WebInspector.ContentProvider.prototype } WebInspector.CompilerSourceMappingContentProvider = function(sourceURL) { this._sourceURL = sourceURL; } WebInspector.CompilerSourceMappingContentProvider.prototype = { contentURL: function() { return this._sourceURL; }, contentType: function() { return WebInspector.resourceTypes.Script; }, requestContent: function(callback) { var sourceCode = ""; try { sourceCode = InspectorFrontendHost.loadResourceSynchronously(this._sourceURL); } catch(e) { console.error(e.message); } callback(sourceCode, false, "text/javascript"); }, searchInContent: function(query, caseSensitive, isRegex, callback) { callback([]); }, __proto__: WebInspector.ContentProvider.prototype } WebInspector.StaticContentProvider = function(contentType, content, mimeType) { this._content = content; this._contentType = contentType; this._mimeType = mimeType; } WebInspector.StaticContentProvider.prototype = { contentURL: function() { return ""; }, contentType: function() { return this._contentType; }, requestContent: function(callback) { callback(this._content, false, this._mimeType || this._contentType.canonicalMimeType()); }, searchInContent: function(query, caseSensitive, isRegex, callback) { function performSearch() { var regex = createSearchRegex(query, caseSensitive, isRegex); var result = []; var lineEndings = this._content.lineEndings(); for (var i = 0; i < lineEndings.length; ++i) { var lineStart = i > 0 ? lineEndings[i - 1] + 1 : 0; var lineEnd = lineEndings[i]; var lineContent = this._content.substring(lineStart, lineEnd); if (lineContent.length > 0 && lineContent.charAt(lineContent.length - 1) === "\r") lineContent = lineContent.substring(0, lineContent.length - 1) if (regex.exec(lineContent)) result.push(new WebInspector.ContentProvider.SearchMatch(i, lineContent)); } callback(result); } window.setTimeout(performSearch.bind(this), 0); }, __proto__: WebInspector.ContentProvider.prototype } WebInspector.ResourceScriptMapping = function(workspace) { this._workspace = workspace; this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._reset, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._uiSourceCodeAddedToWorkspace, this); this._reset(); } WebInspector.ResourceScriptMapping.prototype = { rawLocationToUILocation: function(rawLocation) { var debuggerModelLocation = (rawLocation); var script = WebInspector.debuggerModel.scriptForId(debuggerModelLocation.scriptId); var uiSourceCode = this._workspaceUISourceCodeForScript(script) || this._getOrCreateTemporaryUISourceCode(script); if (uiSourceCode.scriptFile() && uiSourceCode.scriptFile().hasDivergedFromVM()) uiSourceCode = this._getOrCreateOriginalUISourceCode(script, uiSourceCode); console.assert(!!uiSourceCode); return new WebInspector.UILocation(uiSourceCode, debuggerModelLocation.lineNumber, debuggerModelLocation.columnNumber || 0); }, _hasMergedToVM: function(uiSourceCode) { var scripts = this._scriptsForUISourceCode(uiSourceCode); if (!scripts.length) return; this._deleteOriginalUISourceCodeForScripts(scripts); for (var i = 0; i < scripts.length; ++i) scripts[i].setSourceMapping(this); }, _hasDivergedFromVM: function(uiSourceCode) { var scripts = this._scriptsForUISourceCode(uiSourceCode); if (!scripts.length) return; for (var i = 0; i < scripts.length; ++i) scripts[i].setSourceMapping(this); }, _workspaceUISourceCodeForScript: function(script) { if (script.isAnonymousScript() || this._isDynamicScript(script)) return null; return this._workspace.uiSourceCodeForURL(script.sourceURL); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { var scripts = this._scriptsForUISourceCode(uiSourceCode); console.assert(scripts.length); return WebInspector.debuggerModel.createRawLocation(scripts[0], lineNumber, columnNumber); }, addScript: function(script) { if (!script.isAnonymousScript()) { this._scripts.push(script); var scriptsForSourceURL = script.isInlineScript() ? this._inlineScriptsForSourceURL : this._nonInlineScriptsForSourceURL; var bucket = scriptsForSourceURL[script.sourceURL] || []; scriptsForSourceURL[script.sourceURL] = bucket; bucket.push(script); } script.setSourceMapping(this); var uiSourceCode = this._workspaceUISourceCodeForScript(script); if (uiSourceCode) { this._bindUISourceCodeToScripts(uiSourceCode, [script]); return; } var scripts = script.isInlineScript() ? this._scriptsForSourceURL(script.sourceURL, true) : [script]; if (this._deleteTemporaryUISourceCodeForScripts(scripts)) { this._deleteOriginalUISourceCodeForScripts(scripts); this._getOrCreateTemporaryUISourceCode(script); } }, _deleteOriginalUISourceCodeForScripts: function(scripts) { var originalUISourceCode; for (var i = 0; i < scripts.length; ++i) { originalUISourceCode = originalUISourceCode || this._originalUISourceCodeForScriptId[scripts[i].scriptId]; delete this._originalUISourceCodeForScriptId[scripts[i].scriptId]; } if (!originalUISourceCode) return; this._workspace.removeTemporaryUISourceCode(originalUISourceCode); this._scriptIdsForOriginalUISourceCode.remove(originalUISourceCode); }, _deleteTemporaryUISourceCodeForScripts: function(scripts) { var temporaryUISourceCode; for (var i = 0; i < scripts.length; ++i) { temporaryUISourceCode = temporaryUISourceCode || this._temporaryUISourceCodeForScriptId[scripts[i].scriptId]; delete this._temporaryUISourceCodeForScriptId[scripts[i].scriptId]; } if (!temporaryUISourceCode) return false; this._workspace.removeTemporaryUISourceCode(temporaryUISourceCode); this._scriptIdsForTemporaryUISourceCode.remove(temporaryUISourceCode); return true; }, _bindUISourceCodeToScripts: function(uiSourceCode, scripts) { console.assert(scripts.length); if (uiSourceCode.isEditable()) { var scriptFile = new WebInspector.ResourceScriptFile(this, uiSourceCode); uiSourceCode.setScriptFile(scriptFile); } for (var i = 0; i < scripts.length; ++i) scripts[i].setSourceMapping(this); uiSourceCode.setSourceMapping(this); }, _isDynamicScript: function(script) { if (script.isAnonymousScript() || script.isInlineScript()) return false; var inlineScriptsWithTheSameURL = this._scriptsForSourceURL(script.sourceURL, true); return !!inlineScriptsWithTheSameURL.length; }, _scriptsForSourceURL: function(sourceURL, isInlineScript) { var scriptsForSourceURL = isInlineScript ? this._inlineScriptsForSourceURL : this._nonInlineScriptsForSourceURL; return scriptsForSourceURL[sourceURL] || []; }, _createUISourceCode: function(scripts, divergedVersion) { var script = scripts[0]; var contentProvider = script.isInlineScript() ? new WebInspector.ConcatenatedScriptsContentProvider(scripts.slice()) : script; var isDynamicScript = this._isDynamicScript(script); var url = isDynamicScript ? "" : script.sourceURL; var temporaryUISourceCode = this._workspace.addTemporaryUISourceCode(url, contentProvider, !script.isInlineScript() && !divergedVersion, script.isContentScript); temporaryUISourceCode.divergedVersion = divergedVersion; return temporaryUISourceCode; }, _getOrCreateTemporaryUISourceCode: function(script) { var temporaryUISourceCode = this._temporaryUISourceCodeForScriptId[script.scriptId]; if (temporaryUISourceCode) return temporaryUISourceCode; var scripts = script.isInlineScript() ? this._scriptsForSourceURL(script.sourceURL, true) : [script]; temporaryUISourceCode = this._createUISourceCode(scripts); var scriptIds = []; for (var i = 0; i < scripts.length; ++i) { this._temporaryUISourceCodeForScriptId[scripts[i].scriptId] = temporaryUISourceCode; scriptIds.push(scripts[i].scriptId); } this._scriptIdsForTemporaryUISourceCode.put(temporaryUISourceCode, scriptIds); this._bindUISourceCodeToScripts(temporaryUISourceCode, scripts); return temporaryUISourceCode; }, _getOrCreateOriginalUISourceCode: function(script, divergedVersion) { var originalUISourceCode = this._originalUISourceCodeForScriptId[script.scriptId]; if (originalUISourceCode) return originalUISourceCode; var scripts = script.isInlineScript() ? this._scriptsForSourceURL(script.sourceURL, true) : [script]; originalUISourceCode = this._createUISourceCode(scripts, divergedVersion); var scriptIds = []; for (var i = 0; i < scripts.length; ++i) { this._originalUISourceCodeForScriptId[scripts[i].scriptId] = originalUISourceCode; scriptIds.push(scripts[i].scriptId); } this._scriptIdsForOriginalUISourceCode.put(originalUISourceCode, scriptIds); this._bindUISourceCodeToScripts(originalUISourceCode, scripts); return originalUISourceCode; }, _uiSourceCodeAddedToWorkspace: function(event) { var uiSourceCode = (event.data); console.assert(!!uiSourceCode.url); var scripts = this._scriptsForUISourceCode(uiSourceCode); if (!scripts.length) return; this._deleteTemporaryUISourceCodeForScripts(scripts); this._deleteOriginalUISourceCodeForScripts(scripts); this._bindUISourceCodeToScripts(uiSourceCode, scripts); }, _scriptsForUISourceCode: function(uiSourceCode) { var scriptIds = this._scriptIdsForOriginalUISourceCode.get(uiSourceCode) || this._scriptIdsForTemporaryUISourceCode.get(uiSourceCode); if (scriptIds) return scriptIds.map(WebInspector.debuggerModel.scriptForId.bind(WebInspector.debuggerModel)); var isInlineScript; switch (uiSourceCode.contentType()) { case WebInspector.resourceTypes.Document: isInlineScript = true; break; case WebInspector.resourceTypes.Script: isInlineScript = false; break; default: return []; } return this._scriptsForSourceURL(uiSourceCode.url, isInlineScript); }, _reset: function() { this._temporaryUISourceCodeForScriptId = {}; this._scriptIdsForTemporaryUISourceCode = new Map(); this._originalUISourceCodeForScriptId = {}; this._scriptIdsForOriginalUISourceCode = new Map(); this._inlineScriptsForSourceURL = {}; this._nonInlineScriptsForSourceURL = {}; this._scripts = []; }, } WebInspector.ScriptFile = function() { } WebInspector.ScriptFile.Events = { WillMergeToVM: "WillMergeToVM", DidMergeToVM: "DidMergeToVM", WillDivergeFromVM: "WillDivergeFromVM", DidDivergeFromVM: "DidDivergeFromVM", } WebInspector.ScriptFile.prototype = { hasDivergedFromVM: function() { return false; }, isDivergingFromVM: function() { return false; }, addEventListener: function(eventType, listener, thisObject) { }, removeEventListener: function(eventType, listener, thisObject) { } } WebInspector.ResourceScriptFile = function(resourceScriptMapping, uiSourceCode) { WebInspector.ScriptFile.call(this); this._resourceScriptMapping = resourceScriptMapping; this._uiSourceCode = uiSourceCode; this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this); } WebInspector.ResourceScriptFile.prototype = { _workingCopyCommitted: function(event) { function innerCallback(error) { if (error) { this._hasDivergedFromVM = true; WebInspector.showErrorMessage(error); return; } this.dispatchEventToListeners(WebInspector.ScriptFile.Events.WillMergeToVM, this); delete this._hasDivergedFromVM; this._resourceScriptMapping._hasMergedToVM(this._uiSourceCode); this.dispatchEventToListeners(WebInspector.ScriptFile.Events.DidMergeToVM, this); } var rawLocation = (this._uiSourceCode.uiLocationToRawLocation(0, 0)); if (!rawLocation) return; var script = WebInspector.debuggerModel.scriptForId(rawLocation.scriptId); WebInspector.debuggerModel.setScriptSource(script.scriptId, this._uiSourceCode.workingCopy(), innerCallback.bind(this)); }, _workingCopyChanged: function(event) { var wasDirty = (event.data.wasDirty); if (!wasDirty && this._uiSourceCode.isDirty() && !this._hasDivergedFromVM) { this._isDivergingFromVM = true; this.dispatchEventToListeners(WebInspector.ScriptFile.Events.WillDivergeFromVM, this._uiSourceCode); this._resourceScriptMapping._hasDivergedFromVM(this._uiSourceCode); this.dispatchEventToListeners(WebInspector.ScriptFile.Events.DidDivergeFromVM, this._uiSourceCode); delete this._isDivergingFromVM; } else if (wasDirty && !this._uiSourceCode.isDirty() && !this._hasDivergedFromVM) { this.dispatchEventToListeners(WebInspector.ScriptFile.Events.WillMergeToVM, this._uiSourceCode); this._resourceScriptMapping._hasMergedToVM(this._uiSourceCode); this.dispatchEventToListeners(WebInspector.ScriptFile.Events.DidMergeToVM, this._uiSourceCode); } }, hasDivergedFromVM: function() { return this._uiSourceCode.isDirty() || this._hasDivergedFromVM; }, isDivergingFromVM: function() { return this._isDivergingFromVM; }, __proto__: WebInspector.Object.prototype } WebInspector.CompilerScriptMapping = function(workspace, networkWorkspaceProvider) { this._workspace = workspace; this._networkWorkspaceProvider = networkWorkspaceProvider; this._sourceMapForSourceMapURL = {}; this._sourceMapForScriptId = {}; this._scriptForSourceMap = new Map(); this._sourceMapForURL = {}; this._originalUISourceCodeForScriptId = {}; this._scriptForOriginalUISourceCode = new Map(); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._reset, this); } WebInspector.CompilerScriptMapping.prototype = { rawLocationToUILocation: function(rawLocation) { var debuggerModelLocation = (rawLocation); var sourceMap = this._sourceMapForScriptId[debuggerModelLocation.scriptId]; var lineNumber = debuggerModelLocation.lineNumber; var columnNumber = debuggerModelLocation.columnNumber || 0; var entry = sourceMap.findEntry(lineNumber, columnNumber); if (entry.length === 2) { var temporaryUISourceCode = this._originalUISourceCodeForScriptId[debuggerModelLocation.scriptId]; return new WebInspector.UILocation(temporaryUISourceCode, lineNumber, columnNumber); } var uiSourceCode = this._workspace.uiSourceCodeForURL(entry[2]); return new WebInspector.UILocation(uiSourceCode, entry[3], entry[4]); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { var script = this._scriptForOriginalUISourceCode.get(uiSourceCode); if (script) return WebInspector.debuggerModel.createRawLocation(script, lineNumber, columnNumber); var sourceMap = this._sourceMapForURL[uiSourceCode.url]; var entry = sourceMap.findEntryReversed(uiSourceCode.url, lineNumber); return WebInspector.debuggerModel.createRawLocation(this._scriptForSourceMap.get(sourceMap), entry[0], entry[1]); }, addScript: function(script) { var originalUISourceCode = this._workspace.addTemporaryUISourceCode(script.sourceURL, script, false); originalUISourceCode.setSourceMapping(this); this._originalUISourceCodeForScriptId[script.scriptId] = originalUISourceCode; this._scriptForOriginalUISourceCode.put(originalUISourceCode, script); var sourceMap = this.loadSourceMapForScript(script); if (this._scriptForSourceMap.get(sourceMap)) { this._sourceMapForScriptId[script.scriptId] = sourceMap; script.setSourceMapping(this); return; } var sourceURLs = sourceMap.sources(); for (var i = 0; i < sourceURLs.length; ++i) { var sourceURL = sourceURLs[i]; if (this._workspace.uiSourceCodeForURL(sourceURL)) continue; this._sourceMapForURL[sourceURL] = sourceMap; var sourceContent = sourceMap.sourceContent(sourceURL); var contentProvider; if (sourceContent) contentProvider = new WebInspector.StaticContentProvider(WebInspector.resourceTypes.Script, sourceContent); else contentProvider = new WebInspector.CompilerSourceMappingContentProvider(sourceURL); this._networkWorkspaceProvider.addFile(sourceURL, contentProvider, true); var uiSourceCode = this._workspace.uiSourceCodeForURL(sourceURL); uiSourceCode.setSourceMapping(this); uiSourceCode.isContentScript = script.isContentScript; } this._sourceMapForScriptId[script.scriptId] = sourceMap; this._scriptForSourceMap.put(sourceMap, script); script.setSourceMapping(this); }, loadSourceMapForScript: function(script) { var sourceMapURL = WebInspector.SourceMapParser.prototype._canonicalizeURL(script.sourceMapURL, script.sourceURL); var sourceMap = this._sourceMapForSourceMapURL[sourceMapURL]; if (sourceMap) return sourceMap; try { var response = InspectorFrontendHost.loadResourceSynchronously(sourceMapURL); if (response.slice(0, 3) === ")]}") response = response.substring(response.indexOf('\n')); var payload = (JSON.parse(response)); sourceMap = new WebInspector.SourceMapParser(sourceMapURL, payload); } catch(e) { console.error(e.message); return null; } this._sourceMapForSourceMapURL[sourceMapURL] = sourceMap; return sourceMap; }, _reset: function() { this._sourceMapForSourceMapURL = {}; this._sourceMapForScriptId = {}; this._scriptForSourceMap = new Map(); this._sourceMapForURL = {}; this._originalUISourceCodeForScriptId = {}; this._scriptForOriginalUISourceCode = new Map(); } } WebInspector.SourceMapPayload = function() { this.sections = []; this.mappings = ""; this.sourceRoot = ""; this.sources = []; } WebInspector.SourceMapParser = function(sourceMappingURL, payload) { if (!WebInspector.SourceMapParser.prototype._base64Map) { const base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; WebInspector.SourceMapParser.prototype._base64Map = {}; for (var i = 0; i < base64Digits.length; ++i) WebInspector.SourceMapParser.prototype._base64Map[base64Digits.charAt(i)] = i; } this._sourceMappingURL = sourceMappingURL; this._mappings = []; this._reverseMappingsBySourceURL = {}; this._sourceContentByURL = {}; this._parseMappingPayload(payload); } WebInspector.SourceMapParser.prototype = { sources: function() { var sources = []; for (var sourceURL in this._reverseMappingsBySourceURL) sources.push(sourceURL); return sources; }, sourceContent: function(sourceURL) { return this._sourceContentByURL[sourceURL]; }, findEntry: function(lineNumber, columnNumber) { var first = 0; var count = this._mappings.length; while (count > 1) { var step = count >> 1; var middle = first + step; var mapping = this._mappings[middle]; if (lineNumber < mapping[0] || (lineNumber == mapping[0] && columnNumber < mapping[1])) count = step; else { first = middle; count -= step; } } return this._mappings[first]; }, findEntryReversed: function(sourceURL, lineNumber) { var mappings = this._reverseMappingsBySourceURL[sourceURL]; for ( ; lineNumber < mappings.length; ++lineNumber) { var mapping = mappings[lineNumber]; if (mapping) return mapping; } return this._mappings[0]; }, _parseMappingPayload: function(mappingPayload) { if (mappingPayload.sections) this._parseSections(mappingPayload.sections); else this._parseMap(mappingPayload, 0, 0); }, _parseSections: function(sections) { for (var i = 0; i < sections.length; ++i) { var section = sections[i]; this._parseMap(section.map, section.offset.line, section.offset.column) } }, _parseMap: function(map, lineNumber, columnNumber) { var sourceIndex = 0; var sourceLineNumber = 0; var sourceColumnNumber = 0; var nameIndex = 0; var sources = []; for (var i = 0; i < map.sources.length; ++i) { var sourceURL = map.sources[i]; if (map.sourceRoot) sourceURL = map.sourceRoot + "/" + sourceURL; var url = this._canonicalizeURL(sourceURL, this._sourceMappingURL); sources.push(url); if (!this._reverseMappingsBySourceURL[url]) this._reverseMappingsBySourceURL[url] = []; if (map.sourcesContent && map.sourcesContent[i]) this._sourceContentByURL[url] = map.sourcesContent[i]; } var stringCharIterator = new WebInspector.SourceMapParser.StringCharIterator(map.mappings); var sourceURL = sources[sourceIndex]; var reverseMappings = this._reverseMappingsBySourceURL[sourceURL]; while (true) { if (stringCharIterator.peek() === ",") stringCharIterator.next(); else { while (stringCharIterator.peek() === ";") { lineNumber += 1; columnNumber = 0; stringCharIterator.next(); } if (!stringCharIterator.hasNext()) break; } columnNumber += this._decodeVLQ(stringCharIterator); if (this._isSeparator(stringCharIterator.peek())) { this._mappings.push([lineNumber, columnNumber]); continue; } var sourceIndexDelta = this._decodeVLQ(stringCharIterator); if (sourceIndexDelta) { sourceIndex += sourceIndexDelta; sourceURL = sources[sourceIndex]; reverseMappings = this._reverseMappingsBySourceURL[sourceURL]; } sourceLineNumber += this._decodeVLQ(stringCharIterator); sourceColumnNumber += this._decodeVLQ(stringCharIterator); if (!this._isSeparator(stringCharIterator.peek())) nameIndex += this._decodeVLQ(stringCharIterator); this._mappings.push([lineNumber, columnNumber, sourceURL, sourceLineNumber, sourceColumnNumber]); if (!reverseMappings[sourceLineNumber]) reverseMappings[sourceLineNumber] = [lineNumber, columnNumber]; } }, _isSeparator: function(char) { return char === "," || char === ";"; }, _decodeVLQ: function(stringCharIterator) { var result = 0; var shift = 0; do { var digit = this._base64Map[stringCharIterator.next()]; result += (digit & this._VLQ_BASE_MASK) << shift; shift += this._VLQ_BASE_SHIFT; } while (digit & this._VLQ_CONTINUATION_MASK); var negative = result & 1; result >>= 1; return negative ? -result : result; }, _canonicalizeURL: function(url, baseURL) { if (!url || !baseURL || url.asParsedURL() || url.substring(0, 5) === "data:") return url; var base = baseURL.asParsedURL(); if (!base) return url; var baseHost = base.scheme + "://" + base.host + (base.port ? ":" + base.port : ""); if (url[0] === "/") return baseHost + url; return baseHost + base.folderPathComponents + "/" + url; }, _VLQ_BASE_SHIFT: 5, _VLQ_BASE_MASK: (1 << 5) - 1, _VLQ_CONTINUATION_MASK: 1 << 5 } WebInspector.SourceMapParser.StringCharIterator = function(string) { this._string = string; this._position = 0; } WebInspector.SourceMapParser.StringCharIterator.prototype = { next: function() { return this._string.charAt(this._position++); }, peek: function() { return this._string.charAt(this._position); }, hasNext: function() { return this._position < this._string.length; } } WebInspector.SASSSourceMapping = function(workspace, networkWorkspaceProvider) { this._workspace = workspace; this._networkWorkspaceProvider = networkWorkspaceProvider; this._uiLocations = {}; this._cssURLsForSASSURL = {}; this._timeoutForURL = {}; WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, this._resourceAdded, this); WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, this._fileSaveFinished, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._reset, this); } WebInspector.SASSSourceMapping.prototype = { _populate: function() { function populateFrame(frame) { for (var i = 0; i < frame.childFrames.length; ++i) populateFrame.call(this, frame.childFrames[i]); var resources = frame.resources(); for (var i = 0; i < resources.length; ++i) this._resourceAdded({data:resources[i]}); } populateFrame.call(this, WebInspector.resourceTreeModel.mainFrame); }, _fileSaveFinished: function(event) { var sassURL = (event.data); function callback() { delete this._timeoutForURL[sassURL]; var cssURLs = this._cssURLsForSASSURL[sassURL]; if (!cssURLs) return; for (var i = 0; i < cssURLs.length; ++i) this._reloadCSS(cssURLs[i]); } var timer = this._timeoutForURL[sassURL]; if (timer) { clearTimeout(timer); delete this._timeoutForURL[sassURL]; } if (!WebInspector.settings.cssReloadEnabled.get() || !this._cssURLsForSASSURL[sassURL]) return; var timeout = WebInspector.settings.cssReloadTimeout.get(); if (timeout && isFinite(timeout)) this._timeoutForURL[sassURL] = setTimeout(callback.bind(this), Number(timeout)); }, _reloadCSS: function(url) { var uiSourceCode = this._workspace.uiSourceCodeForURL(url); if (!uiSourceCode) return; var newContent = InspectorFrontendHost.loadResourceSynchronously(url); uiSourceCode.addRevision(newContent); }, _resourceAdded: function(event) { var resource = (event.data); if (resource.type !== WebInspector.resourceTypes.Stylesheet) return; function didRequestContent(content, contentEncoded, mimeType) { if (!content) return; var lines = content.split(/\r?\n/); var debugInfoRegex = /@media\s\-sass\-debug\-info{filename{font-family:([^}]+)}line{font-family:\\0000(\d\d)([^}]*)}}/i; var lineNumbersRegex = /\/\*\s+line\s+([0-9]+),\s+([^*\/]+)/; for (var lineNumber = 0; lineNumber < lines.length; ++lineNumber) { var match = debugInfoRegex.exec(lines[lineNumber]); if (match) { var url = match[1].replace(/\\(.)/g, "$1"); var line = parseInt(decodeURI("%" + match[2]) + match[3], 10); this._bindUISourceCode(url, line, resource.url, lineNumber); continue; } match = lineNumbersRegex.exec(lines[lineNumber]); if (match) { var fileName = match[2].trim(); var line = parseInt(match[1], 10); var url = resource.url; if (url.endsWith("/" + resource.parsedURL.lastPathComponent)) url = url.substring(0, url.length - resource.parsedURL.lastPathComponent.length) + fileName; else url = fileName; this._bindUISourceCode(url, line, resource.url, lineNumber); continue; } } } resource.requestContent(didRequestContent.bind(this)); }, _bindUISourceCode: function(url, line, rawURL, rawLine) { var uiSourceCode = this._workspace.uiSourceCodeForURL(url); if (!uiSourceCode) { var content = InspectorFrontendHost.loadResourceSynchronously(url); var contentProvider = new WebInspector.StaticContentProvider(WebInspector.resourceTypes.Stylesheet, content, "text/x-scss"); this._networkWorkspaceProvider.addFile(url, contentProvider, true); uiSourceCode = this._workspace.uiSourceCodeForURL(url); WebInspector.cssModel.setSourceMapping(rawURL, this); } var rawLocationString = rawURL + ":" + (rawLine + 1); this._uiLocations[rawLocationString] = new WebInspector.UILocation(uiSourceCode, line - 1, 0); this._addCSSURLforSASSURL(rawURL, url); }, _addCSSURLforSASSURL: function(cssURL, sassURL) { var cssURLs; if (this._cssURLsForSASSURL.hasOwnProperty(sassURL)) cssURLs = this._cssURLsForSASSURL[sassURL]; else { cssURLs = []; this._cssURLsForSASSURL[sassURL] = cssURLs; } if (cssURLs.indexOf(cssURL) === -1) cssURLs.push(cssURL); }, rawLocationToUILocation: function(rawLocation) { var location = (rawLocation); var uiLocation = this._uiLocations[location.url + ":" + location.lineNumber]; if (!uiLocation) { var uiSourceCode = this._workspace.uiSourceCodeForURL(location.url); uiLocation = new WebInspector.UILocation(uiSourceCode, location.lineNumber, 0); } return uiLocation; }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { return new WebInspector.CSSLocation(uiSourceCode.contentURL() || "", lineNumber); }, _reset: function() { this._uiLocations = {}; this._populate(); } } WebInspector.DOMNode = function(domAgent, doc, isInShadowTree, payload) { this._domAgent = domAgent; this.ownerDocument = doc; this._isInShadowTree = isInShadowTree; this.id = payload.nodeId; domAgent._idToDOMNode[this.id] = this; this._nodeType = payload.nodeType; this._nodeName = payload.nodeName; this._localName = payload.localName; this._nodeValue = payload.nodeValue; this._shadowRoots = []; this._attributes = []; this._attributesMap = {}; if (payload.attributes) this._setAttributesPayload(payload.attributes); this._userProperties = {}; this._descendantUserPropertyCounters = {}; this._childNodeCount = payload.childNodeCount; this.children = null; this.nextSibling = null; this.previousSibling = null; this.firstChild = null; this.lastChild = null; this.parentNode = null; if (payload.shadowRoots && WebInspector.settings.showShadowDOM.get()) { for (var i = 0; i < payload.shadowRoots.length; ++i) { var root = payload.shadowRoots[i]; var node = new WebInspector.DOMNode(this._domAgent, this.ownerDocument, true, root); this._shadowRoots.push(node); } } if (payload.children) this._setChildrenPayload(payload.children); if (payload.contentDocument) { this._contentDocument = new WebInspector.DOMDocument(domAgent, payload.contentDocument); this.children = [this._contentDocument]; this._renumber(); } if (this._nodeType === Node.ELEMENT_NODE) { if (this.ownerDocument && !this.ownerDocument.documentElement && this._nodeName === "HTML") this.ownerDocument.documentElement = this; if (this.ownerDocument && !this.ownerDocument.body && this._nodeName === "BODY") this.ownerDocument.body = this; } else if (this._nodeType === Node.DOCUMENT_TYPE_NODE) { this.publicId = payload.publicId; this.systemId = payload.systemId; this.internalSubset = payload.internalSubset; } else if (this._nodeType === Node.ATTRIBUTE_NODE) { this.name = payload.name; this.value = payload.value; } } WebInspector.DOMNode.XPathStep = function(value, optimized) { this.value = value; this.optimized = optimized; } WebInspector.DOMNode.XPathStep.prototype = { toString: function() { return this.value; } } WebInspector.DOMNode.prototype = { hasAttributes: function() { return this._attributes.length > 0; }, hasChildNodes: function() { return this._childNodeCount > 0 || !!this._shadowRoots.length; }, hasShadowRoots: function() { return !!this._shadowRoots.length; }, nodeType: function() { return this._nodeType; }, nodeName: function() { return this._nodeName; }, isInShadowTree: function() { return this._isInShadowTree; }, nodeNameInCorrectCase: function() { return this.isXMLNode() ? this.nodeName() : this.nodeName().toLowerCase(); }, setNodeName: function(name, callback) { DOMAgent.setNodeName(this.id, name, WebInspector.domAgent._markRevision(this, callback)); }, localName: function() { return this._localName; }, nodeValue: function() { return this._nodeValue; }, setNodeValue: function(value, callback) { DOMAgent.setNodeValue(this.id, value, WebInspector.domAgent._markRevision(this, callback)); }, getAttribute: function(name) { var attr = this._attributesMap[name]; return attr ? attr.value : undefined; }, setAttribute: function(name, text, callback) { DOMAgent.setAttributesAsText(this.id, text, name, WebInspector.domAgent._markRevision(this, callback)); }, setAttributeValue: function(name, value, callback) { DOMAgent.setAttributeValue(this.id, name, value, WebInspector.domAgent._markRevision(this, callback)); }, attributes: function() { return this._attributes; }, removeAttribute: function(name, callback) { function mycallback(error) { if (!error) { delete this._attributesMap[name]; for (var i = 0; i < this._attributes.length; ++i) { if (this._attributes[i].name === name) { this._attributes.splice(i, 1); break; } } } WebInspector.domAgent._markRevision(this, callback)(error); } DOMAgent.removeAttribute(this.id, name, mycallback.bind(this)); }, getChildNodes: function(callback) { if (this.children) { if (callback) callback(this.children); return; } function mycallback(error) { if (!error && callback) callback(this.children); } DOMAgent.requestChildNodes(this.id, mycallback.bind(this)); }, getOuterHTML: function(callback) { DOMAgent.getOuterHTML(this.id, callback); }, setOuterHTML: function(html, callback) { DOMAgent.setOuterHTML(this.id, html, WebInspector.domAgent._markRevision(this, callback)); }, removeNode: function(callback) { DOMAgent.removeNode(this.id, WebInspector.domAgent._markRevision(this, callback)); }, copyNode: function() { function copy(error, text) { if (!error) InspectorFrontendHost.copyText(text); } DOMAgent.getOuterHTML(this.id, copy); }, copyXPath: function(optimized) { InspectorFrontendHost.copyText(this.xPath(optimized)); }, eventListeners: function(callback) { DOMAgent.getEventListenersForNode(this.id, callback); }, path: function() { var path = []; var node = this; while (node && "index" in node && node._nodeName.length) { path.push([node.index, node._nodeName]); node = node.parentNode; } path.reverse(); return path.join(","); }, appropriateSelectorFor: function(justSelector) { var lowerCaseName = this.localName() || this.nodeName().toLowerCase(); var id = this.getAttribute("id"); if (id) { var selector = "#" + id; return (justSelector ? selector : lowerCaseName + selector); } var className = this.getAttribute("class"); if (className) { var selector = "." + className.trim().replace(/\s+/g, "."); return (justSelector ? selector : lowerCaseName + selector); } if (lowerCaseName === "input" && this.getAttribute("type")) return lowerCaseName + "[type=\"" + this.getAttribute("type") + "\"]"; return lowerCaseName; }, isAncestor: function(node) { if (!node) return false; var currentNode = node.parentNode; while (currentNode) { if (this === currentNode) return true; currentNode = currentNode.parentNode; } return false; }, isDescendant: function(descendant) { return descendant !== null && descendant.isAncestor(this); }, _setAttributesPayload: function(attrs) { var attributesChanged = !this._attributes || attrs.length !== this._attributes.length * 2; var oldAttributesMap = this._attributesMap || {}; this._attributes = []; this._attributesMap = {}; for (var i = 0; i < attrs.length; i += 2) { var name = attrs[i]; var value = attrs[i + 1]; this._addAttribute(name, value); if (attributesChanged) continue; if (!oldAttributesMap[name] || oldAttributesMap[name].value !== value) attributesChanged = true; } return attributesChanged; }, _insertChild: function(prev, payload) { var node = new WebInspector.DOMNode(this._domAgent, this.ownerDocument, this._isInShadowTree, payload); if (!prev) { if (!this.children) { this.children = this._shadowRoots.concat([ node ]); } else this.children.unshift(node); } else this.children.splice(this.children.indexOf(prev) + 1, 0, node); this._renumber(); return node; }, _removeChild: function(node) { this.children.splice(this.children.indexOf(node), 1); node.parentNode = null; node._updateChildUserPropertyCountsOnRemoval(this); this._renumber(); }, _setChildrenPayload: function(payloads) { if (this._contentDocument) return; this.children = this._shadowRoots.slice(); for (var i = 0; i < payloads.length; ++i) { var payload = payloads[i]; var node = new WebInspector.DOMNode(this._domAgent, this.ownerDocument, this._isInShadowTree, payload); this.children.push(node); } this._renumber(); }, _renumber: function() { this._childNodeCount = this.children.length; if (this._childNodeCount == 0) { this.firstChild = null; this.lastChild = null; return; } this.firstChild = this.children[0]; this.lastChild = this.children[this._childNodeCount - 1]; for (var i = 0; i < this._childNodeCount; ++i) { var child = this.children[i]; child.index = i; child.nextSibling = i + 1 < this._childNodeCount ? this.children[i + 1] : null; child.previousSibling = i - 1 >= 0 ? this.children[i - 1] : null; child.parentNode = this; } }, _addAttribute: function(name, value) { var attr = { name: name, value: value, _node: this }; this._attributesMap[name] = attr; this._attributes.push(attr); }, _setAttribute: function(name, value) { var attr = this._attributesMap[name]; if (attr) attr.value = value; else this._addAttribute(name, value); }, _removeAttribute: function(name) { var attr = this._attributesMap[name]; if (attr) { this._attributes.remove(attr); delete this._attributesMap[name]; } }, moveTo: function(targetNode, anchorNode, callback) { DOMAgent.moveTo(this.id, targetNode.id, anchorNode ? anchorNode.id : undefined, WebInspector.domAgent._markRevision(this, callback)); }, isXMLNode: function() { return !!this.ownerDocument && !!this.ownerDocument.xmlVersion; }, xPath: function(optimized) { if (this._nodeType === Node.DOCUMENT_NODE) return "/"; var steps = []; var contextNode = this; while (contextNode) { var step = contextNode._xPathValue(optimized); if (!step) break; steps.push(step); if (step.optimized) break; contextNode = contextNode.parentNode; } steps.reverse(); return (steps.length && steps[0].optimized ? "" : "/") + steps.join("/"); }, _xPathValue: function(optimized) { var ownValue; var ownIndex = this._xPathIndex(); if (ownIndex === -1) return null; switch (this._nodeType) { case Node.ELEMENT_NODE: if (optimized && this.getAttribute("id")) return new WebInspector.DOMNode.XPathStep("//*[@id=\"" + this.getAttribute("id") + "\"]", true); ownValue = this._localName; break; case Node.ATTRIBUTE_NODE: ownValue = "@" + this._nodeName; break; case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: ownValue = "text()"; break; case Node.PROCESSING_INSTRUCTION_NODE: ownValue = "processing-instruction()"; break; case Node.COMMENT_NODE: ownValue = "comment()"; break; case Node.DOCUMENT_NODE: ownValue = ""; break; default: ownValue = ""; break; } if (ownIndex > 0) ownValue += "[" + ownIndex + "]"; return new WebInspector.DOMNode.XPathStep(ownValue, this._nodeType === Node.DOCUMENT_NODE); }, _xPathIndex: function() { function areNodesSimilar(left, right) { if (left === right) return true; if (left._nodeType === Node.ELEMENT_NODE && right._nodeType === Node.ELEMENT_NODE) return left._localName === right._localName; if (left._nodeType === right._nodeType) return true; var leftType = left._nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left._nodeType; var rightType = right._nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : right._nodeType; return leftType === rightType; } var siblings = this.parentNode ? this.parentNode.children : null; if (!siblings) return 0; var hasSameNamedElements; for (var i = 0; i < siblings.length; ++i) { if (areNodesSimilar(this, siblings[i]) && siblings[i] !== this) { hasSameNamedElements = true; break; } } if (!hasSameNamedElements) return 0; var ownIndex = 1; for (var i = 0; i < siblings.length; ++i) { if (areNodesSimilar(this, siblings[i])) { if (siblings[i] === this) return ownIndex; ++ownIndex; } } return -1; }, _updateChildUserPropertyCountsOnRemoval: function(parentNode) { var result = {}; if (this._userProperties) { for (var name in this._userProperties) result[name] = (result[name] || 0) + 1; } if (this._descendantUserPropertyCounters) { for (var name in this._descendantUserPropertyCounters) { var counter = this._descendantUserPropertyCounters[name]; result[name] = (result[name] || 0) + counter; } } for (var name in result) parentNode._updateDescendantUserPropertyCount(name, -result[name]); }, _updateDescendantUserPropertyCount: function(name, delta) { if (!this._descendantUserPropertyCounters.hasOwnProperty(name)) this._descendantUserPropertyCounters[name] = 0; this._descendantUserPropertyCounters[name] += delta; if (!this._descendantUserPropertyCounters[name]) delete this._descendantUserPropertyCounters[name]; if (this.parentNode) this.parentNode._updateDescendantUserPropertyCount(name, delta); }, setUserProperty: function(name, value) { if (value === null) { this.removeUserProperty(name); return; } if (this.parentNode && !this._userProperties.hasOwnProperty(name)) this.parentNode._updateDescendantUserPropertyCount(name, 1); this._userProperties[name] = value; }, removeUserProperty: function(name) { if (!this._userProperties.hasOwnProperty(name)) return; delete this._userProperties[name]; if (this.parentNode) this.parentNode._updateDescendantUserPropertyCount(name, -1); }, getUserProperty: function(name) { return this._userProperties ? this._userProperties[name] : null; }, descendantUserPropertyCount: function(name) { return this._descendantUserPropertyCounters && this._descendantUserPropertyCounters[name] ? this._descendantUserPropertyCounters[name] : 0; }, resolveURL: function(url) { if (!url) return url; for (var frameOwnerCandidate = this; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) { if (frameOwnerCandidate.baseURL) return WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL, url); } return null; } } WebInspector.DOMDocument = function(domAgent, payload) { WebInspector.DOMNode.call(this, domAgent, this, false, payload); this.documentURL = payload.documentURL || ""; this.baseURL = (payload.baseURL); console.assert(this.baseURL); this.xmlVersion = payload.xmlVersion; this._listeners = {}; } WebInspector.DOMDocument.prototype = { __proto__: WebInspector.DOMNode.prototype } WebInspector.DOMAgent = function() { this._idToDOMNode = {}; this._document = null; this._attributeLoadNodeIds = {}; InspectorBackend.registerDOMDispatcher(new WebInspector.DOMDispatcher(this)); if (WebInspector.settings.emulateTouchEvents.get()) this._emulateTouchEventsChanged(); WebInspector.settings.emulateTouchEvents.addChangeListener(this._emulateTouchEventsChanged, this); } WebInspector.DOMAgent.Events = { AttrModified: "AttrModified", AttrRemoved: "AttrRemoved", CharacterDataModified: "CharacterDataModified", NodeInserted: "NodeInserted", NodeRemoved: "NodeRemoved", DocumentUpdated: "DocumentUpdated", ChildNodeCountUpdated: "ChildNodeCountUpdated", InspectElementRequested: "InspectElementRequested", UndoRedoRequested: "UndoRedoRequested", UndoRedoCompleted: "UndoRedoCompleted" } WebInspector.DOMAgent.prototype = { requestDocument: function(callback) { if (this._document) { if (callback) callback(this._document); return; } if (this._pendingDocumentRequestCallbacks) { this._pendingDocumentRequestCallbacks.push(callback); return; } this._pendingDocumentRequestCallbacks = [callback]; function onDocumentAvailable(error, root) { if (!error) this._setDocument(root); for (var i = 0; i < this._pendingDocumentRequestCallbacks.length; ++i) { var callback = this._pendingDocumentRequestCallbacks[i]; if (callback) callback(this._document); } delete this._pendingDocumentRequestCallbacks; } DOMAgent.getDocument(onDocumentAvailable.bind(this)); }, existingDocument: function() { return this._document; }, pushNodeToFrontend: function(objectId, callback) { var callbackCast = callback; this._dispatchWhenDocumentAvailable(DOMAgent.requestNode.bind(DOMAgent, objectId), callbackCast); }, pushNodeByPathToFrontend: function(path, callback) { var callbackCast = callback; this._dispatchWhenDocumentAvailable(DOMAgent.pushNodeByPathToFrontend.bind(DOMAgent, path), callbackCast); }, _wrapClientCallback: function(callback) { if (!callback) return; return function(error, result) { callback(error ? null : result); } }, _dispatchWhenDocumentAvailable: function(func, callback) { var callbackWrapper = this._wrapClientCallback(callback); function onDocumentAvailable() { if (this._document) func(callbackWrapper); else { if (callbackWrapper) callbackWrapper("No document"); } } this.requestDocument(onDocumentAvailable.bind(this)); }, _attributeModified: function(nodeId, name, value) { var node = this._idToDOMNode[nodeId]; if (!node) return; node._setAttribute(name, value); this.dispatchEventToListeners(WebInspector.DOMAgent.Events.AttrModified, { node: node, name: name }); }, _attributeRemoved: function(nodeId, name) { var node = this._idToDOMNode[nodeId]; if (!node) return; node._removeAttribute(name); this.dispatchEventToListeners(WebInspector.DOMAgent.Events.AttrRemoved, { node: node, name: name }); }, _inlineStyleInvalidated: function(nodeIds) { for (var i = 0; i < nodeIds.length; ++i) this._attributeLoadNodeIds[nodeIds[i]] = true; if ("_loadNodeAttributesTimeout" in this) return; this._loadNodeAttributesTimeout = setTimeout(this._loadNodeAttributes.bind(this), 0); }, _loadNodeAttributes: function() { function callback(nodeId, error, attributes) { if (error) { return; } var node = this._idToDOMNode[nodeId]; if (node) { if (node._setAttributesPayload(attributes)) this.dispatchEventToListeners(WebInspector.DOMAgent.Events.AttrModified, { node: node, name: "style" }); } } delete this._loadNodeAttributesTimeout; for (var nodeId in this._attributeLoadNodeIds) { var nodeIdAsNumber = parseInt(nodeId, 10); DOMAgent.getAttributes(nodeIdAsNumber, callback.bind(this, nodeIdAsNumber)); } this._attributeLoadNodeIds = {}; }, _characterDataModified: function(nodeId, newValue) { var node = this._idToDOMNode[nodeId]; node._nodeValue = newValue; this.dispatchEventToListeners(WebInspector.DOMAgent.Events.CharacterDataModified, node); }, nodeForId: function(nodeId) { return this._idToDOMNode[nodeId]; }, _documentUpdated: function() { this._setDocument(null); }, _setDocument: function(payload) { this._idToDOMNode = {}; if (payload && "nodeId" in payload) this._document = new WebInspector.DOMDocument(this, payload); else this._document = null; this.dispatchEventToListeners(WebInspector.DOMAgent.Events.DocumentUpdated, this._document); }, _setDetachedRoot: function(payload) { if (payload.nodeName === "#document") new WebInspector.DOMDocument(this, payload); else new WebInspector.DOMNode(this, null, false, payload); }, _setChildNodes: function(parentId, payloads) { if (!parentId && payloads.length) { this._setDetachedRoot(payloads[0]); return; } var parent = this._idToDOMNode[parentId]; parent._setChildrenPayload(payloads); }, _childNodeCountUpdated: function(nodeId, newValue) { var node = this._idToDOMNode[nodeId]; node._childNodeCount = newValue; this.dispatchEventToListeners(WebInspector.DOMAgent.Events.ChildNodeCountUpdated, node); }, _childNodeInserted: function(parentId, prevId, payload) { var parent = this._idToDOMNode[parentId]; var prev = this._idToDOMNode[prevId]; var node = parent._insertChild(prev, payload); this._idToDOMNode[node.id] = node; this.dispatchEventToListeners(WebInspector.DOMAgent.Events.NodeInserted, node); }, _childNodeRemoved: function(parentId, nodeId) { var parent = this._idToDOMNode[parentId]; var node = this._idToDOMNode[nodeId]; parent._removeChild(node); this._unbind(node); this.dispatchEventToListeners(WebInspector.DOMAgent.Events.NodeRemoved, {node: node, parent: parent}); }, _shadowRootPopped: function(rootId) { }, _unbind: function(node) { delete this._idToDOMNode[node.id]; for (var i = 0; node.children && i < node.children.length; ++i) this._unbind(node.children[i]); }, inspectElement: function(nodeId) { var node = this._idToDOMNode[nodeId]; if (node) this.dispatchEventToListeners(WebInspector.DOMAgent.Events.InspectElementRequested, node); }, performSearch: function(query, searchCallback) { this.cancelSearch(); function callback(error, searchId, resultsCount) { this._searchId = searchId; searchCallback(resultsCount); } DOMAgent.performSearch(query, callback.bind(this)); }, searchResult: function(index, callback) { if (this._searchId) { function mycallback(error, nodeIds) { if (error) { console.error(error); callback(null); return; } if (nodeIds.length != 1) return; callback(this._idToDOMNode[nodeIds[0]]); } DOMAgent.getSearchResults(this._searchId, index, index + 1, mycallback.bind(this)); } else callback(null); }, cancelSearch: function() { if (this._searchId) { DOMAgent.discardSearchResults(this._searchId); delete this._searchId; } }, querySelector: function(nodeId, selectors, callback) { var callbackCast = callback; DOMAgent.querySelector(nodeId, selectors, this._wrapClientCallback(callbackCast)); }, querySelectorAll: function(nodeId, selectors, callback) { var callbackCast = callback; DOMAgent.querySelectorAll(nodeId, selectors, this._wrapClientCallback(callbackCast)); }, highlightDOMNode: function(nodeId, mode, objectId) { if (this._hideDOMNodeHighlightTimeout) { clearTimeout(this._hideDOMNodeHighlightTimeout); delete this._hideDOMNodeHighlightTimeout; } if (objectId || nodeId) DOMAgent.highlightNode(this._buildHighlightConfig(mode), objectId ? undefined : nodeId, objectId); else DOMAgent.hideHighlight(); }, hideDOMNodeHighlight: function() { this.highlightDOMNode(0); }, highlightDOMNodeForTwoSeconds: function(nodeId) { this.highlightDOMNode(nodeId); this._hideDOMNodeHighlightTimeout = setTimeout(this.hideDOMNodeHighlight.bind(this), 2000); }, setInspectModeEnabled: function(enabled, callback) { DOMAgent.setInspectModeEnabled(enabled, this._buildHighlightConfig(), callback); }, _buildHighlightConfig: function(mode) { mode = mode || "all"; var highlightConfig = { showInfo: mode === "all", showRulers: WebInspector.settings.showMetricsRulers.get() }; if (mode === "all" || mode === "content") highlightConfig.contentColor = WebInspector.Color.PageHighlight.Content.toProtocolRGBA(); if (mode === "all" || mode === "padding") highlightConfig.paddingColor = WebInspector.Color.PageHighlight.Padding.toProtocolRGBA(); if (mode === "all" || mode === "border") highlightConfig.borderColor = WebInspector.Color.PageHighlight.Border.toProtocolRGBA(); if (mode === "all" || mode === "margin") highlightConfig.marginColor = WebInspector.Color.PageHighlight.Margin.toProtocolRGBA(); return highlightConfig; }, _markRevision: function(node, callback) { function wrapperFunction(error) { if (!error) this.markUndoableState(); if (callback) callback.apply(this, arguments); } return wrapperFunction.bind(this); }, _emulateTouchEventsChanged: function() { const injectedFunction = function() { const touchEvents = ["ontouchstart", "ontouchend", "ontouchmove", "ontouchcancel"]; var recepients = [window.__proto__, document.__proto__]; for (var i = 0; i < touchEvents.length; ++i) { for (var j = 0; j < recepients.length; ++j) { if (!(touchEvents[i] in recepients[j])) Object.defineProperty(recepients[j], touchEvents[i], { value: null, writable: true, configurable: true, enumerable: true }); } } } var emulationEnabled = WebInspector.settings.emulateTouchEvents.get(); if (emulationEnabled && !this._addTouchEventsScriptInjecting) { this._addTouchEventsScriptInjecting = true; PageAgent.addScriptToEvaluateOnLoad("(" + injectedFunction.toString() + ")", scriptAddedCallback.bind(this)); } else { if (typeof this._addTouchEventsScriptId !== "undefined") { PageAgent.removeScriptToEvaluateOnLoad(this._addTouchEventsScriptId); delete this._addTouchEventsScriptId; } } function scriptAddedCallback(error, scriptId) { delete this._addTouchEventsScriptInjecting; if (error) return; this._addTouchEventsScriptId = scriptId; } PageAgent.setTouchEmulationEnabled(emulationEnabled); }, markUndoableState: function() { DOMAgent.markUndoableState(); }, undo: function(callback) { function mycallback(error) { this.dispatchEventToListeners(WebInspector.DOMAgent.Events.UndoRedoCompleted); callback(error); } this.dispatchEventToListeners(WebInspector.DOMAgent.Events.UndoRedoRequested); DOMAgent.undo(callback); }, redo: function(callback) { function mycallback(error) { this.dispatchEventToListeners(WebInspector.DOMAgent.Events.UndoRedoCompleted); callback(error); } this.dispatchEventToListeners(WebInspector.DOMAgent.Events.UndoRedoRequested); DOMAgent.redo(callback); }, __proto__: WebInspector.Object.prototype } WebInspector.DOMDispatcher = function(domAgent) { this._domAgent = domAgent; } WebInspector.DOMDispatcher.prototype = { documentUpdated: function() { this._domAgent._documentUpdated(); }, attributeModified: function(nodeId, name, value) { this._domAgent._attributeModified(nodeId, name, value); }, attributeRemoved: function(nodeId, name) { this._domAgent._attributeRemoved(nodeId, name); }, inlineStyleInvalidated: function(nodeIds) { this._domAgent._inlineStyleInvalidated(nodeIds); }, characterDataModified: function(nodeId, characterData) { this._domAgent._characterDataModified(nodeId, characterData); }, setChildNodes: function(parentId, payloads) { this._domAgent._setChildNodes(parentId, payloads); }, childNodeCountUpdated: function(nodeId, childNodeCount) { this._domAgent._childNodeCountUpdated(nodeId, childNodeCount); }, childNodeInserted: function(parentNodeId, previousNodeId, payload) { this._domAgent._childNodeInserted(parentNodeId, previousNodeId, payload); }, childNodeRemoved: function(parentNodeId, nodeId) { this._domAgent._childNodeRemoved(parentNodeId, nodeId); }, shadowRootPushed: function(hostId, root) { this._domAgent._childNodeInserted(hostId, 0, root); }, shadowRootPopped: function(hostId, rootId) { this._domAgent._childNodeRemoved(hostId, rootId); } } WebInspector.domAgent = null; WebInspector.TestController = function() { } WebInspector.TestController.prototype = { notifyDone: function(callId, result) { var message = typeof result === "undefined" ? "\"<undefined>\"" : JSON.stringify(result); RuntimeAgent.evaluate("didEvaluateForTestInFrontend(" + callId + ", " + message + ")", "test"); } } WebInspector.evaluateForTestInFrontend = function(callId, script) { window.isUnderTest = true; function invokeMethod() { try { script = script + "//@ sourceURL=evaluateInWebInspector" + callId + ".js"; var result = window.eval(script); WebInspector.TestController.prototype.notifyDone(callId, result); } catch (e) { WebInspector.TestController.prototype.notifyDone(callId, e.toString()); } } InspectorBackend.runAfterPendingDispatches(invokeMethod); } WebInspector.Dialog = function(relativeToElement, delegate) { this._delegate = delegate; this._relativeToElement = relativeToElement; this._glassPaneElement = document.body.createChild("div"); this._glassPaneElement.className = "dialog-glass-pane"; this._glassPaneElement.tabIndex = 0; this._glassPaneElement.addEventListener("focus", this._onGlassPaneFocus.bind(this), false); this._element = this._glassPaneElement.createChild("div"); this._element.tabIndex = 0; this._element.addEventListener("focus", this._onFocus.bind(this), false); this._element.addEventListener("keydown", this._onKeyDown.bind(this), false); this._closeKeys = [ WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, ]; delegate.show(this._element); this._position(); this._windowResizeHandler = this._position.bind(this); window.addEventListener("resize", this._windowResizeHandler, true); this._previousFocusElement = WebInspector.currentFocusElement(); this._delegate.focus(); } WebInspector.Dialog.currentInstance = function() { return WebInspector.Dialog._instance; } WebInspector.Dialog.show = function(relativeToElement, delegate) { if (WebInspector.Dialog._instance) return; WebInspector.Dialog._instance = new WebInspector.Dialog(relativeToElement, delegate); } WebInspector.Dialog.hide = function() { if (!WebInspector.Dialog._instance) return; WebInspector.Dialog._instance._hide(); } WebInspector.Dialog.prototype = { _hide: function() { if (this._isHiding) return; this._isHiding = true; this._delegate.willHide(); if (this._element.isSelfOrAncestor(document.activeElement)) WebInspector.setCurrentFocusElement(this._previousFocusElement); delete WebInspector.Dialog._instance; document.body.removeChild(this._glassPaneElement); window.removeEventListener("resize", this._windowResizeHandler, true); }, _onGlassPaneFocus: function(event) { this._hide(); }, _onFocus: function(event) { this._delegate.focus(); }, _position: function() { this._delegate.position(this._element, this._relativeToElement); }, _onKeyDown: function(event) { if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Tab.code) { event.preventDefault(); return; } if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Enter.code) this._delegate.onEnter(); if (this._closeKeys.indexOf(event.keyCode) >= 0) { this._hide(); event.consume(true); } } }; WebInspector.DialogDelegate = function() { } WebInspector.DialogDelegate.prototype = { show: function(element) { element.appendChild(this.element); this.element.addStyleClass("dialog-contents"); element.addStyleClass("dialog"); }, position: function(element, relativeToElement) { var offset = relativeToElement.offsetRelativeToWindow(window); var positionX = offset.x + (relativeToElement.offsetWidth - element.offsetWidth) / 2; positionX = Number.constrain(positionX, 0, window.innerWidth - element.offsetWidth); var positionY = offset.y + (relativeToElement.offsetHeight - element.offsetHeight) / 2; positionY = Number.constrain(positionY, 0, window.innerHeight - element.offsetHeight); element.style.left = positionX + "px"; element.style.top = positionY + "px"; }, focus: function() { }, onEnter: function() { }, willHide: function() { }, __proto__: WebInspector.Object.prototype } WebInspector.GoToLineDialog = function(view) { WebInspector.DialogDelegate.call(this); this.element = document.createElement("div"); this.element.className = "go-to-line-dialog"; this.element.createChild("label").textContent = WebInspector.UIString("Go to line: "); this._input = this.element.createChild("input"); this._input.setAttribute("type", "text"); this._input.setAttribute("size", 6); this._goButton = this.element.createChild("button"); this._goButton.textContent = WebInspector.UIString("Go"); this._goButton.addEventListener("click", this._onGoClick.bind(this), false); this._view = view; } WebInspector.GoToLineDialog.install = function(panel, viewGetter) { function showGoToLineDialog() { var view = viewGetter(); if (view) WebInspector.GoToLineDialog._show(view); } var goToLineShortcut = WebInspector.GoToLineDialog.createShortcut(); panel.registerShortcuts([goToLineShortcut], showGoToLineDialog); } WebInspector.GoToLineDialog._show = function(sourceView) { if (!sourceView || !sourceView.canHighlightLine()) return; WebInspector.Dialog.show(sourceView.element, new WebInspector.GoToLineDialog(sourceView)); } WebInspector.GoToLineDialog.createShortcut = function() { var isMac = WebInspector.isMac(); var shortcut; if (isMac) return WebInspector.KeyboardShortcut.makeDescriptor("l", WebInspector.KeyboardShortcut.Modifiers.Meta); return WebInspector.KeyboardShortcut.makeDescriptor("g", WebInspector.KeyboardShortcut.Modifiers.Ctrl); } WebInspector.GoToLineDialog.prototype = { focus: function() { WebInspector.setCurrentFocusElement(this._input); this._input.select(); }, _onGoClick: function() { this._applyLineNumber(); WebInspector.Dialog.hide(); }, _applyLineNumber: function() { var value = this._input.value; var lineNumber = parseInt(value, 10) - 1; if (!isNaN(lineNumber) && lineNumber >= 0) this._view.highlightLine(lineNumber); }, onEnter: function() { this._applyLineNumber(); }, __proto__: WebInspector.DialogDelegate.prototype } WebInspector.SidebarOverlay = function(view, widthSettingName, minimalWidth) { this.element = document.createElement("div"); this.element.className = "sidebar-overlay"; this._view = view; this._widthSettingName = widthSettingName; this._minimalWidth = minimalWidth; this._savedWidth = minimalWidth || 300; if (this._widthSettingName) WebInspector.settings[this._widthSettingName] = WebInspector.settings.createSetting(this._widthSettingName, undefined); this._resizerElement = document.createElement("div"); this._resizerElement.className = "sidebar-overlay-resizer"; this._installResizer(this._resizerElement); } WebInspector.SidebarOverlay.prototype = { show: function(relativeToElement) { relativeToElement.appendChild(this.element); relativeToElement.addStyleClass("sidebar-overlay-shown"); this._view.show(this.element); this.element.appendChild(this._resizerElement); if (this._resizerWidgetElement) this.element.appendChild(this._resizerWidgetElement); this.position(relativeToElement); }, position: function(relativeToElement) { this._totalWidth = relativeToElement.offsetWidth; this._setWidth(this._preferredWidth()); }, focus: function() { WebInspector.setCurrentFocusElement(this._view.element); }, hide: function() { var element = this.element.parentElement; if (!element) return; this._view.detach(); element.removeChild(this.element); element.removeStyleClass("sidebar-overlay-shown"); this.element.removeChild(this._resizerElement); if (this._resizerWidgetElement) this.element.removeChild(this._resizerWidgetElement); }, _setWidth: function(newWidth) { var width = Number.constrain(newWidth, this._minimalWidth, this._totalWidth); if (this._width === width) return; this.element.style.width = width + "px"; this._resizerElement.style.left = (width - 3) + "px"; this._width = width; this._view.doResize(); this._saveWidth(); }, _preferredWidth: function() { if (!this._widthSettingName) return this._savedWidth; return WebInspector.settings[this._widthSettingName].get() || this._savedWidth; }, _saveWidth: function() { this._savedWidth = this._width; if (!this._widthSettingName) return; WebInspector.settings[this._widthSettingName].set(this._width); }, _startResizerDragging: function(event) { var width = this._width; this._dragOffset = width - event.pageX; return true; }, _resizerDragging: function(event) { var width = event.pageX + this._dragOffset; this._setWidth(width); event.preventDefault(); }, _endResizerDragging: function(event) { delete this._dragOffset; }, _installResizer: function(resizerElement) { WebInspector.installDragHandle(resizerElement, this._startResizerDragging.bind(this), this._resizerDragging.bind(this), this._endResizerDragging.bind(this), "ew-resize"); }, set resizerWidgetElement(resizerWidgetElement) { this._resizerWidgetElement = resizerWidgetElement; this._installResizer(resizerWidgetElement); } } WebInspector.SettingsScreen = function(onHide) { WebInspector.HelpScreen.call(this); this.element.id = "settings-screen"; this._onHide = onHide; this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.element.addStyleClass("help-window-main"); var settingsLabelElement = document.createElement("div"); settingsLabelElement.className = "help-window-label"; settingsLabelElement.createTextChild(WebInspector.UIString("Settings")); this._tabbedPane.element.insertBefore(settingsLabelElement, this._tabbedPane.element.firstChild); this._tabbedPane.element.appendChild(this._createCloseButton()); this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.General, WebInspector.UIString("General"), new WebInspector.GenericSettingsTab()); if (!WebInspector.experimentsSettings.showOverridesInDrawer.isEnabled()) this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.Overrides, WebInspector.UIString("Overrides"), new WebInspector.OverridesSettingsTab()); if (WebInspector.experimentsSettings.experimentsEnabled) this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.Experiments, WebInspector.UIString("Experiments"), new WebInspector.ExperimentsSettingsTab()); this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.Shortcuts, WebInspector.UIString("Shortcuts"), WebInspector.shortcutsScreen.createShortcutsTabView()); this._tabbedPane.shrinkableTabs = false; this._tabbedPane.verticalTabLayout = true; this._lastSelectedTabSetting = WebInspector.settings.createSetting("lastSelectedSettingsTab", WebInspector.SettingsScreen.Tabs.General); this.selectTab(this._lastSelectedTabSetting.get()); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); } WebInspector.SettingsScreen.Tabs = { General: "general", Overrides: "overrides", Experiments: "experiments", Shortcuts: "shortcuts" } WebInspector.SettingsScreen.prototype = { selectTab: function(tabId) { this._tabbedPane.selectTab(tabId); }, _tabSelected: function(event) { this._lastSelectedTabSetting.set(this._tabbedPane.selectedTabId); }, wasShown: function() { this._tabbedPane.show(this.element); WebInspector.HelpScreen.prototype.wasShown.call(this); }, isClosingKey: function(keyCode) { return [ WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, ].indexOf(keyCode) >= 0; }, willHide: function() { this._onHide(); WebInspector.HelpScreen.prototype.willHide.call(this); }, __proto__: WebInspector.HelpScreen.prototype } WebInspector.SettingsTab = function(name, id) { WebInspector.View.call(this); this.element.className = "settings-tab-container"; if (id) this.element.id = id; var header = this.element.createChild("header"); header.createChild("h3").appendChild(document.createTextNode(name)); this.containerElement = this.element.createChild("div", "help-container-wrapper").createChild("div", "settings-tab help-content help-container"); } WebInspector.SettingsTab.prototype = { _appendSection: function(name) { var block = this.containerElement.createChild("div", "help-block"); if (name) block.createChild("div", "help-section-title").textContent = name; return block; }, _createCheckboxSetting: function(name, setting, omitParagraphElement, inputElement) { var input = inputElement || document.createElement("input"); input.type = "checkbox"; input.name = name; input.checked = setting.get(); function listener() { setting.set(input.checked); } input.addEventListener("click", listener, false); var label = document.createElement("label"); label.appendChild(input); label.appendChild(document.createTextNode(name)); if (omitParagraphElement) return label; var p = document.createElement("p"); p.appendChild(label); return p; }, _createSelectSetting: function(name, options, setting) { var fieldsetElement = document.createElement("fieldset"); fieldsetElement.createChild("label").textContent = name; var select = document.createElement("select"); var settingValue = setting.get(); for (var i = 0; i < options.length; ++i) { var option = options[i]; select.add(new Option(option[0], option[1])); if (settingValue === option[1]) select.selectedIndex = i; } function changeListener(e) { setting.set(e.target.value); } select.addEventListener("change", changeListener, false); fieldsetElement.appendChild(select); var p = document.createElement("p"); p.appendChild(fieldsetElement); return p; }, _createRadioSetting: function(name, options, setting) { var pp = document.createElement("p"); var fieldsetElement = document.createElement("fieldset"); var legendElement = document.createElement("legend"); legendElement.textContent = name; fieldsetElement.appendChild(legendElement); function clickListener(e) { setting.set(e.target.value); } var settingValue = setting.get(); for (var i = 0; i < options.length; ++i) { var p = document.createElement("p"); var label = document.createElement("label"); p.appendChild(label); var input = document.createElement("input"); input.type = "radio"; input.name = setting.name; input.value = options[i][0]; input.addEventListener("click", clickListener, false); if (settingValue == input.value) input.checked = true; label.appendChild(input); label.appendChild(document.createTextNode(options[i][1])); fieldsetElement.appendChild(p); } pp.appendChild(fieldsetElement); return pp; }, _createCustomSetting: function(name, element) { var p = document.createElement("p"); var fieldsetElement = document.createElement("fieldset"); fieldsetElement.createChild("label").textContent = name; fieldsetElement.appendChild(element); p.appendChild(fieldsetElement); return p; }, __proto__: WebInspector.View.prototype } WebInspector.GenericSettingsTab = function() { WebInspector.SettingsTab.call(this, WebInspector.UIString("General")); var p = this._appendSection(); if (Preferences.exposeDisableCache) p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Disable cache"), WebInspector.settings.cacheDisabled)); var disableJSElement = this._createCheckboxSetting(WebInspector.UIString("Disable JavaScript"), WebInspector.settings.javaScriptDisabled); p.appendChild(disableJSElement); WebInspector.settings.javaScriptDisabled.addChangeListener(this._javaScriptDisabledChanged, this); this._disableJSCheckbox = disableJSElement.getElementsByTagName("input")[0]; this._updateScriptDisabledCheckbox(); p = this._appendSection(WebInspector.UIString("Appearance")); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show toolbar icons"), WebInspector.settings.showToolbarIcons)); p = this._appendSection(WebInspector.UIString("Elements")); p.appendChild(this._createRadioSetting(WebInspector.UIString("Color format"), [ [ WebInspector.Color.Format.Original, WebInspector.UIString("As authored") ], [ WebInspector.Color.Format.HEX, "HEX: #DAC0DE" ], [ WebInspector.Color.Format.RGB, "RGB: rgb(128, 255, 255)" ], [ WebInspector.Color.Format.HSL, "HSL: hsl(300, 80%, 90%)" ] ], WebInspector.settings.colorFormat)); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show user agent styles"), WebInspector.settings.showUserAgentStyles)); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Word wrap"), WebInspector.settings.domWordWrap)); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show Shadow DOM"), WebInspector.settings.showShadowDOM)); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show rulers"), WebInspector.settings.showMetricsRulers)); p = this._appendSection(WebInspector.UIString("Rendering")); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show paint rectangles"), WebInspector.settings.showPaintRects)); WebInspector.settings.showPaintRects.addChangeListener(this._showPaintRectsChanged, this); if (Capabilities.canShowFPSCounter) { p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show FPS meter"), WebInspector.settings.showFPSCounter)); WebInspector.settings.showFPSCounter.addChangeListener(this._showFPSCounterChanged, this); } p = this._appendSection(WebInspector.UIString("Sources")); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show folders"), WebInspector.settings.showScriptFolders)); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Search in content scripts"), WebInspector.settings.searchInContentScripts)); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Enable source maps"), WebInspector.settings.sourceMapsEnabled)); if (WebInspector.experimentsSettings.isEnabled("sass")) p.appendChild(this._createCSSAutoReloadControls()); var indentationElement = this._createSelectSetting(WebInspector.UIString("Indentation"), [ [ WebInspector.UIString("2 spaces"), WebInspector.TextEditorModel.Indent.TwoSpaces ], [ WebInspector.UIString("4 spaces"), WebInspector.TextEditorModel.Indent.FourSpaces ], [ WebInspector.UIString("8 spaces"), WebInspector.TextEditorModel.Indent.EightSpaces ], [ WebInspector.UIString("Tab character"), WebInspector.TextEditorModel.Indent.TabCharacter ] ], WebInspector.settings.textEditorIndent); indentationElement.firstChild.className = "toplevel"; p.appendChild(indentationElement); p = this._appendSection(WebInspector.UIString("Profiler")); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show objects' hidden properties"), WebInspector.settings.showHeapSnapshotObjectsHiddenProperties)); if (WebInspector.experimentsSettings.nativeMemorySnapshots.isEnabled()) p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show uninstrumented native memory"), WebInspector.settings.showNativeSnapshotUninstrumentedSize)); if (Capabilities.timelineCanMonitorMainThread) { p = this._appendSection(WebInspector.UIString("Timeline")); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show CPU activity on the ruler"), WebInspector.settings.showCpuOnTimelineRuler)); } p = this._appendSection(WebInspector.UIString("Console")); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Log XMLHttpRequests"), WebInspector.settings.monitoringXHREnabled)); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Preserve log upon navigation"), WebInspector.settings.preserveConsoleLog)); if (WebInspector.extensionServer.hasExtensions()) { var handlerSelector = new WebInspector.HandlerSelector(WebInspector.openAnchorLocationRegistry); p = this._appendSection(WebInspector.UIString("Extensions")); p.appendChild(this._createCustomSetting(WebInspector.UIString("Open links in"), handlerSelector.element)); } } WebInspector.GenericSettingsTab.prototype = { _showPaintRectsChanged: function() { PageAgent.setShowPaintRects(WebInspector.settings.showPaintRects.get()); }, _showFPSCounterChanged: function() { PageAgent.setShowFPSCounter(WebInspector.settings.showFPSCounter.get()); }, _updateScriptDisabledCheckbox: function() { function executionStatusCallback(error, status) { if (error || !status) return; switch (status) { case "forbidden": this._disableJSCheckbox.checked = true; this._disableJSCheckbox.disabled = true; break; case "disabled": this._disableJSCheckbox.checked = true; break; default: this._disableJSCheckbox.checked = false; break; } } PageAgent.getScriptExecutionStatus(executionStatusCallback.bind(this)); }, _javaScriptDisabledChanged: function() { PageAgent.setScriptExecutionDisabled(WebInspector.settings.javaScriptDisabled.get(), this._updateScriptDisabledCheckbox.bind(this)); }, _createCSSAutoReloadControls: function() { var fragment = document.createDocumentFragment(); var labelElement = fragment.createChild("label"); var checkboxElement = labelElement.createChild("input"); checkboxElement.type = "checkbox"; checkboxElement.checked = WebInspector.settings.cssReloadEnabled.get(); checkboxElement.addEventListener("click", checkboxClicked, false); labelElement.appendChild(document.createTextNode(WebInspector.UIString("Auto-reload CSS upon Sass save"))); var fieldsetElement = fragment.createChild("fieldset"); fieldsetElement.disabled = !checkboxElement.checked; var p = fieldsetElement.createChild("p"); p.appendChild(document.createTextNode(WebInspector.UIString("Timeout (ms)"))); p.appendChild(document.createTextNode(" ")); var timeoutInput = p.createChild("input"); timeoutInput.value = WebInspector.settings.cssReloadTimeout.get(); timeoutInput.className = "numeric"; timeoutInput.style.width = "60px"; timeoutInput.maxLength = 8; timeoutInput.addEventListener("blur", blurListener, false); return fragment; function checkboxClicked() { var reloadEnabled = checkboxElement.checked; WebInspector.settings.cssReloadEnabled.set(reloadEnabled); fieldsetElement.disabled = !reloadEnabled; } function blurListener() { var value = timeoutInput.value; if (!isFinite(value) || value <= 0) { timeoutInput.value = WebInspector.settings.cssReloadTimeout.get(); return; } WebInspector.settings.cssReloadTimeout.set(Number(value)); } }, __proto__: WebInspector.SettingsTab.prototype } WebInspector.OverridesSettingsTab = function() { WebInspector.SettingsTab.call(this, WebInspector.UIString("Overrides"), "overrides-tab-content"); this._view = new WebInspector.OverridesView(); this.containerElement.parentElement.appendChild(this._view.containerElement); this.containerElement.remove(); this.containerElement = this._view.containerElement; } WebInspector.OverridesSettingsTab.prototype = { __proto__: WebInspector.SettingsTab.prototype } WebInspector.ExperimentsSettingsTab = function() { WebInspector.SettingsTab.call(this, WebInspector.UIString("Experiments"), "experiments-tab-content"); var experiments = WebInspector.experimentsSettings.experiments; if (experiments.length) { var experimentsSection = this._appendSection(); experimentsSection.appendChild(this._createExperimentsWarningSubsection()); for (var i = 0; i < experiments.length; ++i) experimentsSection.appendChild(this._createExperimentCheckbox(experiments[i])); } } WebInspector.ExperimentsSettingsTab.prototype = { _createExperimentsWarningSubsection: function() { var subsection = document.createElement("div"); var warning = subsection.createChild("span", "settings-experiments-warning-subsection-warning"); warning.textContent = WebInspector.UIString("WARNING:"); subsection.appendChild(document.createTextNode(" ")); var message = subsection.createChild("span", "settings-experiments-warning-subsection-message"); message.textContent = WebInspector.UIString("These experiments could be dangerous and may require restart."); return subsection; }, _createExperimentCheckbox: function(experiment) { var input = document.createElement("input"); input.type = "checkbox"; input.name = experiment.name; input.checked = experiment.isEnabled(); function listener() { experiment.setEnabled(input.checked); } input.addEventListener("click", listener, false); var p = document.createElement("p"); var label = document.createElement("label"); label.appendChild(input); label.appendChild(document.createTextNode(WebInspector.UIString(experiment.title))); p.appendChild(label); return p; }, __proto__: WebInspector.SettingsTab.prototype } WebInspector.SettingsController = function() { this._statusBarButton = new WebInspector.StatusBarButton(WebInspector.UIString("Settings"), "settings-status-bar-item"); if (WebInspector.experimentsSettings.showOverridesInDrawer.isEnabled()) this._statusBarButton.element.addEventListener("mousedown", this._mouseDown.bind(this), false); else this._statusBarButton.element.addEventListener("mouseup", this._mouseUp.bind(this), false); this._settingsScreen; } WebInspector.SettingsController.prototype = { get statusBarItem() { return this._statusBarButton.element; }, _mouseDown: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Overrides"), showOverrides.bind(this)); contextMenu.appendItem(WebInspector.UIString("Settings"), showSettings.bind(this)); function showOverrides() { if (this._settingsScreenVisible) this._hideSettingsScreen(); WebInspector.OverridesView.showInDrawer(); } function showSettings() { if (!this._settingsScreenVisible) this.showSettingsScreen(); } contextMenu.showSoftMenu(); }, _mouseUp: function(event) { this.showSettingsScreen(); }, _onHideSettingsScreen: function() { delete this._settingsScreenVisible; }, showSettingsScreen: function(tabId) { if (!this._settingsScreen) this._settingsScreen = new WebInspector.SettingsScreen(this._onHideSettingsScreen.bind(this)); if (tabId) this._settingsScreen.selectTab(tabId); this._settingsScreen.showModal(); this._settingsScreenVisible = true; }, _hideSettingsScreen: function() { if (this._settingsScreen) this._settingsScreen.hide(); }, resize: function() { if (this._settingsScreen && this._settingsScreen.isShowing()) this._settingsScreen.doResize(); } } WebInspector.ShortcutsScreen = function() { this._sections = ({}); } WebInspector.ShortcutsScreen.prototype = { section: function(name) { var section = this._sections[name]; if (!section) this._sections[name] = section = new WebInspector.ShortcutsSection(name); return section; }, createShortcutsTabView: function() { var orderedSections = []; for (var section in this._sections) orderedSections.push(this._sections[section]); function compareSections(a, b) { return a.order - b.order; } orderedSections.sort(compareSections); var view = new WebInspector.View(); view.element.className = "settings-tab-container"; view.element.createChild("header").createChild("h3").appendChild(document.createTextNode(WebInspector.UIString("Shortcuts"))); var container = view.element.createChild("div", "help-container-wrapper").createChild("div"); container.className = "help-content help-container"; for (var i = 0; i < orderedSections.length; ++i) orderedSections[i].renderSection(container); return view; } } WebInspector.shortcutsScreen = null; WebInspector.ShortcutsSection = function(name) { this.name = name; this._lines = ([]); this.order = ++WebInspector.ShortcutsSection._sequenceNumber; }; WebInspector.ShortcutsSection._sequenceNumber = 0; WebInspector.ShortcutsSection.prototype = { addKey: function(key, description) { this._addLine(this._renderKey(key), description); }, addRelatedKeys: function(keys, description) { this._addLine(this._renderSequence(keys, "/"), description); }, addAlternateKeys: function(keys, description) { this._addLine(this._renderSequence(keys, WebInspector.UIString("or")), description); }, _addLine: function(keyElement, description) { this._lines.push({ key: keyElement, text: description }) }, renderSection: function(container) { var parent = container.createChild("div", "help-block"); var headLine = parent.createChild("div", "help-line"); headLine.createChild("div", "help-key-cell"); headLine.createChild("div", "help-section-title help-cell").textContent = this.name; for (var i = 0; i < this._lines.length; ++i) { var line = parent.createChild("div", "help-line"); var keyCell = line.createChild("div", "help-key-cell"); keyCell.appendChild(this._lines[i].key); keyCell.appendChild(this._createSpan("help-key-delimiter", ":")); line.createChild("div", "help-cell").textContent = this._lines[i].text; } }, _renderSequence: function(sequence, delimiter) { var delimiterSpan = this._createSpan("help-key-delimiter", delimiter); return this._joinNodes(sequence.map(this._renderKey.bind(this)), delimiterSpan); }, _renderKey: function(key) { var keyName = key.name; var plus = this._createSpan("help-combine-keys", "+"); return this._joinNodes(keyName.split(" + ").map(this._createSpan.bind(this, "help-key monospace")), plus); }, _createSpan: function(className, textContent) { var node = document.createElement("span"); node.className = className; node.textContent = textContent; return node; }, _joinNodes: function(nodes, delimiter) { var result = document.createDocumentFragment(); for (var i = 0; i < nodes.length; ++i) { if (i > 0) result.appendChild(delimiter.cloneNode(true)); result.appendChild(nodes[i]); } return result; } } WebInspector.OverridesView = function() { WebInspector.View.call(this); this.registerRequiredCSS("helpScreen.css"); this.element.addStyleClass("fill"); this.element.addStyleClass("help-window-main"); this.element.addStyleClass("settings-tab-container"); var paneContent = this.element.createChild("div", "tabbed-pane-content"); function appendBlockTo(targetElement, contentElement) { var blockElement = targetElement.createChild("div", "help-block"); blockElement.appendChild(contentElement); } var headerTitle = paneContent.createChild("header").createChild("h3"); headerTitle.appendChild(document.createTextNode(WebInspector.UIString("Overrides"))); var container = paneContent.createChild("div", "help-container-wrapper").createChild("div", "settings-tab help-content help-container"); this.containerElement = container; appendBlockTo(container, this._createUserAgentControl()); if (Capabilities.canOverrideDeviceMetrics) appendBlockTo(container, this._createDeviceMetricsControl()); if (Capabilities.canOverrideGeolocation) appendBlockTo(container, this._createGeolocationOverrideControl()); if (Capabilities.canOverrideDeviceOrientation) appendBlockTo(container, this._createDeviceOrientationOverrideControl()); appendBlockTo(container, this._createCheckboxSetting(WebInspector.UIString("Emulate touch events"), WebInspector.settings.emulateTouchEvents)); appendBlockTo(container, this._createMediaEmulationElement()); this._statusElement = document.createElement("span"); this._statusElement.textContent = WebInspector.UIString("Overrides"); } WebInspector.OverridesView.showInDrawer = function() { if (!WebInspector.OverridesView._view) WebInspector.OverridesView._view = new WebInspector.OverridesView(); var view = WebInspector.OverridesView._view; WebInspector.showViewInDrawer(view._statusElement, view); } WebInspector.OverridesView.prototype = { _createCheckboxSetting: function(name, setting, omitParagraphElement, inputElement) { var input = inputElement || document.createElement("input"); input.type = "checkbox"; input.name = name; input.checked = setting.get(); function listener() { setting.set(input.checked); } input.addEventListener("click", listener, false); var label = document.createElement("label"); label.appendChild(input); label.appendChild(document.createTextNode(name)); if (omitParagraphElement) return label; var p = document.createElement("p"); p.appendChild(label); return p; }, _createUserAgentControl: function() { var userAgent = WebInspector.settings.userAgent.get(); var p = document.createElement("p"); var labelElement = p.createChild("label"); var checkboxElement = labelElement.createChild("input"); checkboxElement.type = "checkbox"; checkboxElement.checked = false; labelElement.appendChild(document.createTextNode(WebInspector.UIString("User Agent"))); p.appendChild(this._createUserAgentSelectRowElement(checkboxElement)); return p; }, _createUserAgentSelectRowElement: function(checkboxElement) { var userAgent = WebInspector.settings.userAgent.get(); const userAgents = [ ["Internet Explorer 9", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"], ["Internet Explorer 8", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"], ["Internet Explorer 7", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"], ["Firefox 7 \u2014 Windows", "Mozilla/5.0 (Windows NT 6.1; Intel Mac OS X 10.6; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"], ["Firefox 7 \u2014 Mac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"], ["Firefox 4 \u2014 Windows", "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"], ["Firefox 4 \u2014 Mac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"], ["Firefox 14 \u2014 Android Mobile", "Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0"], ["Firefox 14 \u2014 Android Tablet", "Mozilla/5.0 (Android; Tablet; rv:14.0) Gecko/14.0 Firefox/14.0"], ["Chrome \u2014 Android Mobile", "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19"], ["Chrome \u2014 Android Tablet", "Mozilla/5.0 (Linux; Android 4.1.2; Nexus 7 Build/JZ054K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19"], ["iPhone \u2014 iOS 5", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3", "640x960x1"], ["iPhone \u2014 iOS 4", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5", "640x960x1"], ["iPad \u2014 iOS 5", "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3", "1024x768x1"], ["iPad \u2014 iOS 4", "Mozilla/5.0 (iPad; CPU OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5", "1024x768x1"], ["Android 2.3 \u2014 Nexus S", "Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1", "480x800x1.1"], ["Android 4.0.2 \u2014 Galaxy Nexus", "Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", "720x1280x1.1"], ["BlackBerry \u2014 PlayBook 2.1", "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+", "1024x600x1"], ["BlackBerry \u2014 9900", "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0.187 Mobile Safari/534.11+", "640x480x1"], ["BlackBerry \u2014 BB10", "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.1+ (KHTML, like Gecko) Version/10.0.0.1337 Mobile Safari/537.1+", "768x1280x1"], ["MeeGo \u2014 Nokia N9", "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13", "480x854x1"], [WebInspector.UIString("Other..."), "Other"] ]; var fieldsetElement = document.createElement("fieldset"); this._selectElement = fieldsetElement.createChild("select"); this._otherUserAgentElement = fieldsetElement.createChild("input"); this._otherUserAgentElement.type = "text"; this._otherUserAgentElement.value = userAgent; this._otherUserAgentElement.title = userAgent; this._userAgentFieldsetElement = fieldsetElement; var selectionRestored = false; for (var i = 0; i < userAgents.length; ++i) { var agent = userAgents[i]; var option = new Option(agent[0], agent[1]); option._metrics = agent[2] ? agent[2] : ""; this._selectElement.add(option); if (userAgent === agent[1]) { this._selectElement.selectedIndex = i; selectionRestored = true; } } if (!selectionRestored) { if (!userAgent) this._selectElement.selectedIndex = 0; else this._selectElement.selectedIndex = userAgents.length - 1; } this._selectElement.addEventListener("change", this._selectionChanged.bind(this, true), false); fieldsetElement.addEventListener("dblclick", textDoubleClicked.bind(this), false); this._otherUserAgentElement.addEventListener("blur", textChanged.bind(this), false); function textDoubleClicked() { this._selectElement.selectedIndex = userAgents.length - 1; this._selectionChanged(); } function textChanged() { WebInspector.settings.userAgent.set(this._otherUserAgentElement.value); } function checkboxClicked() { if (checkboxElement.checked) { this._userAgentFieldsetElement.disabled = false; this._selectionChanged(); } else { this._userAgentFieldsetElement.disabled = true; this._otherUserAgentElement.disabled = true; } WebInspector.userAgentSupport.toggleUserAgentOverride(checkboxElement.checked); } checkboxElement.addEventListener("click", checkboxClicked.bind(this), false); checkboxClicked.call(this); return fieldsetElement; }, _selectionChanged: function(isUserGesture) { var value = this._selectElement.options[this._selectElement.selectedIndex].value; if (value !== "Other") { WebInspector.settings.userAgent.set(value); this._otherUserAgentElement.value = value; this._otherUserAgentElement.title = value; this._otherUserAgentElement.disabled = true; } else { this._otherUserAgentElement.disabled = false; this._otherUserAgentElement.focus(); } if (isUserGesture && Capabilities.canOverrideDeviceMetrics) { var metrics = this._selectElement.options[this._selectElement.selectedIndex]._metrics; this._setDeviceMetricsOverride(WebInspector.UserAgentSupport.DeviceMetrics.parseSetting(metrics), false, true); } }, _createInput: function(parentElement, id, defaultText, eventListener, numeric) { var element = parentElement.createChild("input"); element.id = id; element.type = "text"; element.maxLength = 12; element.style.width = "80px"; element.value = defaultText; element.align = "right"; if (numeric) element.className = "numeric"; element.addEventListener("blur", eventListener, false); return element; }, _createDeviceMetricsControl: function() { const metricsSetting = WebInspector.settings.deviceMetrics.get(); var metrics = WebInspector.UserAgentSupport.DeviceMetrics.parseSetting(metricsSetting); const p = document.createElement("p"); const labelElement = p.createChild("label"); const checkboxElement = labelElement.createChild("input"); checkboxElement.id = "metrics-override-checkbox"; checkboxElement.type = "checkbox"; checkboxElement.checked = false; checkboxElement.addEventListener("click", this._onMetricsCheckboxClicked.bind(this), false); this._metricsCheckboxElement = checkboxElement; labelElement.appendChild(document.createTextNode(WebInspector.UIString("Device metrics"))); const metricsSectionElement = this._createDeviceMetricsElement(metrics); p.appendChild(metricsSectionElement); this._metricsSectionElement = metricsSectionElement; this._onMetricsCheckboxClicked(); return p; }, _onMetricsCheckboxClicked: function() { var controlsDisabled = !this._metricsCheckboxElement.checked; this._deviceMetricsFieldsetElement.disabled = controlsDisabled; if (controlsDisabled) { WebInspector.userAgentSupport.toggleDeviceMetricsOverride(false); return; } var metrics = WebInspector.UserAgentSupport.DeviceMetrics.parseUserInput(this._widthOverrideElement.value, this._heightOverrideElement.value, this._fontScaleFactorOverrideElement.value); if (metrics && metrics.isValid() && metrics.width && metrics.height) { this._setDeviceMetricsOverride(metrics, false, false); WebInspector.userAgentSupport.toggleDeviceMetricsOverride(true); } if (!this._widthOverrideElement.value) this._widthOverrideElement.focus(); }, _applyDeviceMetricsUserInput: function() { this._setDeviceMetricsOverride(WebInspector.UserAgentSupport.DeviceMetrics.parseUserInput(this._widthOverrideElement.value.trim(), this._heightOverrideElement.value.trim(), this._fontScaleFactorOverrideElement.value.trim()), true, false); }, _setDeviceMetricsOverride: function(metrics, userInputModified, updateCheckbox) { function setValid(condition, element) { if (condition) element.removeStyleClass("error-input"); else element.addStyleClass("error-input"); } setValid(metrics && metrics.isWidthValid(), this._widthOverrideElement); setValid(metrics && metrics.isHeightValid(), this._heightOverrideElement); setValid(metrics && metrics.isFontScaleFactorValid(), this._fontScaleFactorOverrideElement); if (!metrics) return; if (!userInputModified) { this._widthOverrideElement.value = metrics.widthToInput(); this._heightOverrideElement.value = metrics.heightToInput(); this._fontScaleFactorOverrideElement.value = metrics.fontScaleFactorToInput(); } if (metrics.isValid()) { var value = metrics.toSetting(); if (value !== WebInspector.settings.deviceMetrics.get()) WebInspector.settings.deviceMetrics.set(value); } if (this._metricsCheckboxElement && updateCheckbox) { this._metricsCheckboxElement.checked = !!metrics.toSetting(); this._onMetricsCheckboxClicked(); } }, _createDeviceMetricsElement: function(metrics) { var fieldsetElement = document.createElement("fieldset"); fieldsetElement.id = "metrics-override-section"; this._deviceMetricsFieldsetElement = fieldsetElement; function swapDimensionsClicked(event) { var widthValue = this._widthOverrideElement.value; this._widthOverrideElement.value = this._heightOverrideElement.value; this._heightOverrideElement.value = widthValue; this._applyDeviceMetricsUserInput(); } var tableElement = fieldsetElement.createChild("table", "nowrap"); var rowElement = tableElement.createChild("tr"); var cellElement = rowElement.createChild("td"); cellElement.appendChild(document.createTextNode(WebInspector.UIString("Screen resolution:"))); cellElement = rowElement.createChild("td"); this._widthOverrideElement = this._createInput(cellElement, "metrics-override-width", String(metrics.width || screen.width), this._applyDeviceMetricsUserInput.bind(this), true); cellElement.appendChild(document.createTextNode(" \u00D7 ")); this._heightOverrideElement = this._createInput(cellElement, "metrics-override-height", String(metrics.height || screen.height), this._applyDeviceMetricsUserInput.bind(this), true); cellElement.appendChild(document.createTextNode(" \u2014 ")); this._swapDimensionsElement = cellElement.createChild("button"); this._swapDimensionsElement.appendChild(document.createTextNode(" \u21C4 ")); this._swapDimensionsElement.title = WebInspector.UIString("Swap dimensions"); this._swapDimensionsElement.addEventListener("click", swapDimensionsClicked.bind(this), false); rowElement = tableElement.createChild("tr"); cellElement = rowElement.createChild("td"); cellElement.appendChild(document.createTextNode(WebInspector.UIString("Font scale factor:"))); cellElement = rowElement.createChild("td"); this._fontScaleFactorOverrideElement = this._createInput(cellElement, "metrics-override-font-scale", String(metrics.fontScaleFactor || 1), this._applyDeviceMetricsUserInput.bind(this), true); rowElement = tableElement.createChild("tr"); cellElement = rowElement.createChild("td"); cellElement.colSpan = 2; this._fitWindowCheckboxElement = document.createElement("input"); cellElement.appendChild(this._createCheckboxSetting(WebInspector.UIString("Fit in window"), WebInspector.settings.deviceFitWindow, true, this._fitWindowCheckboxElement)); return fieldsetElement; }, _createGeolocationOverrideControl: function() { const geolocationSetting = WebInspector.settings.geolocationOverride.get(); var geolocation = WebInspector.UserAgentSupport.GeolocationPosition.parseSetting(geolocationSetting); var p = document.createElement("p"); var labelElement = p.createChild("label"); var checkboxElement = labelElement.createChild("input"); checkboxElement.id = "geolocation-override-checkbox"; checkboxElement.type = "checkbox"; checkboxElement.checked = false; checkboxElement.addEventListener("click", this._onGeolocationOverrideCheckboxClicked.bind(this), false); this._geolocationOverrideCheckboxElement = checkboxElement; labelElement.appendChild(document.createTextNode(WebInspector.UIString("Override Geolocation"))); var geolocationSectionElement = this._createGeolocationOverrideElement(geolocation); p.appendChild(geolocationSectionElement); this._geolocationSectionElement = geolocationSectionElement; this._onGeolocationOverrideCheckboxClicked(); return p; }, _onGeolocationOverrideCheckboxClicked: function() { var controlsDisabled = !this._geolocationOverrideCheckboxElement.checked; this._geolocationFieldsetElement.disabled = controlsDisabled; if (controlsDisabled) { WebInspector.userAgentSupport.toggleGeolocationPositionOverride(false); return; } var geolocation = WebInspector.UserAgentSupport.GeolocationPosition.parseUserInput(this._latitudeElement.value, this._longitudeElement.value, this._geolocationErrorElement.checked); if (geolocation) { this._setGeolocationPosition(geolocation, false, false); WebInspector.userAgentSupport.toggleGeolocationPositionOverride(true); } if (!this._latitudeElement.value) this._latitudeElement.focus(); }, _applyGeolocationUserInput: function() { this._setGeolocationPosition(WebInspector.UserAgentSupport.GeolocationPosition.parseUserInput(this._latitudeElement.value.trim(), this._longitudeElement.value.trim(), this._geolocationErrorElement.checked), true, false); }, _setGeolocationPosition: function(geolocation, userInputModified, updateCheckbox) { if (!geolocation) return; if (!userInputModified) { this._latitudeElement.value = geolocation.latitude; this._longitudeElement.value = geolocation.longitude; } var value = geolocation.toSetting(); WebInspector.settings.geolocationOverride.set(value); if (this._geolocationOverrideCheckboxElement && updateCheckbox) { this._geolocationOverrideCheckboxElement.checked = !!geolocation.toSetting(); this._onGeolocationOverrideCheckboxClicked(); } }, _createGeolocationOverrideElement: function(geolocation) { var fieldsetElement = document.createElement("fieldset"); fieldsetElement.id = "geolocation-override-section"; this._geolocationFieldsetElement = fieldsetElement; var tableElement = fieldsetElement.createChild("table"); var rowElement = tableElement.createChild("tr"); var cellElement = rowElement.createChild("td"); cellElement.appendChild(document.createTextNode(WebInspector.UIString("Geolocation Position") + ":")); cellElement = rowElement.createChild("td"); cellElement.appendChild(document.createTextNode(WebInspector.UIString("Lat = "))); this._latitudeElement = this._createInput(cellElement, "geolocation-override-latitude", String(geolocation.latitude), this._applyGeolocationUserInput.bind(this), true); cellElement.appendChild(document.createTextNode(" , ")); cellElement.appendChild(document.createTextNode(WebInspector.UIString("Lon = "))); this._longitudeElement = this._createInput(cellElement, "geolocation-override-longitude", String(geolocation.longitude), this._applyGeolocationUserInput.bind(this), true); rowElement = tableElement.createChild("tr"); cellElement = rowElement.createChild("td"); cellElement.colSpan = 2; var geolocationErrorLabelElement = document.createElement("label"); var geolocationErrorCheckboxElement = geolocationErrorLabelElement.createChild("input"); geolocationErrorCheckboxElement.id = "geolocation-error"; geolocationErrorCheckboxElement.type = "checkbox"; geolocationErrorCheckboxElement.checked = !geolocation || geolocation.error; geolocationErrorCheckboxElement.addEventListener("click", this._applyGeolocationUserInput.bind(this), false); geolocationErrorLabelElement.appendChild(document.createTextNode(WebInspector.UIString("Emulate position unavailable"))); this._geolocationErrorElement = geolocationErrorCheckboxElement; cellElement.appendChild(geolocationErrorLabelElement); return fieldsetElement; }, _createDeviceOrientationOverrideControl: function() { const deviceOrientationSetting = WebInspector.settings.deviceOrientationOverride.get(); var deviceOrientation = WebInspector.UserAgentSupport.DeviceOrientation.parseSetting(deviceOrientationSetting); var p = document.createElement("p"); var labelElement = p.createChild("label"); var checkboxElement = labelElement.createChild("input"); checkboxElement.id = "device-orientation-override-checkbox"; checkboxElement.type = "checkbox"; checkboxElement.checked = false; checkboxElement.addEventListener("click", this._onDeviceOrientationOverrideCheckboxClicked.bind(this), false); this._deviceOrientationOverrideCheckboxElement = checkboxElement; labelElement.appendChild(document.createTextNode(WebInspector.UIString("Override Device Orientation"))); var deviceOrientationSectionElement = this._createDeviceOrientationOverrideElement(deviceOrientation); p.appendChild(deviceOrientationSectionElement); this._deviceOrientationSectionElement = deviceOrientationSectionElement; this._onDeviceOrientationOverrideCheckboxClicked(); return p; }, _onDeviceOrientationOverrideCheckboxClicked: function() { var controlsDisabled = !this._deviceOrientationOverrideCheckboxElement.checked; this._deviceOrientationFieldsetElement.disabled = controlsDisabled; if (controlsDisabled) { WebInspector.userAgentSupport.toggleDeviceOrientationOverride(false); return; } var deviceOrientation = WebInspector.UserAgentSupport.DeviceOrientation.parseUserInput(this._alphaElement.value, this._betaElement.value, this._gammaElement.value); if (deviceOrientation) { this._setDeviceOrientation(deviceOrientation, false, false); WebInspector.userAgentSupport.toggleDeviceOrientationOverride(true); } if (!this._alphaElement.value) this._alphaElement.focus(); }, _applyDeviceOrientationUserInput: function() { this._setDeviceOrientation(WebInspector.UserAgentSupport.DeviceOrientation.parseUserInput(this._alphaElement.value.trim(), this._betaElement.value.trim(), this._gammaElement.value.trim()), true, false); }, _setDeviceOrientation: function(deviceOrientation, userInputModified, updateCheckbox) { if (!deviceOrientation) return; if (!userInputModified) { this._alphaElement.value = deviceOrientation.alpha; this._betaElement.value = deviceOrientation.beta; this._gammaElement.value = deviceOrientation.gamma; } var value = deviceOrientation.toSetting(); WebInspector.settings.deviceOrientationOverride.set(value); if (this._deviceOrientationOverrideCheckboxElement && updateCheckbox) { this._deviceOrientationOverrideCheckboxElement.checked = !!deviceOrientation.toSetting(); this._onDeviceOrientationOverrideCheckboxClicked(); } }, _createDeviceOrientationOverrideElement: function(deviceOrientation) { var fieldsetElement = document.createElement("fieldset"); fieldsetElement.id = "device-orientation-override-section"; this._deviceOrientationFieldsetElement = fieldsetElement; var tableElement = fieldsetElement.createChild("table"); var rowElement = tableElement.createChild("tr"); var cellElement = rowElement.createChild("td"); cellElement.appendChild(document.createTextNode("\u03B1: ")); this._alphaElement = this._createInput(cellElement, "device-orientation-override-alpha", String(deviceOrientation.alpha), this._applyDeviceOrientationUserInput.bind(this), true); cellElement.appendChild(document.createTextNode(" \u03B2: ")); this._betaElement = this._createInput(cellElement, "device-orientation-override-beta", String(deviceOrientation.beta), this._applyDeviceOrientationUserInput.bind(this), true); cellElement.appendChild(document.createTextNode(" \u03B3: ")); this._gammaElement = this._createInput(cellElement, "device-orientation-override-gamma", String(deviceOrientation.gamma), this._applyDeviceOrientationUserInput.bind(this), true); return fieldsetElement; }, _createMediaEmulationElement: function() { const p = document.createElement("p"); const labelElement = p.createChild("label"); const checkboxElement = labelElement.createChild("input"); checkboxElement.type = "checkbox"; checkboxElement.checked = false; labelElement.appendChild(document.createTextNode(WebInspector.UIString("Emulate CSS media"))); var mediaSelectElement = p.createChild("select"); var mediaTypes = WebInspector.CSSStyleModel.MediaTypes; var defaultMedia = WebInspector.settings.emulatedCSSMedia.get(); for (var i = 0; i < mediaTypes.length; ++i) { var mediaType = mediaTypes[i]; if (mediaType === "all") { continue; } var option = document.createElement("option"); option.text = mediaType; option.value = mediaType; mediaSelectElement.add(option); if (mediaType === defaultMedia) mediaSelectElement.selectedIndex = mediaSelectElement.options.length - 1; } mediaSelectElement.disabled = true; var boundListener = this._emulateMediaChanged.bind(this, checkboxElement, mediaSelectElement); checkboxElement.addEventListener("click", boundListener, false); mediaSelectElement.addEventListener("change", boundListener, false); return p; }, _emulateMediaChanged: function(checkbox, select) { select.disabled = !checkbox.checked; if (checkbox.checked) { var media = select.options[select.selectedIndex].value; WebInspector.settings.emulatedCSSMedia.set(media); PageAgent.setEmulatedMedia(media); } else PageAgent.setEmulatedMedia(""); WebInspector.cssModel.mediaQueryResultChanged(); }, __proto__: WebInspector.View.prototype } WebInspector.HAREntry = function(request) { this._request = request; } WebInspector.HAREntry.prototype = { build: function() { var entry = { startedDateTime: new Date(this._request.startTime * 1000), time: WebInspector.HAREntry._toMilliseconds(this._request.duration), request: this._buildRequest(), response: this._buildResponse(), cache: { }, timings: this._buildTimings() }; var page = WebInspector.networkLog.pageLoadForRequest(this._request); if (page) entry.pageref = "page_" + page.id; return entry; }, _buildRequest: function() { var res = { method: this._request.requestMethod, url: this._buildRequestURL(this._request.url), httpVersion: this._request.requestHttpVersion, headers: this._request.requestHeaders, queryString: this._buildParameters(this._request.queryParameters || []), cookies: this._buildCookies(this._request.requestCookies || []), headersSize: this._request.requestHeadersSize, bodySize: this.requestBodySize }; if (this._request.requestFormData) res.postData = this._buildPostData(); return res; }, _buildResponse: function() { return { status: this._request.statusCode, statusText: this._request.statusText, httpVersion: this._request.responseHttpVersion, headers: this._request.responseHeaders, cookies: this._buildCookies(this._request.responseCookies || []), content: this._buildContent(), redirectURL: this._request.responseHeaderValue("Location") || "", headersSize: this._request.responseHeadersSize, bodySize: this.responseBodySize }; }, _buildContent: function() { var content = { size: this._request.resourceSize, mimeType: this._request.mimeType, }; var compression = this.responseCompression; if (typeof compression === "number") content.compression = compression; return content; }, _buildTimings: function() { var waitForConnection = this._interval("connectStart", "connectEnd"); var blocked; var connect; var dns = this._interval("dnsStart", "dnsEnd"); var send = this._interval("sendStart", "sendEnd"); var ssl = this._interval("sslStart", "sslEnd"); if (ssl !== -1 && send !== -1) send -= ssl; if (this._request.connectionReused) { connect = -1; blocked = waitForConnection; } else { blocked = 0; connect = waitForConnection; if (dns !== -1) connect -= dns; } return { blocked: blocked, dns: dns, connect: connect, send: send, wait: this._interval("sendEnd", "receiveHeadersEnd"), receive: WebInspector.HAREntry._toMilliseconds(this._request.receiveDuration), ssl: ssl }; }, _buildPostData: function() { var res = { mimeType: this._request.requestHeaderValue("Content-Type"), text: this._request.requestFormData }; if (this._request.formParameters) res.params = this._buildParameters(this._request.formParameters); return res; }, _buildParameters: function(parameters) { return parameters.slice(); }, _buildRequestURL: function(url) { return url.split("#", 2)[0]; }, _buildCookies: function(cookies) { return cookies.map(this._buildCookie.bind(this)); }, _buildCookie: function(cookie) { return { name: cookie.name(), value: cookie.value(), path: cookie.path(), domain: cookie.domain(), expires: cookie.expiresDate(new Date(this._request.startTime * 1000)), httpOnly: cookie.httpOnly(), secure: cookie.secure() }; }, _interval: function(start, end) { var timing = this._request.timing; if (!timing) return -1; var startTime = timing[start]; return typeof startTime !== "number" || startTime === -1 ? -1 : Math.round(timing[end] - startTime); }, get requestBodySize() { return !this._request.requestFormData ? 0 : this._request.requestFormData.length; }, get responseBodySize() { if (this._request.cached || this._request.statusCode === 304) return 0; return this._request.transferSize - this._request.responseHeadersSize }, get responseCompression() { if (this._request.cached || this._request.statusCode === 304) return; return this._request.resourceSize - (this._request.transferSize - this._request.responseHeadersSize); } } WebInspector.HAREntry._toMilliseconds = function(time) { return time === -1 ? -1 : Math.round(time * 1000); } WebInspector.HARLog = function(requests) { this._requests = requests; } WebInspector.HARLog.prototype = { build: function() { return { version: "1.2", creator: this._creator(), pages: this._buildPages(), entries: this._requests.map(this._convertResource.bind(this)) } }, _creator: function() { var webKitVersion = /AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent); return { name: "WebInspector", version: webKitVersion ? webKitVersion[1] : "n/a" }; }, _buildPages: function() { var seenIdentifiers = {}; var pages = []; for (var i = 0; i < this._requests.length; ++i) { var page = WebInspector.networkLog.pageLoadForRequest(this._requests[i]); if (!page || seenIdentifiers[page.id]) continue; seenIdentifiers[page.id] = true; pages.push(this._convertPage(page)); } return pages; }, _convertPage: function(page) { return { startedDateTime: new Date(page.startTime * 1000), id: "page_" + page.id, title: page.url, pageTimings: { onContentLoad: this._pageEventTime(page, page.contentLoadTime), onLoad: this._pageEventTime(page, page.loadTime) } } }, _convertResource: function(request) { return (new WebInspector.HAREntry(request)).build(); }, _pageEventTime: function(page, time) { var startTime = page.startTime; if (time === -1 || startTime === -1) return -1; return WebInspector.HAREntry._toMilliseconds(time - startTime); } } WebInspector.HARWriter = function() { } WebInspector.HARWriter.prototype = { write: function(stream, requests, progress) { this._stream = stream; this._harLog = (new WebInspector.HARLog(requests)).build(); this._pendingRequests = 1; var entries = this._harLog.entries; for (var i = 0; i < entries.length; ++i) { var content = requests[i].content; if (typeof content === "undefined" && requests[i].finished) { ++this._pendingRequests; requests[i].requestContent(this._onContentAvailable.bind(this, entries[i])); } else if (content !== null) entries[i].response.content.text = content; } var compositeProgress = new WebInspector.CompositeProgress(progress); this._writeProgress = compositeProgress.createSubProgress(); if (--this._pendingRequests) { this._requestsProgress = compositeProgress.createSubProgress(); this._requestsProgress.setTitle(WebInspector.UIString("Collecting content…")); this._requestsProgress.setTotalWork(this._pendingRequests); } else this._beginWrite(); }, _onContentAvailable: function(entry, content, contentEncoded, mimeType) { if (content !== null) entry.response.content.text = content; if (this._requestsProgress) this._requestsProgress.worked(); if (!--this._pendingRequests) { this._requestsProgress.done(); this._beginWrite(); } }, _beginWrite: function() { const jsonIndent = 2; this._text = JSON.stringify({log: this._harLog}, null, jsonIndent); this._writeProgress.setTitle(WebInspector.UIString("Writing file…")); this._writeProgress.setTotalWork(this._text.length); this._bytesWritten = 0; this._writeNextChunk(this._stream); }, _writeNextChunk: function(stream, error) { if (this._bytesWritten >= this._text.length || error) { stream.close(); this._writeProgress.done(); return; } const chunkSize = 100000; var text = this._text.substring(this._bytesWritten, this._bytesWritten + chunkSize); this._bytesWritten += text.length; stream.write(text, this._writeNextChunk.bind(this)); this._writeProgress.setWorked(this._bytesWritten); } } WebInspector.CookieParser = function() { } WebInspector.CookieParser.KeyValue = function(key, value, position) { this.key = key; this.value = value; this.position = position; } WebInspector.CookieParser.prototype = { cookies: function() { return this._cookies; }, parseCookie: function(cookieHeader) { if (!this._initialize(cookieHeader)) return null; for (var kv = this._extractKeyValue(); kv; kv = this._extractKeyValue()) { if (kv.key.charAt(0) === "$" && this._lastCookie) this._lastCookie.addAttribute(kv.key.slice(1), kv.value); else if (kv.key.toLowerCase() !== "$version" && typeof kv.value === "string") this._addCookie(kv, WebInspector.Cookie.Type.Request); this._advanceAndCheckCookieDelimiter(); } this._flushCookie(); return this._cookies; }, parseSetCookie: function(setCookieHeader) { if (!this._initialize(setCookieHeader)) return null; for (var kv = this._extractKeyValue(); kv; kv = this._extractKeyValue()) { if (this._lastCookie) this._lastCookie.addAttribute(kv.key, kv.value); else this._addCookie(kv, WebInspector.Cookie.Type.Response); if (this._advanceAndCheckCookieDelimiter()) this._flushCookie(); } this._flushCookie(); return this._cookies; }, _initialize: function(headerValue) { this._input = headerValue; if (typeof headerValue !== "string") return false; this._cookies = []; this._lastCookie = null; this._originalInputLength = this._input.length; return true; }, _flushCookie: function() { if (this._lastCookie) this._lastCookie.setSize(this._originalInputLength - this._input.length - this._lastCookiePosition); this._lastCookie = null; }, _extractKeyValue: function() { if (!this._input || !this._input.length) return null; var keyValueMatch = /^[ \t]*([^\s=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this._input); if (!keyValueMatch) { console.log("Failed parsing cookie header before: " + this._input); return null; } var result = new WebInspector.CookieParser.KeyValue(keyValueMatch[1], keyValueMatch[2] && keyValueMatch[2].trim(), this._originalInputLength - this._input.length); this._input = this._input.slice(keyValueMatch[0].length); return result; }, /** * @return {boolean} */ _advanceAndCheckCookieDelimiter: function() { var match = /^\s*[\n;]\s*/.exec(this._input); if (!match) return false; this._input = this._input.slice(match[0].length); return match[0].match("\n") !== null; }, _addCookie: function(keyValue, type) { if (this._lastCookie) this._lastCookie.setSize(keyValue.position - this._lastCookiePosition); this._lastCookie = keyValue.value ? new WebInspector.Cookie(keyValue.key, keyValue.value, type) : new WebInspector.Cookie("", keyValue.key, type); this._lastCookiePosition = keyValue.position; this._cookies.push(this._lastCookie); } }; WebInspector.CookieParser.parseCookie = function(header) { return (new WebInspector.CookieParser()).parseCookie(header); } WebInspector.CookieParser.parseSetCookie = function(header) { return (new WebInspector.CookieParser()).parseSetCookie(header); } WebInspector.Cookie = function(name, value, type) { this._name = name; this._value = value; this._type = type; this._attributes = {}; } WebInspector.Cookie.prototype = { name: function() { return this._name; }, value: function() { return this._value; }, type: function() { return this._type; }, httpOnly: function() { return "httponly" in this._attributes; }, secure: function() { return "secure" in this._attributes; }, session: function() { return !("expires" in this._attributes || "max-age" in this._attributes); }, path: function() { return this._attributes["path"]; }, port: function() { return this._attributes["port"]; }, domain: function() { return this._attributes["domain"]; }, expires: function() { return this._attributes["expires"]; }, maxAge: function() { return this._attributes["max-age"]; }, size: function() { return this._size; }, setSize: function(size) { this._size = size; }, expiresDate: function(requestDate) { if (this.maxAge()) { var targetDate = requestDate === null ? new Date() : requestDate; return new Date(targetDate.getTime() + 1000 * this.maxAge()); } if (this.expires()) return new Date(this.expires()); return null; }, attributes: function() { return this._attributes; }, addAttribute: function(key, value) { this._attributes[key.toLowerCase()] = value; } } WebInspector.Cookie.Type = { Request: 0, Response: 1 }; WebInspector.Cookies = {} WebInspector.Cookies.getCookiesAsync = function(callback) { function mycallback(error, cookies, cookiesString) { if (error) return; if (cookiesString) callback(WebInspector.Cookies.buildCookiesFromString(cookiesString), false); else callback(cookies.map(WebInspector.Cookies.buildCookieProtocolObject), true); } PageAgent.getCookies(mycallback); } WebInspector.Cookies.buildCookiesFromString = function(rawCookieString) { var rawCookies = rawCookieString.split(/;\s*/); var cookies = []; if (!(/^\s*$/.test(rawCookieString))) { for (var i = 0; i < rawCookies.length; ++i) { var rawCookie = rawCookies[i]; var delimIndex = rawCookie.indexOf("="); var name = rawCookie.substring(0, delimIndex); var value = rawCookie.substring(delimIndex + 1); var size = name.length + value.length; var cookie = new WebInspector.Cookie(name, value, null); cookie.setSize(size); cookies.push(cookie); } } return cookies; } WebInspector.Cookies.buildCookieProtocolObject = function(protocolCookie) { var cookie = new WebInspector.Cookie(protocolCookie.name, protocolCookie.value, null); cookie.addAttribute("domain", protocolCookie["domain"]); cookie.addAttribute("path", protocolCookie["path"]); cookie.addAttribute("port", protocolCookie["port"]); if (protocolCookie["expires"]) cookie.addAttribute("expires", protocolCookie["expires"]); if (protocolCookie["httpOnly"]) cookie.addAttribute("httpOnly"); if (protocolCookie["secure"]) cookie.addAttribute("secure"); cookie.setSize(protocolCookie["size"]); return cookie; } WebInspector.Cookies.cookieMatchesResourceURL = function(cookie, resourceURL) { var url = resourceURL.asParsedURL(); if (!url || !WebInspector.Cookies.cookieDomainMatchesResourceDomain(cookie.domain(), url.host)) return false; return (url.path.startsWith(cookie.path()) && (!cookie.port() || url.port == cookie.port()) && (!cookie.secure() || url.scheme === "https")); } WebInspector.Cookies.cookieDomainMatchesResourceDomain = function(cookieDomain, resourceDomain) { if (cookieDomain.charAt(0) !== '.') return resourceDomain === cookieDomain; return !!resourceDomain.match(new RegExp("^([^\\.]+\\.)*" + cookieDomain.substring(1).escapeForRegExp() + "$", "i")); } WebInspector.Toolbar = function() { this.element = document.getElementById("toolbar"); WebInspector.installDragHandle(this.element, this._toolbarDragStart.bind(this), this._toolbarDrag.bind(this), this._toolbarDragEnd.bind(this), "default"); this._dropdownButton = document.getElementById("toolbar-dropdown-arrow"); this._dropdownButton.addEventListener("click", this._toggleDropdown.bind(this), false); document.getElementById("close-button-left").addEventListener("click", this._onClose, true); document.getElementById("close-button-right").addEventListener("click", this._onClose, true); } WebInspector.Toolbar.prototype = { resize: function() { this._updateDropdownButtonAndHideDropdown(); }, addPanel: function(panelDescriptor) { this.element.appendChild(this._createPanelToolbarItem(panelDescriptor)); this.resize(); }, _createPanelToolbarItem: function(panelDescriptor) { var toolbarItem = document.createElement("button"); toolbarItem.className = "toolbar-item toggleable"; toolbarItem.panelDescriptor = panelDescriptor; toolbarItem.addStyleClass(panelDescriptor.name()); function onToolbarItemClicked() { this._updateDropdownButtonAndHideDropdown(); WebInspector.inspectorView.setCurrentPanel(panelDescriptor.panel()); } toolbarItem.addEventListener("click", onToolbarItemClicked.bind(this), false); function panelSelected() { if (WebInspector.inspectorView.currentPanel() && panelDescriptor.name() === WebInspector.inspectorView.currentPanel().name) toolbarItem.addStyleClass("toggled-on"); else toolbarItem.removeStyleClass("toggled-on"); } WebInspector.inspectorView.addEventListener(WebInspector.InspectorView.Events.PanelSelected, panelSelected); var iconElement = toolbarItem.createChild("div", "toolbar-icon"); toolbarItem.createChild("div", "toolbar-label").textContent = panelDescriptor.title(); if (panelDescriptor.iconURL()) { iconElement.addStyleClass("custom-toolbar-icon"); iconElement.style.backgroundImage = "url(" + panelDescriptor.iconURL() + ")"; } panelSelected(); return toolbarItem; }, setDockedToBottom: function(dockedToBottom) { this._isDockedToBottom = dockedToBottom; }, _toolbarDragStart: function(event) { if ((!this._isDockedToBottom && WebInspector.platformFlavor() !== WebInspector.PlatformFlavor.MacLeopard && WebInspector.platformFlavor() !== WebInspector.PlatformFlavor.MacSnowLeopard) || WebInspector.port() == "qt") return false; var target = event.target; if (target.hasStyleClass("toolbar-item") && target.hasStyleClass("toggleable")) return false; if (target !== this.element && !target.hasStyleClass("toolbar-item")) return false; this.element.lastScreenX = event.screenX; this.element.lastScreenY = event.screenY; return true; }, _toolbarDragEnd: function(event) { delete this.element.lastScreenX; delete this.element.lastScreenY; }, _toolbarDrag: function(event) { if (this._isDockedToBottom) { var height = window.innerHeight - (event.screenY - this.element.lastScreenY); InspectorFrontendHost.setAttachedWindowHeight(height); } else { var x = event.screenX - this.element.lastScreenX; var y = event.screenY - this.element.lastScreenY; InspectorFrontendHost.moveWindowBy(x, y); } this.element.lastScreenX = event.screenX; this.element.lastScreenY = event.screenY; event.preventDefault(); }, _onClose: function() { WebInspector.close(); }, _setDropdownVisible: function(visible) { if (!this._dropdown) { if (!visible) return; this._dropdown = new WebInspector.ToolbarDropdown(this); } if (visible) this._dropdown.show(); else this._dropdown.hide(); }, _toggleDropdown: function() { this._setDropdownVisible(!this._dropdown || !this._dropdown.visible); }, _updateDropdownButtonAndHideDropdown: function() { WebInspector.invokeOnceAfterBatchUpdate(this, this._innerUpdateDropdownButtonAndHideDropdown); }, _innerUpdateDropdownButtonAndHideDropdown: function() { this._setDropdownVisible(false); if (this.element.scrollHeight > this.element.offsetHeight) this._dropdownButton.removeStyleClass("hidden"); else this._dropdownButton.addStyleClass("hidden"); } } WebInspector.ToolbarDropdown = function(toolbar) { this._toolbar = toolbar; this._arrow = document.getElementById("toolbar-dropdown-arrow"); this.element = document.createElement("div"); this.element.id = "toolbar-dropdown"; this.element.className = "toolbar-small"; this._contentElement = this.element.createChild("div", "scrollable-content"); this._contentElement.tabIndex = 0; this._contentElement.addEventListener("keydown", this._onKeyDown.bind(this), true); } WebInspector.ToolbarDropdown.prototype = { show: function() { if (this.visible) return; var style = this.element.style; this._populate(); var top = this._arrow.totalOffsetTop() + this._arrow.clientHeight; this._arrow.addStyleClass("dropdown-visible"); this.element.style.top = top + "px"; this.element.style.right = window.innerWidth - this._arrow.totalOffsetLeft() - this._arrow.clientWidth + "px"; this._contentElement.style.maxHeight = window.innerHeight - top - 20 + "px"; this._toolbar.element.appendChild(this.element); }, hide: function() { if (!this.visible) return; this._arrow.removeStyleClass("dropdown-visible"); this.element.parentNode.removeChild(this.element); this._contentElement.removeChildren(); }, get visible() { return !!this.element.parentNode; }, _populate: function() { var toolbarItems = this._toolbar.element.querySelectorAll(".toolbar-item.toggleable"); for (var i = 0; i < toolbarItems.length; ++i) { if (toolbarItems[i].offsetTop > 1) this._contentElement.appendChild(this._toolbar._createPanelToolbarItem(toolbarItems[i].panelDescriptor)); } }, _onKeyDown: function(event) { if (event.keyCode !== WebInspector.KeyboardShortcut.Keys.Esc.code) return; event.consume(); this.hide(); } } WebInspector.toolbar = null; WebInspector.SearchController = function() { this._element = document.createElement("table"); this._element.className = "toolbar-search"; this._element.cellSpacing = 0; this._firstRowElement = this._element.createChild("tr"); this._secondRowElement = this._element.createChild("tr", "hidden"); var searchControlElementColumn = this._firstRowElement.createChild("td"); this._searchControlElement = searchControlElementColumn.createChild("span", "toolbar-search-control"); this._searchInputElement = this._searchControlElement.createChild("input", "search-replace"); this._searchInputElement.id = "search-input-field"; this._searchInputElement.placeholder = WebInspector.UIString("Find"); this._filterControlElement = searchControlElementColumn.createChild("span", "toolbar-search-control"); this._filterControlElement.addStyleClass("hidden"); this._filterInputElement = this._filterControlElement.createChild("input", "filter"); this._filterInputElement.id = "filter-input-field"; this._filterInputElement.placeholder = WebInspector.UIString("Filter"); this._matchesElement = this._searchControlElement.createChild("label", "search-results-matches"); this._matchesElement.setAttribute("for", "search-input-field"); var searchNavigationElement = this._searchControlElement.createChild("div", "toolbar-search-navigation-controls"); this._searchNavigationPrevElement = searchNavigationElement.createChild("div", "toolbar-search-navigation toolbar-search-navigation-prev"); this._searchNavigationPrevElement.addEventListener("click", this._onPrevButtonSearch.bind(this), false); this._searchNavigationPrevElement.title = WebInspector.UIString("Search Previous"); this._searchNavigationNextElement = searchNavigationElement.createChild("div", "toolbar-search-navigation toolbar-search-navigation-next"); this._searchNavigationNextElement.addEventListener("click", this._onNextButtonSearch.bind(this), false); this._searchNavigationNextElement.title = WebInspector.UIString("Search Next"); this._searchInputElement.addEventListener("mousedown", this._onSearchFieldManualFocus.bind(this), false); this._searchInputElement.addEventListener("keydown", this._onKeyDown.bind(this), true); this._filterInputElement.addEventListener("keydown", this._onKeyDown.bind(this), true); this._filterInputElement.addEventListener("input", this._onFilterInput.bind(this), false); this._searchInputElement.addEventListener("input", this._onSearchInput.bind(this), false); this._replaceInputElement = this._secondRowElement.createChild("td").createChild("input", "search-replace toolbar-replace-control"); this._replaceInputElement.addEventListener("keydown", this._onKeyDown.bind(this), true); this._replaceInputElement.placeholder = WebInspector.UIString("Replace"); this._findButtonElement = this._firstRowElement.createChild("td").createChild("button", "hidden"); this._findButtonElement.textContent = WebInspector.UIString("Find"); this._findButtonElement.tabIndex = -1; this._findButtonElement.addEventListener("click", this._onNextButtonSearch.bind(this), false); this._replaceButtonElement = this._secondRowElement.createChild("td").createChild("button"); this._replaceButtonElement.textContent = WebInspector.UIString("Replace"); this._replaceButtonElement.disabled = true; this._replaceButtonElement.tabIndex = -1; this._replaceButtonElement.addEventListener("click", this._replace.bind(this), false); this._prevButtonElement = this._firstRowElement.createChild("td").createChild("button", "hidden"); this._prevButtonElement.textContent = WebInspector.UIString("Previous"); this._prevButtonElement.disabled = true; this._prevButtonElement.tabIndex = -1; this._prevButtonElement.addEventListener("click", this._onPrevButtonSearch.bind(this), false); this._replaceAllButtonElement = this._secondRowElement.createChild("td").createChild("button"); this._replaceAllButtonElement.textContent = WebInspector.UIString("Replace All"); this._replaceAllButtonElement.addEventListener("click", this._replaceAll.bind(this), false); this._replaceElement = this._firstRowElement.createChild("td").createChild("span"); this._replaceCheckboxElement = this._replaceElement.createChild("input"); this._replaceCheckboxElement.type = "checkbox"; this._replaceCheckboxElement.id = "search-replace-trigger"; this._replaceCheckboxElement.addEventListener("click", this._updateSecondRowVisibility.bind(this), false); this._replaceLabelElement = this._replaceElement.createChild("label"); this._replaceLabelElement.textContent = WebInspector.UIString("Replace"); this._replaceLabelElement.setAttribute("for", "search-replace-trigger"); this._filterCheckboxContainer = this._firstRowElement.createChild("td").createChild("span"); this._filterCheckboxElement = this._filterCheckboxContainer.createChild("input"); this._filterCheckboxElement.type = "checkbox"; this._filterCheckboxElement.id = "filter-trigger"; this._filterCheckboxElement.addEventListener("click", this._filterCheckboxClick.bind(this), false); this._filterLabelElement = this._filterCheckboxContainer.createChild("label"); this._filterLabelElement.textContent = WebInspector.UIString("Filter"); this._filterLabelElement.setAttribute("for", "filter-trigger"); var cancelButtonElement = this._firstRowElement.createChild("td").createChild("button"); cancelButtonElement.textContent = WebInspector.UIString("Cancel"); cancelButtonElement.tabIndex = -1; cancelButtonElement.addEventListener("click", this.cancelSearch.bind(this), false); } WebInspector.SearchController.prototype = { updateSearchMatchesCount: function(matches, panel) { if (!panel) panel = WebInspector.inspectorView.currentPanel(); panel.currentSearchMatches = matches; if (panel === WebInspector.inspectorView.currentPanel()) this._updateSearchMatchesCountAndCurrentMatchIndex(WebInspector.inspectorView.currentPanel().currentQuery ? matches : 0, -1); }, updateCurrentMatchIndex: function(currentMatchIndex, panel) { if (panel === WebInspector.inspectorView.currentPanel()) this._updateSearchMatchesCountAndCurrentMatchIndex(panel.currentSearchMatches, currentMatchIndex); }, cancelSearch: function() { if (!this._searchIsVisible) return; if (this._filterCheckboxElement.checked) { this._filterCheckboxElement.checked = false; this._switchFilterToSearch(); } delete this._searchIsVisible; WebInspector.inspectorView.setFooterElement(null); this.resetSearch(); }, resetSearch: function() { this._performSearch("", false, false); this._updateReplaceVisibility(); this._matchesElement.textContent = ""; }, disableSearchUntilExplicitAction: function() { this._performSearch("", false, false); }, handleShortcut: function(event) { var isMac = WebInspector.isMac(); switch (event.keyIdentifier) { case "U+0046": if (isMac) var isFindKey = event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey; else var isFindKey = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey; if (isFindKey) { this.showSearchField(); event.consume(true); return true; } break; case "F3": if (!isMac) { this.showSearchField(); event.consume(); } break; case "U+0047": var currentPanel = WebInspector.inspectorView.currentPanel(); if (isMac && event.metaKey && !event.ctrlKey && !event.altKey) { if (event.shiftKey) currentPanel.jumpToPreviousSearchResult(); else currentPanel.jumpToNextSearchResult(); event.consume(true); return true; } break; } return false; }, _updateSearchNavigationButtonState: function(enabled) { this._replaceButtonElement.disabled = !enabled; this._prevButtonElement.disabled = !enabled; var panel = WebInspector.inspectorView.currentPanel(); if (enabled) { this._searchNavigationPrevElement.addStyleClass("enabled"); this._searchNavigationNextElement.addStyleClass("enabled"); } else { this._searchNavigationPrevElement.removeStyleClass("enabled"); this._searchNavigationNextElement.removeStyleClass("enabled"); } }, _updateSearchMatchesCountAndCurrentMatchIndex: function(matches, currentMatchIndex) { if (matches === 0 || currentMatchIndex >= 0) this._matchesElement.textContent = WebInspector.UIString("%d of %d", currentMatchIndex + 1, matches); this._updateSearchNavigationButtonState(matches > 0); }, showSearchField: function() { WebInspector.inspectorView.setFooterElement(this._element); this._updateReplaceVisibility(); this._updateFilterVisibility(); var selection = window.getSelection(); if (selection.rangeCount) this._searchInputElement.value = selection.toString().replace(/\r?\n.*/, ""); this._searchInputElement.focus(); this._searchInputElement.select(); this._searchIsVisible = true; }, _switchFilterToSearch: function() { this._filterControlElement.addStyleClass("hidden"); this._searchControlElement.removeStyleClass("hidden"); this._searchInputElement.focus(); this._searchInputElement.select(); this._searchInputElement.value = this._filterInputElement.value; this.resetFilter(); }, _switchSearchToFilter: function() { this._filterControlElement.removeStyleClass("hidden"); this._searchControlElement.addStyleClass("hidden"); this._filterInputElement.focus(); this._filterInputElement.select(); this._filterInputElement.value = this._searchInputElement.value; this.resetSearch(); }, _updateFilterVisibility: function() { if (WebInspector.inspectorView.currentPanel().canFilter()) this._filterCheckboxContainer.removeStyleClass("hidden"); else this._filterCheckboxContainer.addStyleClass("hidden"); }, _updateReplaceVisibility: function() { var panel = WebInspector.inspectorView.currentPanel(); if (panel && panel.canSearchAndReplace()) this._replaceElement.removeStyleClass("hidden"); else { this._replaceElement.addStyleClass("hidden"); this._replaceCheckboxElement.checked = false; this._updateSecondRowVisibility(); } }, _onSearchFieldManualFocus: function(event) { WebInspector.setCurrentFocusElement(event.target); }, _onKeyDown: function(event) { if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) { event.consume(true); this.cancelSearch(); WebInspector.setCurrentFocusElement(WebInspector.previousFocusElement()); if (WebInspector.currentFocusElement() === event.target) WebInspector.currentFocusElement().select(); return false; } if (isEnterKey(event)) { if (event.target === this._searchInputElement) this._performSearch(event.target.value, true, event.shiftKey); else if (event.target === this._replaceInputElement) this._replace(); } }, _onNextButtonSearch: function(event) { this._performSearch(this._searchInputElement.value, true, false); this._searchInputElement.focus(); }, _onPrevButtonSearch: function(event) { if (!this._searchNavigationPrevElement.hasStyleClass("enabled")) return; this._performSearch(this._searchInputElement.value, true, true); this._searchInputElement.focus(); }, _performSearch: function(query, forceSearch, isBackwardSearch) { if (!query || !query.length) { delete this._currentQuery; for (var panelName in WebInspector.panels) { var panel = WebInspector.panels[panelName]; var hadCurrentQuery = !!panel.currentQuery; delete panel.currentQuery; if (hadCurrentQuery) panel.searchCanceled(); } this._updateSearchMatchesCountAndCurrentMatchIndex(0, -1); return; } var currentPanel = WebInspector.inspectorView.currentPanel(); if (query === currentPanel.currentQuery && currentPanel.currentQuery === this._currentQuery) { if (forceSearch) { if (!isBackwardSearch) currentPanel.jumpToNextSearchResult(); else if (isBackwardSearch) currentPanel.jumpToPreviousSearchResult(); } return; } if (!forceSearch && query.length < 3 && !this._currentQuery) return; this._currentQuery = query; currentPanel.currentQuery = query; currentPanel.performSearch(query); }, _updateSecondRowVisibility: function() { if (!this._searchIsVisible) return; if (this._replaceCheckboxElement.checked) { this._element.addStyleClass("toolbar-search-replace"); this._secondRowElement.removeStyleClass("hidden"); this._prevButtonElement.removeStyleClass("hidden"); this._findButtonElement.removeStyleClass("hidden"); this._replaceCheckboxElement.tabIndex = -1; this._replaceInputElement.focus(); } else { this._element.removeStyleClass("toolbar-search-replace"); this._secondRowElement.addStyleClass("hidden"); this._prevButtonElement.addStyleClass("hidden"); this._findButtonElement.addStyleClass("hidden"); this._replaceCheckboxElement.tabIndex = 0; this._searchInputElement.focus(); } WebInspector.inspectorView.setFooterElement(this._element); }, _replace: function() { var currentPanel = WebInspector.inspectorView.currentPanel(); currentPanel.replaceSelectionWith(this._replaceInputElement.value); var query = this._currentQuery; delete this._currentQuery; this._performSearch(query, true, false); }, _replaceAll: function() { var currentPanel = WebInspector.inspectorView.currentPanel(); currentPanel.replaceAllWith(this._searchInputElement.value, this._replaceInputElement.value); }, _filterCheckboxClick: function() { if (this._filterCheckboxElement.checked) { this._switchSearchToFilter(); this._performFilter(this._filterInputElement.value); } else { this._switchFilterToSearch(); this._performSearch(this._searchInputElement.value, false, false); } }, _performFilter: function(query) { WebInspector.inspectorView.currentPanel().performFilter(query); }, _onFilterInput: function(event) { this._performFilter(event.target.value); }, _onSearchInput: function(event) { this._performSearch(event.target.value, false, false); }, resetFilter: function() { this._performFilter(""); } } WebInspector.searchController = null; WebInspector.WorkerManager = function() { this._workerIdToWindow = {}; InspectorBackend.registerWorkerDispatcher(new WebInspector.WorkerDispatcher(this)); } WebInspector.WorkerManager.isWorkerFrontend = function() { return !!WebInspector.queryParamsObject["dedicatedWorkerId"] || !!WebInspector.queryParamsObject["isSharedWorker"]; } WebInspector.WorkerManager.isDedicatedWorkerFrontend = function() { return !!WebInspector.queryParamsObject["dedicatedWorkerId"]; } WebInspector.WorkerManager.loaded = function() { var workerId = WebInspector.queryParamsObject["dedicatedWorkerId"]; if (workerId) WebInspector.WorkerManager._initializeDedicatedWorkerFrontend(workerId); else WebInspector.workerManager = new WebInspector.WorkerManager(); } WebInspector.WorkerManager.loadCompleted = function() { if (WebInspector.queryParamsObject["workerPaused"]) { DebuggerAgent.pause(); RuntimeAgent.run(calculateTitle); } else if (WebInspector.WorkerManager.isWorkerFrontend()) calculateTitle(); function calculateTitle() { WebInspector.WorkerManager._calculateWorkerInspectorTitle(); } if (WebInspector.workerManager) WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, WebInspector.workerManager._mainFrameNavigated, WebInspector.workerManager); } WebInspector.WorkerManager._initializeDedicatedWorkerFrontend = function(workerId) { function receiveMessage(event) { var message = event.data; InspectorBackend.dispatch(message); } window.addEventListener("message", receiveMessage, true); InspectorBackend.sendMessageObjectToBackend = function(message) { window.opener.postMessage({workerId: workerId, command: "sendMessageToBackend", message: message}, "*"); } InspectorFrontendHost.loaded = function() { window.opener.postMessage({workerId: workerId, command: "loaded"}, "*"); } } WebInspector.WorkerManager._calculateWorkerInspectorTitle = function() { var expression = "location.href"; if (WebInspector.queryParamsObject["isSharedWorker"]) expression += " + (this.name ? ' (' + this.name + ')' : '')"; RuntimeAgent.evaluate.invoke({expression:expression, doNotPauseOnExceptionsAndMuteConsole:true, returnByValue: true}, evalCallback.bind(this)); function evalCallback(error, result, wasThrown) { if (error || wasThrown) { console.error(error); return; } InspectorFrontendHost.inspectedURLChanged(result.value); } } WebInspector.WorkerManager.Events = { WorkerAdded: "worker-added", WorkerRemoved: "worker-removed", WorkersCleared: "workers-cleared", } WebInspector.WorkerManager.prototype = { _workerCreated: function(workerId, url, inspectorConnected) { if (inspectorConnected) this._openInspectorWindow(workerId, true); this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerAdded, {workerId: workerId, url: url, inspectorConnected: inspectorConnected}); }, _workerTerminated: function(workerId) { this.closeWorkerInspector(workerId); this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerRemoved, workerId); }, _sendMessageToWorkerInspector: function(workerId, message) { var workerInspectorWindow = this._workerIdToWindow[workerId]; if (workerInspectorWindow) workerInspectorWindow.postMessage(message, "*"); }, openWorkerInspector: function(workerId) { var existingInspector = this._workerIdToWindow[workerId]; if (existingInspector) { existingInspector.focus(); return; } this._openInspectorWindow(workerId, false); WorkerAgent.connectToWorker(workerId); }, _openInspectorWindow: function(workerId, workerIsPaused) { var search = window.location.search; var hash = window.location.hash; var url = window.location.href; url = url.replace(hash, ""); url += (search ? "&dedicatedWorkerId=" : "?dedicatedWorkerId=") + workerId; if (workerIsPaused) url += "&workerPaused=true"; url = url.replace("docked=true&", ""); url += hash; var workerInspectorWindow = window.open(url, undefined, "location=0"); this._workerIdToWindow[workerId] = workerInspectorWindow; workerInspectorWindow.addEventListener("beforeunload", this._workerInspectorClosing.bind(this, workerId), true); window.addEventListener("beforeunload", this._pageInspectorClosing.bind(this), true); WebInspector.notifications.addEventListener(WebInspector.Events.InspectorClosing, this._pageInspectorClosing, this); }, closeWorkerInspector: function(workerId) { var workerInspectorWindow = this._workerIdToWindow[workerId]; if (workerInspectorWindow) workerInspectorWindow.close(); }, _mainFrameNavigated: function(event) { for (var workerId in this._workerIdToWindow) this.closeWorkerInspector(workerId); this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkersCleared); }, _pageInspectorClosing: function() { this._ignoreWorkerInspectorClosing = true; for (var workerId in this._workerIdToWindow) { this._workerIdToWindow[workerId].close(); WorkerAgent.disconnectFromWorker(parseInt(workerId, 10)); } }, _workerInspectorClosing: function(workerId, event) { if (event.target.location.href === "about:blank") return; if (this._ignoreWorkerInspectorClosing) return; delete this._workerIdToWindow[workerId]; WorkerAgent.disconnectFromWorker(workerId); }, _disconnectedFromWorker: function() { var screen = new WebInspector.WorkerTerminatedScreen(); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, screen.hide, screen); screen.showModal(); }, __proto__: WebInspector.Object.prototype } WebInspector.WorkerDispatcher = function(workerManager) { this._workerManager = workerManager; window.addEventListener("message", this._receiveMessage.bind(this), true); } WebInspector.WorkerDispatcher.prototype = { _receiveMessage: function(event) { var workerId = event.data["workerId"]; workerId = parseInt(workerId, 10); var command = event.data.command; var message = event.data.message; if (command == "sendMessageToBackend") WorkerAgent.sendMessageToWorker(workerId, message); }, workerCreated: function(workerId, url, inspectorConnected) { this._workerManager._workerCreated(workerId, url, inspectorConnected); }, workerTerminated: function(workerId) { this._workerManager._workerTerminated(workerId); }, dispatchMessageFromWorker: function(workerId, message) { this._workerManager._sendMessageToWorkerInspector(workerId, message); }, disconnectedFromWorker: function() { this._workerManager._disconnectedFromWorker(); } } WebInspector.WorkerTerminatedScreen = function() { WebInspector.HelpScreen.call(this, WebInspector.UIString("Inspected worker terminated")); var p = this.contentElement.createChild("p"); p.addStyleClass("help-section"); p.textContent = WebInspector.UIString("Inspected worker has terminated. Once it restarts we will attach to it automatically."); } WebInspector.WorkerTerminatedScreen.prototype = { willHide: function() { WebInspector.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this.hide, this); WebInspector.HelpScreen.prototype.willHide.call(this); }, __proto__: WebInspector.HelpScreen.prototype } WebInspector.UserMetrics = function() { for (var actionName in WebInspector.UserMetrics._ActionCodes) { var actionCode = WebInspector.UserMetrics._ActionCodes[actionName]; this[actionName] = new WebInspector.UserMetrics._Recorder(actionCode); } function settingChanged(trueCode, falseCode, event) { if (event.data) InspectorFrontendHost.recordSettingChanged(trueCode); else InspectorFrontendHost.recordSettingChanged(falseCode); } WebInspector.settings.domWordWrap.addChangeListener(settingChanged.bind(this, WebInspector.UserMetrics._SettingCodes.ElementsDOMWrapOn, WebInspector.UserMetrics._SettingCodes.ElementsDOMWrapOff)); WebInspector.settings.monitoringXHREnabled.addChangeListener(settingChanged.bind(this, WebInspector.UserMetrics._SettingCodes.ConsoleMonitorXHROn, WebInspector.UserMetrics._SettingCodes.ConsoleMonitorXHROff)); WebInspector.settings.preserveConsoleLog.addChangeListener(settingChanged.bind(this, WebInspector.UserMetrics._SettingCodes.ConsolePreserveLogOn, WebInspector.UserMetrics._SettingCodes.ConsolePreserveLogOff)); WebInspector.settings.resourcesLargeRows.addChangeListener(settingChanged.bind(this, WebInspector.UserMetrics._SettingCodes.NetworkShowLargeRowsOn, WebInspector.UserMetrics._SettingCodes.NetworkShowLargeRowsOff)); } WebInspector.UserMetrics._ActionCodes = { WindowDocked: 1, WindowUndocked: 2, ScriptsBreakpointSet: 3, TimelineStarted: 4, ProfilesCPUProfileTaken: 5, ProfilesHeapProfileTaken: 6, AuditsStarted: 7, ConsoleEvaluated: 8 } WebInspector.UserMetrics._SettingCodes = { ElementsDOMWrapOn: 1, ElementsDOMWrapOff: 2, ConsoleMonitorXHROn: 3, ConsoleMonitorXHROff: 4, ConsolePreserveLogOn: 5, ConsolePreserveLogOff: 6, NetworkShowLargeRowsOn: 7, NetworkShowLargeRowsOff: 8 } WebInspector.UserMetrics._PanelCodes = { elements: 1, resources: 2, network: 3, scripts: 4, timeline: 5, profiles: 6, audits: 7, console: 8 } WebInspector.UserMetrics.UserAction = "UserAction"; WebInspector.UserMetrics.UserActionNames = { ForcedElementState: "forcedElementState", FileSaved: "fileSaved", RevertRevision: "revertRevision", ApplyOriginalContent: "applyOriginalContent", TogglePrettyPrint: "togglePrettyPrint", SetBreakpoint: "setBreakpoint", OpenSourceLink: "openSourceLink", NetworkSort: "networkSort", NetworkRequestSelected: "networkRequestSelected", NetworkRequestTabSelected: "networkRequestTabSelected", HeapSnapshotFilterChanged: "heapSnapshotFilterChanged" }; WebInspector.UserMetrics.prototype = { panelShown: function(panelName) { InspectorFrontendHost.recordPanelShown(WebInspector.UserMetrics._PanelCodes[panelName] || 0); } } WebInspector.UserMetrics._Recorder = function(actionCode) { this._actionCode = actionCode; } WebInspector.UserMetrics._Recorder.prototype = { record: function() { InspectorFrontendHost.recordActionTaken(this._actionCode); } } WebInspector.userMetrics = new WebInspector.UserMetrics(); WebInspector.RuntimeModel = function(resourceTreeModel) { resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this); resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this); resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this); resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, this._didLoadCachedResources, this); this._frameIdToContextList = {}; } WebInspector.RuntimeModel.Events = { FrameExecutionContextListAdded: "FrameExecutionContextListAdded", FrameExecutionContextListRemoved: "FrameExecutionContextListRemoved", } WebInspector.RuntimeModel.prototype = { setCurrentExecutionContext: function(executionContext) { this._currentExecutionContext = executionContext; }, currentExecutionContext: function() { return this._currentExecutionContext; }, contextLists: function() { return Object.values(this._frameIdToContextList); }, contextByFrameAndSecurityOrigin: function(frame, securityOrigin) { var frameContext = this._frameIdToContextList[frame.id]; return frameContext && frameContext.contextBySecurityOrigin(securityOrigin); }, _frameAdded: function(event) { var frame = event.data; var context = new WebInspector.FrameExecutionContextList(frame); this._frameIdToContextList[frame.id] = context; this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.FrameExecutionContextListAdded, context); }, _frameNavigated: function(event) { var frame = event.data; var context = this._frameIdToContextList[frame.id]; if (context) context._frameNavigated(frame); }, _frameDetached: function(event) { var frame = event.data; var context = this._frameIdToContextList[frame.id]; if (!context) return; this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.FrameExecutionContextListRemoved, context); delete this._frameIdToContextList[frame.id]; }, _didLoadCachedResources: function() { InspectorBackend.registerRuntimeDispatcher(new WebInspector.RuntimeDispatcher(this)); RuntimeAgent.enable(); }, _executionContextCreated: function(context) { var contextList = this._frameIdToContextList[context.frameId]; if (!contextList) return; contextList._addExecutionContext(new WebInspector.ExecutionContext(context.id, context.name, context.isPageContext)); }, evaluate: function(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback) { if (WebInspector.debuggerModel.selectedCallFrame()) { WebInspector.debuggerModel.evaluateOnSelectedCallFrame(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback); return; } if (!expression) { expression = "this"; } function evalCallback(error, result, wasThrown) { if (error) { console.error(error); callback(null, false); return; } if (returnByValue) callback(null, !!wasThrown, wasThrown ? null : result); else callback(WebInspector.RemoteObject.fromPayload(result), !!wasThrown); } RuntimeAgent.evaluate(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, this._currentExecutionContext ? this._currentExecutionContext.id : undefined, returnByValue, generatePreview, evalCallback); }, completionsForTextPrompt: function(proxyElement, wordRange, force, completionsReadyCallback) { var expressionRange = wordRange.startContainer.rangeOfWord(wordRange.startOffset, " =:[({;,!+-*/&|^<>", proxyElement, "backward"); var expressionString = expressionRange.toString(); var prefix = wordRange.toString(); this._completionsForExpression(expressionString, prefix, force, completionsReadyCallback); }, _completionsForExpression: function(expressionString, prefix, force, completionsReadyCallback) { var lastIndex = expressionString.length - 1; var dotNotation = (expressionString[lastIndex] === "."); var bracketNotation = (expressionString[lastIndex] === "["); if (dotNotation || bracketNotation) expressionString = expressionString.substr(0, lastIndex); if (expressionString && parseInt(expressionString, 10) == expressionString) { completionsReadyCallback([]); return; } if (!prefix && !expressionString && !force) { completionsReadyCallback([]); return; } if (!expressionString && WebInspector.debuggerModel.selectedCallFrame()) WebInspector.debuggerModel.getSelectedCallFrameVariables(receivedPropertyNames.bind(this)); else this.evaluate(expressionString, "completion", true, true, false, false, evaluated.bind(this)); function evaluated(result, wasThrown) { if (!result || wasThrown) { completionsReadyCallback([]); return; } function getCompletions(primitiveType) { var object; if (primitiveType === "string") object = new String(""); else if (primitiveType === "number") object = new Number(0); else if (primitiveType === "boolean") object = new Boolean(false); else object = this; var resultSet = {}; for (var o = object; o; o = o.__proto__) { try { var names = Object.getOwnPropertyNames(o); for (var i = 0; i < names.length; ++i) resultSet[names[i]] = true; } catch (e) { } } return resultSet; } if (result.type === "object" || result.type === "function") result.callFunctionJSON(getCompletions, undefined, receivedPropertyNames.bind(this)); else if (result.type === "string" || result.type === "number" || result.type === "boolean") this.evaluate("(" + getCompletions + ")(\"" + result.type + "\")", "completion", false, true, true, false, receivedPropertyNamesFromEval.bind(this)); } function receivedPropertyNamesFromEval(notRelevant, wasThrown, result) { if (result && !wasThrown) receivedPropertyNames.call(this, result.value); else completionsReadyCallback([]); } function receivedPropertyNames(propertyNames) { RuntimeAgent.releaseObjectGroup("completion"); if (!propertyNames) { completionsReadyCallback([]); return; } var includeCommandLineAPI = (!dotNotation && !bracketNotation); if (includeCommandLineAPI) { const commandLineAPI = ["dir", "dirxml", "keys", "values", "profile", "profileEnd", "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear"]; for (var i = 0; i < commandLineAPI.length; ++i) propertyNames[commandLineAPI[i]] = true; } this._reportCompletions(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, Object.keys(propertyNames)); } }, _reportCompletions: function(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, properties) { if (bracketNotation) { if (prefix.length && prefix[0] === "'") var quoteUsed = "'"; else var quoteUsed = "\""; } var results = []; if (!expressionString) { const keywords = ["break", "case", "catch", "continue", "default", "delete", "do", "else", "finally", "for", "function", "if", "in", "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with"]; properties = properties.concat(keywords); } properties.sort(); for (var i = 0; i < properties.length; ++i) { var property = properties[i]; if (dotNotation && !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(property)) continue; if (bracketNotation) { if (!/^[0-9]+$/.test(property)) property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + quoteUsed; property += "]"; } if (property.length < prefix.length) continue; if (prefix.length && !property.startsWith(prefix)) continue; results.push(property); } completionsReadyCallback(results); }, __proto__: WebInspector.Object.prototype } WebInspector.runtimeModel = null; WebInspector.RuntimeDispatcher = function(runtimeModel) { this._runtimeModel = runtimeModel; } WebInspector.RuntimeDispatcher.prototype = { executionContextCreated: function(context) { this._runtimeModel._executionContextCreated(context); } } WebInspector.ExecutionContext = function(id, name, isPageContext) { this.id = id; this.name = (isPageContext && !name) ? "<page context>" : name; this.isMainWorldContext = isPageContext; } WebInspector.ExecutionContext.comparator = function(a, b) { if (a.isMainWorldContext) return -1; if (b.isMainWorldContext) return +1; return a.name.localeCompare(b.name); } WebInspector.FrameExecutionContextList = function(frame) { this._frame = frame; this._executionContexts = []; } WebInspector.FrameExecutionContextList.EventTypes = { ContextsUpdated: "ContextsUpdated", ContextAdded: "ContextAdded" } WebInspector.FrameExecutionContextList.prototype = { _frameNavigated: function(frame) { this._frame = frame; this._executionContexts = []; this.dispatchEventToListeners(WebInspector.FrameExecutionContextList.EventTypes.ContextsUpdated, this); }, _addExecutionContext: function(context) { var insertAt = insertionIndexForObjectInListSortedByFunction(context, this._executionContexts, WebInspector.ExecutionContext.comparator); this._executionContexts.splice(insertAt, 0, context); this.dispatchEventToListeners(WebInspector.FrameExecutionContextList.EventTypes.ContextAdded, this); }, executionContexts: function() { return this._executionContexts; }, contextBySecurityOrigin: function(securityOrigin) { for (var i = 0; i < this._executionContexts.length; ++i) { var context = this._executionContexts[i]; if (!context.isMainWorldContext && context.name === securityOrigin) return context; } }, get frameId() { return this._frame.id; }, get url() { return this._frame.url; }, get displayName() { if (!this._frame.parentFrame) return "<top frame>"; var name = this._frame.name || ""; var subtitle = new WebInspector.ParsedURL(this._frame.url).displayName; if (subtitle) { if (!name) return subtitle; return name + "( " + subtitle + " )"; } return "<iframe>"; }, __proto__: WebInspector.Object.prototype } WebInspector.HandlerRegistry = function(setting) { WebInspector.Object.call(this); this._handlers = {}; this._setting = setting; this._activeHandler = this._setting.get(); WebInspector.ContextMenu.registerProvider(this); } WebInspector.HandlerRegistry.prototype = { get handlerNames() { return Object.getOwnPropertyNames(this._handlers); }, get activeHandler() { return this._activeHandler; }, set activeHandler(value) { this._activeHandler = value; this._setting.set(value); }, dispatch: function(data) { return this.dispatchToHandler(this._activeHandler, data); }, dispatchToHandler: function(name, data) { var handler = this._handlers[name]; var result = handler && handler(data); return !!result; }, registerHandler: function(name, handler) { this._handlers[name] = handler; this.dispatchEventToListeners(WebInspector.HandlerRegistry.EventTypes.HandlersUpdated); }, unregisterHandler: function(name) { delete this._handlers[name]; this.dispatchEventToListeners(WebInspector.HandlerRegistry.EventTypes.HandlersUpdated); }, appendApplicableItems: function(event, contextMenu, target) { if (event.hasBeenHandledByHandlerRegistry) return; event.hasBeenHandledByHandlerRegistry = true; this._appendContentProviderItems(contextMenu, target); this._appendHrefItems(contextMenu, target); }, _appendContentProviderItems: function(contextMenu, target) { if (!(target instanceof WebInspector.UISourceCode || target instanceof WebInspector.Resource || target instanceof WebInspector.NetworkRequest)) return; var contentProvider = (target); if (!contentProvider.contentURL()) return; contextMenu.appendItem(WebInspector.openLinkExternallyLabel(), WebInspector.openResource.bind(WebInspector, contentProvider.contentURL(), false)); for (var i = 1; i < this.handlerNames.length; ++i) { var handler = this.handlerNames[i]; contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open using %s" : "Open Using %s", handler), this.dispatchToHandler.bind(this, handler, { url: contentProvider.contentURL() })); } contextMenu.appendItem(WebInspector.copyLinkAddressLabel(), InspectorFrontendHost.copyText.bind(InspectorFrontendHost, contentProvider.contentURL())); if (!InspectorFrontendHost.canSave() || !contentProvider.contentURL()) return; var contentType = contentProvider.contentType(); if (contentType !== WebInspector.resourceTypes.Document && contentType !== WebInspector.resourceTypes.Stylesheet && contentType !== WebInspector.resourceTypes.Script) return; function doSave(forceSaveAs, content) { var url = contentProvider.contentURL(); WebInspector.fileManager.save(url, content, forceSaveAs); WebInspector.fileManager.close(url); } function save(forceSaveAs) { if (contentProvider instanceof WebInspector.UISourceCode) { var uiSourceCode = (contentProvider); if (uiSourceCode.isDirty()) { doSave(forceSaveAs, uiSourceCode.workingCopy()); uiSourceCode.commitWorkingCopy(function() { }); return; } } contentProvider.requestContent(doSave.bind(this, forceSaveAs)); } contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString("Save"), save.bind(this, false)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Save as..." : "Save As..."), save.bind(this, true)); }, _appendHrefItems: function(contextMenu, target) { if (!(target instanceof Node)) return; var targetNode = (target); var anchorElement = targetNode.enclosingNodeOrSelfWithClass("webkit-html-resource-link") || targetNode.enclosingNodeOrSelfWithClass("webkit-html-external-link"); if (!anchorElement) return; var resourceURL = anchorElement.href; if (!resourceURL) return; contextMenu.appendItem(WebInspector.openLinkExternallyLabel(), WebInspector.openResource.bind(WebInspector, resourceURL, false)); if (WebInspector.resourceForURL(resourceURL)) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open link in Resources panel" : "Open Link in Resources Panel"), WebInspector.openResource.bind(null, resourceURL, true)); contextMenu.appendItem(WebInspector.copyLinkAddressLabel(), InspectorFrontendHost.copyText.bind(InspectorFrontendHost, resourceURL)); }, __proto__: WebInspector.Object.prototype } WebInspector.HandlerRegistry.EventTypes = { HandlersUpdated: "HandlersUpdated" } WebInspector.HandlerSelector = function(handlerRegistry) { this._handlerRegistry = handlerRegistry; this.element = document.createElement("select"); this.element.addEventListener("change", this._onChange.bind(this), false); this._update(); this._handlerRegistry.addEventListener(WebInspector.HandlerRegistry.EventTypes.HandlersUpdated, this._update.bind(this)); } WebInspector.HandlerSelector.prototype = { _update: function() { this.element.removeChildren(); var names = this._handlerRegistry.handlerNames; var activeHandler = this._handlerRegistry.activeHandler; for (var i = 0; i < names.length; ++i) { var option = document.createElement("option"); option.textContent = names[i]; option.selected = activeHandler === names[i]; this.element.appendChild(option); } this.element.disabled = names.length <= 1; }, _onChange: function(event) { var value = event.target.value; this._handlerRegistry.activeHandler = value; } } WebInspector.openAnchorLocationRegistry = null; WebInspector.SnippetStorage = function(settingPrefix, namePrefix) { this._snippets = {}; this._lastSnippetIdentifierSetting = WebInspector.settings.createSetting(settingPrefix + "Snippets_lastIdentifier", 0); this._snippetsSetting = WebInspector.settings.createSetting(settingPrefix + "Snippets", []); this._namePrefix = namePrefix; this._loadSettings(); } WebInspector.SnippetStorage.prototype = { get namePrefix() { return this._namePrefix; }, _saveSettings: function() { var savedSnippets = []; for (var id in this._snippets) savedSnippets.push(this._snippets[id].serializeToObject()); this._snippetsSetting.set(savedSnippets); }, snippets: function() { var result = []; for (var id in this._snippets) result.push(this._snippets[id]); return result; }, snippetForId: function(id) { return this._snippets[id]; }, _loadSettings: function() { var savedSnippets = this._snippetsSetting.get(); for (var i = 0; i < savedSnippets.length; ++i) this._snippetAdded(WebInspector.Snippet.fromObject(this, savedSnippets[i])); }, deleteSnippet: function(snippet) { delete this._snippets[snippet.id]; this._saveSettings(); }, createSnippet: function() { var nextId = this._lastSnippetIdentifierSetting.get() + 1; var snippetId = String(nextId); this._lastSnippetIdentifierSetting.set(nextId); var snippet = new WebInspector.Snippet(this, snippetId); this._snippetAdded(snippet); this._saveSettings(); return snippet; }, _snippetAdded: function(snippet) { this._snippets[snippet.id] = snippet; }, reset: function() { this._lastSnippetIdentifierSetting.set(0); this._snippetsSetting.set([]); this._snippets = {}; }, __proto__: WebInspector.Object.prototype } WebInspector.Snippet = function(storage, id, name, content) { this._storage = storage; this._id = id; this._name = name || storage.namePrefix + id; this._content = content || ""; } WebInspector.Snippet.fromObject = function(storage, serializedSnippet) { return new WebInspector.Snippet(storage, serializedSnippet.id, serializedSnippet.name, serializedSnippet.content); } WebInspector.Snippet.prototype = { get id() { return this._id; }, get name() { return this._name; }, set name(name) { if (this._name === name) return; this._name = name; this._storage._saveSettings(); }, get content() { return this._content; }, set content(content) { if (this._content === content) return; this._content = content; this._storage._saveSettings(); }, serializeToObject: function() { var serializedSnippet = {}; serializedSnippet.id = this.id; serializedSnippet.name = this.name; serializedSnippet.content = this.content; return serializedSnippet; }, __proto__: WebInspector.Object.prototype } WebInspector.ScriptSnippetModel = function(workspace, networkWorkspaceProvider) { this._workspace = workspace; this._networkWorkspaceProvider = networkWorkspaceProvider; this._uiSourceCodeForScriptId = {}; this._scriptForUISourceCode = new Map(); this._uiSourceCodeForSnippetId = {}; this._snippetIdForUISourceCode = new Map(); this._snippetStorage = new WebInspector.SnippetStorage("script", "Script snippet #"); this._lastSnippetEvaluationIndexSetting = WebInspector.settings.createSetting("lastSnippetEvaluationIndex", 0); this._snippetScriptMapping = new WebInspector.SnippetScriptMapping(this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._projectWillReset, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectDidReset, this._projectDidReset, this); this._loadSnippets(); } WebInspector.ScriptSnippetModel.prototype = { get scriptMapping() { return this._snippetScriptMapping; }, _loadSnippets: function() { var snippets = this._snippetStorage.snippets(); for (var i = 0; i < snippets.length; ++i) this._addScriptSnippet(snippets[i]); }, createScriptSnippet: function() { var snippet = this._snippetStorage.createSnippet(); return this._addScriptSnippet(snippet); }, _addScriptSnippet: function(snippet) { this._networkWorkspaceProvider.addFile(snippet.name, new WebInspector.SnippetContentProvider(snippet), true, false, true); var uiSourceCode = this._workspace.uiSourceCodeForURL(snippet.name); var scriptFile = new WebInspector.SnippetScriptFile(this, uiSourceCode); uiSourceCode.setScriptFile(scriptFile); this._snippetIdForUISourceCode.put(uiSourceCode, snippet.id); uiSourceCode.setSourceMapping(this._snippetScriptMapping); this._uiSourceCodeForSnippetId[snippet.id] = uiSourceCode; return uiSourceCode; }, deleteScriptSnippet: function(uiSourceCode) { var snippetId = this._snippetIdForUISourceCode.get(uiSourceCode); var snippet = this._snippetStorage.snippetForId(snippetId); this._snippetStorage.deleteSnippet(snippet); this._removeBreakpoints(uiSourceCode); this._releaseSnippetScript(uiSourceCode); delete this._uiSourceCodeForSnippetId[snippet.id]; this._snippetIdForUISourceCode.remove(uiSourceCode); this._networkWorkspaceProvider.removeFile(snippet.name); }, renameScriptSnippet: function(uiSourceCode, newName) { var breakpointLocations = this._removeBreakpoints(uiSourceCode); var snippetId = this._snippetIdForUISourceCode.get(uiSourceCode); var snippet = this._snippetStorage.snippetForId(snippetId); if (!snippet || !newName || snippet.name === newName) return; snippet.name = newName; this._restoreBreakpoints(uiSourceCode, breakpointLocations); uiSourceCode.urlChanged(snippet.name); }, _setScriptSnippetContent: function(uiSourceCode, newContent) { var snippetId = this._snippetIdForUISourceCode.get(uiSourceCode); var snippet = this._snippetStorage.snippetForId(snippetId); snippet.content = newContent; }, _scriptSnippetEdited: function(uiSourceCode) { var script = this._scriptForUISourceCode.get(uiSourceCode); if (!script) return; var breakpointLocations = this._removeBreakpoints(uiSourceCode); var createdUISourceCode = this._releaseSnippetScript(uiSourceCode); this._restoreBreakpoints(uiSourceCode, breakpointLocations); if (createdUISourceCode) this._restoreBreakpoints(createdUISourceCode, breakpointLocations); }, _nextEvaluationIndex: function(snippetId) { var evaluationIndex = this._lastSnippetEvaluationIndexSetting.get() + 1; this._lastSnippetEvaluationIndexSetting.set(evaluationIndex); return evaluationIndex; }, evaluateScriptSnippet: function(uiSourceCode) { var breakpointLocations = this._removeBreakpoints(uiSourceCode); this._releaseSnippetScript(uiSourceCode); this._restoreBreakpoints(uiSourceCode, breakpointLocations); var snippetId = this._snippetIdForUISourceCode.get(uiSourceCode); var evaluationIndex = this._nextEvaluationIndex(snippetId); uiSourceCode._evaluationIndex = evaluationIndex; var evaluationUrl = this._evaluationSourceURL(uiSourceCode); var expression = uiSourceCode.workingCopy(); if (WebInspector.debuggerModel.selectedCallFrame() || !Capabilities.separateScriptCompilationAndExecutionEnabled) { expression = uiSourceCode.workingCopy() + "\n//@ sourceURL=" + evaluationUrl + "\n"; WebInspector.evaluateInConsole(expression, true); return; } WebInspector.showConsole(); DebuggerAgent.compileScript(expression, evaluationUrl, compileCallback.bind(this)); function compileCallback(error, scriptId, syntaxErrorMessage) { if (!uiSourceCode || uiSourceCode._evaluationIndex !== evaluationIndex) return; if (error) { console.error(error); return; } if (!scriptId) { var consoleMessage = WebInspector.ConsoleMessage.create( WebInspector.ConsoleMessage.MessageSource.JS, WebInspector.ConsoleMessage.MessageLevel.Error, syntaxErrorMessage || ""); WebInspector.console.addMessage(consoleMessage); return; } var breakpointLocations = this._removeBreakpoints(uiSourceCode); this._restoreBreakpoints(uiSourceCode, breakpointLocations); this._runScript(scriptId); } }, _runScript: function(scriptId) { var currentExecutionContext = WebInspector.runtimeModel.currentExecutionContext(); DebuggerAgent.runScript(scriptId, currentExecutionContext ? currentExecutionContext.id : undefined, "console", false, runCallback.bind(this)); function runCallback(error, result, wasThrown) { if (error) { console.error(error); return; } this._printRunScriptResult(result, wasThrown); } }, _printRunScriptResult: function(result, wasThrown) { var level = (wasThrown ? WebInspector.ConsoleMessage.MessageLevel.Error : WebInspector.ConsoleMessage.MessageLevel.Log); var message = WebInspector.ConsoleMessage.create(WebInspector.ConsoleMessage.MessageSource.JS, level, "", undefined, undefined, undefined, undefined, [result]); WebInspector.console.addMessage(message) }, _rawLocationToUILocation: function(rawLocation) { var uiSourceCode = this._uiSourceCodeForScriptId[rawLocation.scriptId]; return new WebInspector.UILocation(uiSourceCode, rawLocation.lineNumber, rawLocation.columnNumber || 0); }, _uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { var script = this._scriptForUISourceCode.get(uiSourceCode); if (!script) return null; return WebInspector.debuggerModel.createRawLocation(script, lineNumber, columnNumber); }, _releasedUISourceCodes: function() { var result = []; for (var scriptId in this._uiSourceCodeForScriptId) { var uiSourceCode = this._uiSourceCodeForScriptId[scriptId]; if (uiSourceCode.isTemporary) result.push(uiSourceCode); } return result; }, _addScript: function(script) { var snippetId = this._snippetIdForSourceURL(script.sourceURL); if (!snippetId) return; var uiSourceCode = this._uiSourceCodeForSnippetId[snippetId]; if (!uiSourceCode || this._evaluationSourceURL(uiSourceCode) !== script.sourceURL) { this._createUISourceCodeForScript(script); return; } console.assert(!this._scriptForUISourceCode.get(uiSourceCode)); this._uiSourceCodeForScriptId[script.scriptId] = uiSourceCode; this._scriptForUISourceCode.put(uiSourceCode, script); uiSourceCode.scriptFile().setHasDivergedFromVM(false); script.setSourceMapping(this._snippetScriptMapping); }, _createUISourceCodeForScript: function(script) { var uiSourceCode = this._workspace.addTemporaryUISourceCode(script.sourceURL, script, false, true); uiSourceCode.setSourceMapping(this._snippetScriptMapping); this._uiSourceCodeForScriptId[script.scriptId] = uiSourceCode; this._scriptForUISourceCode.put(uiSourceCode, script); script.setSourceMapping(this._snippetScriptMapping); return uiSourceCode; }, _removeBreakpoints: function(uiSourceCode) { var breakpointLocations = WebInspector.breakpointManager.breakpointLocationsForUISourceCode(uiSourceCode); for (var i = 0; i < breakpointLocations.length; ++i) breakpointLocations[i].breakpoint.remove(); return breakpointLocations; }, _restoreBreakpoints: function(uiSourceCode, breakpointLocations) { for (var i = 0; i < breakpointLocations.length; ++i) { var uiLocation = breakpointLocations[i].uiLocation; var breakpoint = breakpointLocations[i].breakpoint; WebInspector.breakpointManager.setBreakpoint(uiSourceCode, uiLocation.lineNumber, breakpoint.condition(), breakpoint.enabled()); } }, _releaseSnippetScript: function(uiSourceCode) { var script = this._scriptForUISourceCode.get(uiSourceCode); if (!script) return null; uiSourceCode.scriptFile().setIsDivergingFromVM(true); uiSourceCode.scriptFile().setHasDivergedFromVM(true); delete this._uiSourceCodeForScriptId[script.scriptId]; this._scriptForUISourceCode.remove(uiSourceCode); delete uiSourceCode._evaluationIndex; var createdUISourceCode = this._createUISourceCodeForScript(script); uiSourceCode.scriptFile().setIsDivergingFromVM(false); return createdUISourceCode; }, _evaluationSourceURL: function(uiSourceCode) { var evaluationSuffix = "_" + uiSourceCode._evaluationIndex; var snippetId = this._snippetIdForUISourceCode.get(uiSourceCode); return WebInspector.Script.snippetSourceURLPrefix + snippetId + evaluationSuffix; }, _snippetIdForSourceURL: function(sourceURL) { var snippetPrefix = WebInspector.Script.snippetSourceURLPrefix; if (!sourceURL.startsWith(snippetPrefix)) return null; var splittedURL = sourceURL.substring(snippetPrefix.length).split("_"); var snippetId = splittedURL[0]; return snippetId; }, _projectWillReset: function() { var removedUISourceCodes = this._releasedUISourceCodes(); this._uiSourceCodeForScriptId = {}; this._scriptForUISourceCode = new Map(); this._uiSourceCodeForSnippetId = {}; this._snippetIdForUISourceCode = new Map(); }, _projectDidReset: function() { this._loadSnippets(); }, __proto__: WebInspector.Object.prototype } WebInspector.SnippetScriptFile = function(scriptSnippetModel, uiSourceCode) { WebInspector.ScriptFile.call(this); this._scriptSnippetModel = scriptSnippetModel; this._uiSourceCode = uiSourceCode; this._hasDivergedFromVM = true; this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this); } WebInspector.SnippetScriptFile.prototype = { hasDivergedFromVM: function() { return this._hasDivergedFromVM; }, setHasDivergedFromVM: function(hasDivergedFromVM) { this._hasDivergedFromVM = hasDivergedFromVM; }, isDivergingFromVM: function() { return this._isDivergingFromVM; }, setIsDivergingFromVM: function(isDivergingFromVM) { this._isDivergingFromVM = isDivergingFromVM; }, _workingCopyCommitted: function() { this._scriptSnippetModel._setScriptSnippetContent(this._uiSourceCode, this._uiSourceCode.workingCopy()); }, _workingCopyChanged: function() { this._scriptSnippetModel._scriptSnippetEdited(this._uiSourceCode); }, __proto__: WebInspector.Object.prototype } WebInspector.SnippetScriptMapping = function(scriptSnippetModel) { this._scriptSnippetModel = scriptSnippetModel; } WebInspector.SnippetScriptMapping.prototype = { rawLocationToUILocation: function(rawLocation) { var debuggerModelLocation = rawLocation; return this._scriptSnippetModel._rawLocationToUILocation(debuggerModelLocation); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { return this._scriptSnippetModel._uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber); }, snippetIdForSourceURL: function(sourceURL) { return this._scriptSnippetModel._snippetIdForSourceURL(sourceURL); }, addScript: function(script) { this._scriptSnippetModel._addScript(script); } } WebInspector.SnippetContentProvider = function(snippet) { WebInspector.StaticContentProvider.call(this, WebInspector.resourceTypes.Script, snippet.content); } WebInspector.SnippetContentProvider.prototype = { __proto__: WebInspector.StaticContentProvider.prototype } WebInspector.scriptSnippetModel = null; WebInspector.Progress = function() { } WebInspector.Progress.prototype = { setTotalWork: function(totalWork) { }, setTitle: function(title) { }, setWorked: function(worked, title) { }, worked: function(worked) { }, done: function() { }, isCanceled: function() { return false; } } WebInspector.CompositeProgress = function(parent) { this._parent = parent; this._children = []; this._childrenDone = 0; this._parent.setTotalWork(1); this._parent.setWorked(0); } WebInspector.CompositeProgress.prototype = { _childDone: function() { if (++this._childrenDone === this._children.length) this._parent.done(); }, createSubProgress: function(weight) { var child = new WebInspector.SubProgress(this, weight); this._children.push(child); return child; }, _update: function() { var totalWeights = 0; var done = 0; for (var i = 0; i < this._children.length; ++i) { var child = this._children[i]; if (child._totalWork) done += child._weight * child._worked / child._totalWork; totalWeights += child._weight; } this._parent.setWorked(done / totalWeights); } } WebInspector.SubProgress = function(composite, weight) { this._composite = composite; this._weight = weight || 1; this._worked = 0; } WebInspector.SubProgress.prototype = { isCanceled: function() { return this._composite._parent.isCanceled(); }, setTitle: function(title) { this._composite._parent.setTitle(title); }, done: function() { this.setWorked(this._totalWork); this._composite._childDone(); }, setTotalWork: function(totalWork) { this._totalWork = totalWork; this._composite._update(); }, setWorked: function(worked, title) { this._worked = worked; if (typeof title !== "undefined") this.setTitle(title); this._composite._update(); }, worked: function(worked) { this.setWorked(this._worked + (worked || 1)); } } WebInspector.ProgressIndicator = function() { this.element = document.createElement("div"); this.element.className = "progress-bar-container"; this._labelElement = this.element.createChild("span"); this._progressElement = this.element.createChild("progress"); this._stopButton = new WebInspector.StatusBarButton(WebInspector.UIString("Cancel"), "progress-bar-stop-button"); this._stopButton.addEventListener("click", this.cancel, this); this.element.appendChild(this._stopButton.element); this._isCanceled = false; this._worked = 0; } WebInspector.ProgressIndicator.Events = { Done: "Done" } WebInspector.ProgressIndicator.prototype = { show: function(parent) { parent.appendChild(this.element); }, hide: function() { var parent = this.element.parentElement; if (parent) parent.removeChild(this.element); }, done: function() { if (this._isDone) return; this._isDone = true; this.hide(); this.dispatchEventToListeners(WebInspector.ProgressIndicator.Events.Done); }, cancel: function() { this._isCanceled = true; }, isCanceled: function() { return this._isCanceled; }, setTitle: function(title) { this._labelElement.textContent = title; }, setTotalWork: function(totalWork) { this._progressElement.max = totalWork; }, setWorked: function(worked, title) { this._worked = worked; this._progressElement.value = worked; if (title) this.setTitle(title); }, worked: function(worked) { this.setWorked(this._worked + (worked || 1)); }, __proto__: WebInspector.Object.prototype } WebInspector.StylesSourceMapping = function(workspace) { this._workspace = workspace; this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._reset, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._uiSourceCodeAddedToWorkspace, this); this._uiSourceCodeForURL = {}; } WebInspector.StylesSourceMapping.prototype = { rawLocationToUILocation: function(rawLocation) { var location = (rawLocation); var uiSourceCode = this._uiSourceCodeForURL[location.url]; return new WebInspector.UILocation(uiSourceCode, location.lineNumber, 0); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { return new WebInspector.CSSLocation(uiSourceCode.contentURL() || "", lineNumber); }, _uiSourceCodeAddedToWorkspace: function(event) { var uiSourceCode = (event.data); if (!uiSourceCode.url || this._uiSourceCodeForURL[uiSourceCode.url]) return; if (uiSourceCode.contentType() !== WebInspector.resourceTypes.Stylesheet) return; if (!WebInspector.resourceForURL(uiSourceCode.url)) return; this._addUISourceCode(uiSourceCode); }, _addUISourceCode: function(uiSourceCode) { this._uiSourceCodeForURL[uiSourceCode.url] = uiSourceCode; uiSourceCode.setSourceMapping(this); var styleFile = new WebInspector.StyleFile(uiSourceCode); uiSourceCode.setStyleFile(styleFile); WebInspector.cssModel.setSourceMapping(uiSourceCode.url, this); }, _reset: function() { this._uiSourceCodeForURL = {}; WebInspector.cssModel.resetSourceMappings(); } } WebInspector.StyleFile = function(uiSourceCode) { this._uiSourceCode = uiSourceCode; this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this); } WebInspector.StyleFile.updateTimeout = 200; WebInspector.StyleFile.prototype = { _workingCopyCommitted: function(event) { if (this._isAddingRevision) return; this._commitIncrementalEdit(true); }, _workingCopyChanged: function(event) { if (this._isAddingRevision) return; if (WebInspector.StyleFile.updateTimeout >= 0) { this._incrementalUpdateTimer = setTimeout(this._commitIncrementalEdit.bind(this, false), WebInspector.StyleFile.updateTimeout) } else this._commitIncrementalEdit(false); }, _commitIncrementalEdit: function(majorChange) { this._clearIncrementalUpdateTimer(); WebInspector.styleContentBinding.setStyleContent(this._uiSourceCode, this._uiSourceCode.workingCopy(), majorChange, this._styleContentSet.bind(this)); }, _styleContentSet: function(error) { if (error) WebInspector.showErrorMessage(error); }, _clearIncrementalUpdateTimer: function() { if (!this._incrementalUpdateTimer) return; clearTimeout(this._incrementalUpdateTimer); delete this._incrementalUpdateTimer; }, addRevision: function(content) { this._isAddingRevision = true; this._uiSourceCode.addRevision(content); delete this._isAddingRevision; }, } WebInspector.StyleContentBinding = function(cssModel) { this._cssModel = cssModel; this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetChanged, this); } WebInspector.StyleContentBinding.prototype = { setStyleContent: function(uiSourceCode, content, majorChange, userCallback) { var resource = WebInspector.resourceForURL(uiSourceCode.url); if (!resource) { userCallback("No resource found: " + uiSourceCode.url); return; } this._cssModel.resourceBinding().requestStyleSheetIdForResource(resource, callback.bind(this)); function callback(styleSheetId) { if (!styleSheetId) { userCallback("No stylesheet found: " + resource.frameId + ":" + resource.url); return; } this._innerSetContent(styleSheetId, content, majorChange, userCallback, null); } }, _innerSetContent: function(styleSheetId, content, majorChange, userCallback) { this._isSettingContent = true; function callback(error) { userCallback(error); delete this._isSettingContent; } this._cssModel.setStyleSheetText(styleSheetId, content, majorChange, callback.bind(this)); }, _styleSheetChanged: function(event) { if (this._isSettingContent) return; if (!event.data.majorChange) return; function callback(error, content) { if (!error) this._innerStyleSheetChanged(event.data.styleSheetId, content); } CSSAgent.getStyleSheetText(event.data.styleSheetId, callback.bind(this)); }, _innerStyleSheetChanged: function(styleSheetId, content) { function callback(styleSheetURL) { if (typeof styleSheetURL !== "string") return; var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(styleSheetURL); if (!uiSourceCode) return; if (uiSourceCode.styleFile()) uiSourceCode.styleFile().addRevision(content); } this._cssModel.resourceBinding().requestResourceURLForStyleSheetId(styleSheetId, callback.bind(this)); }, } WebInspector.styleContentBinding = null; WebInspector.NetworkUISourceCodeProvider = function(workspace, networkWorkspaceProvider) { this._workspace = workspace; this._networkWorkspaceProvider = networkWorkspaceProvider; WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, this._resourceAdded, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._projectWillReset, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectDidReset, this._projectDidReset, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this); this._processedURLs = {}; this._lastDynamicAnonymousScriptIndexForURL = {}; } WebInspector.NetworkUISourceCodeProvider.prototype = { _populate: function() { function populateFrame(frame) { for (var i = 0; i < frame.childFrames.length; ++i) populateFrame.call(this, frame.childFrames[i]); var resources = frame.resources(); for (var i = 0; i < resources.length; ++i) this._resourceAdded({data:resources[i]}); } populateFrame.call(this, WebInspector.resourceTreeModel.mainFrame); }, _parsedScriptSource: function(event) { var script = (event.data); if (!script.sourceURL || script.isInlineScript()) return; if (WebInspector.experimentsSettings.snippetsSupport.isEnabled() && script.isSnippet()) return; var isDynamicAnonymousScript; if (!script.hasSourceURL && !script.isContentScript) { var requestURL = script.sourceURL.replace(/#.*/, ""); if (WebInspector.resourceForURL(requestURL) || WebInspector.networkLog.requestForURL(requestURL)) return; } if (script.isContentScript && !script.hasSourceURL) { var parsedURL = new WebInspector.ParsedURL(script.sourceURL); if (!parsedURL.host) return; } this._addFile(script.sourceURL, script, script.isContentScript); }, _resourceAdded: function(event) { var resource = (event.data); this._addFile(resource.url, resource); }, _addFile: function(url, contentProvider, isContentScript) { var type = contentProvider.contentType(); if (type !== WebInspector.resourceTypes.Stylesheet && type !== WebInspector.resourceTypes.Document && type !== WebInspector.resourceTypes.Script) return; if (this._processedURLs[url]) return; this._processedURLs[url] = true; var isEditable = type !== WebInspector.resourceTypes.Document; this._networkWorkspaceProvider.addFile(url, contentProvider, isEditable, isContentScript); }, _projectWillReset: function() { this._processedURLs = {}; this._lastDynamicAnonymousScriptIndexForURL = {}; }, _projectDidReset: function() { this._populate(); } } WebInspector.ElementsPanelDescriptor = function() { WebInspector.PanelDescriptor.call(this, "elements", WebInspector.UIString("Elements"), "ElementsPanel", "ElementsPanel.js"); WebInspector.ContextMenu.registerProvider(this); } WebInspector.ElementsPanelDescriptor.prototype = { appendApplicableItems: function(event, contextMenu, target) { if (!(target instanceof WebInspector.RemoteObject)) return; var remoteObject = (target); if (remoteObject.subtype !== "node") return; this.panel().appendApplicableItems(event, contextMenu, target); }, registerShortcuts: function() { var elementsSection = WebInspector.shortcutsScreen.section(WebInspector.UIString("Elements Panel")); var navigate = WebInspector.ElementsPanelDescriptor.ShortcutKeys.NavigateUp.concat(WebInspector.ElementsPanelDescriptor.ShortcutKeys.NavigateDown); elementsSection.addRelatedKeys(navigate, WebInspector.UIString("Navigate elements")); var expandCollapse = WebInspector.ElementsPanelDescriptor.ShortcutKeys.Expand.concat(WebInspector.ElementsPanelDescriptor.ShortcutKeys.Collapse); elementsSection.addRelatedKeys(expandCollapse, WebInspector.UIString("Expand/collapse")); elementsSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.EditAttribute, WebInspector.UIString("Edit attribute")); elementsSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.HideElement, WebInspector.UIString("Hide element")); elementsSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.ToggleEditAsHTML, WebInspector.UIString("Toggle edit as HTML")); var stylesPaneSection = WebInspector.shortcutsScreen.section(WebInspector.UIString("Styles Pane")); var nextPreviousProperty = WebInspector.ElementsPanelDescriptor.ShortcutKeys.NextProperty.concat(WebInspector.ElementsPanelDescriptor.ShortcutKeys.PreviousProperty); stylesPaneSection.addRelatedKeys(nextPreviousProperty, WebInspector.UIString("Next/previous property")); stylesPaneSection.addRelatedKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.IncrementValue, WebInspector.UIString("Increment value")); stylesPaneSection.addRelatedKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.DecrementValue, WebInspector.UIString("Decrement value")); stylesPaneSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.IncrementBy10, WebInspector.UIString("Increment by %f", 10)); stylesPaneSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.DecrementBy10, WebInspector.UIString("Decrement by %f", 10)); stylesPaneSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.IncrementBy100, WebInspector.UIString("Increment by %f", 100)); stylesPaneSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.DecrementBy100, WebInspector.UIString("Decrement by %f", 100)); stylesPaneSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.IncrementBy01, WebInspector.UIString("Increment by %f", 0.1)); stylesPaneSection.addAlternateKeys(WebInspector.ElementsPanelDescriptor.ShortcutKeys.DecrementBy01, WebInspector.UIString("Decrement by %f", 0.1)); }, __proto__: WebInspector.PanelDescriptor.prototype } WebInspector.ElementsPanelDescriptor.ShortcutKeys = { NavigateUp: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up) ], NavigateDown: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down) ], Expand: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Right) ], Collapse: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Left) ], EditAttribute: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Enter) ], HideElement: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.H) ], ToggleEditAsHTML: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F2) ], NextProperty: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Tab) ], PreviousProperty: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Tab, WebInspector.KeyboardShortcut.Modifiers.Shift) ], IncrementValue: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up) ], DecrementValue: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down) ], IncrementBy10: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageUp), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up, WebInspector.KeyboardShortcut.Modifiers.Shift) ], DecrementBy10: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageDown), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down, WebInspector.KeyboardShortcut.Modifiers.Shift) ], IncrementBy100: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageUp, WebInspector.KeyboardShortcut.Modifiers.Shift) ], DecrementBy100: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageDown, WebInspector.KeyboardShortcut.Modifiers.Shift) ], IncrementBy01: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageUp, WebInspector.KeyboardShortcut.Modifiers.Alt) ], DecrementBy01: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageDown, WebInspector.KeyboardShortcut.Modifiers.Alt) ] }; WebInspector.NetworkPanelDescriptor = function() { WebInspector.PanelDescriptor.call(this, "network", WebInspector.UIString("Network"), "NetworkPanel", "NetworkPanel.js"); WebInspector.ContextMenu.registerProvider(this); } WebInspector.NetworkPanelDescriptor.prototype = { appendApplicableItems: function(event, contextMenu, target) { if (!(target instanceof WebInspector.NetworkRequest)) return; this.panel().appendApplicableItems(event, contextMenu, target); }, __proto__: WebInspector.PanelDescriptor.prototype } WebInspector.ScriptsPanelDescriptor = function() { WebInspector.PanelDescriptor.call(this, "scripts", WebInspector.UIString("Sources"), "ScriptsPanel", "ScriptsPanel.js"); WebInspector.ContextMenu.registerProvider(this); } WebInspector.ScriptsPanelDescriptor.prototype = { appendApplicableItems: function(event, contextMenu, target) { var hasApplicableItems = target instanceof WebInspector.UISourceCode; if (!hasApplicableItems && target instanceof WebInspector.RemoteObject) { var remoteObject = (target); if (remoteObject.type !== "function") return; } this.panel().appendApplicableItems(event, contextMenu, target); }, registerShortcuts: function() { var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Sources Panel")); section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.PauseContinue, WebInspector.UIString("Pause/Continue")); section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOver, WebInspector.UIString("Step over")); section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepInto, WebInspector.UIString("Step into")); section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOut, WebInspector.UIString("Step out")); var nextAndPrevFrameKeys = WebInspector.ScriptsPanelDescriptor.ShortcutKeys.NextCallFrame.concat(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.PrevCallFrame); section.addRelatedKeys(nextAndPrevFrameKeys, WebInspector.UIString("Next/previous call frame")); section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.EvaluateSelectionInConsole, WebInspector.UIString("Evaluate selection in console")); section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.GoToMember, WebInspector.UIString("Go to member")); section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.ToggleBreakpoint, WebInspector.UIString("Toggle breakpoint")); }, __proto__: WebInspector.PanelDescriptor.prototype } WebInspector.ScriptsPanelDescriptor.ShortcutKeys = { PauseContinue: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F8), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Slash, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ], StepOver: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F10), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.SingleQuote, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ], StepInto: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ], StepOut: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ], EvaluateSelectionInConsole: [ WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.Ctrl) ], GoToMember: [ WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta | WebInspector.KeyboardShortcut.Modifiers.Shift) ], ToggleBreakpoint: [ WebInspector.KeyboardShortcut.makeDescriptor("b", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ], NextCallFrame: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Period, WebInspector.KeyboardShortcut.Modifiers.Ctrl) ], PrevCallFrame: [ WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Comma, WebInspector.KeyboardShortcut.Modifiers.Ctrl) ] }; WebInspector.TimelinePanelDescriptor = function() { WebInspector.PanelDescriptor.call(this, "timeline", WebInspector.UIString("Timeline"), "TimelinePanel", "TimelinePanel.js"); } WebInspector.TimelinePanelDescriptor.prototype = { registerShortcuts: function() { var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Timeline Panel")); section.addAlternateKeys(WebInspector.TimelinePanelDescriptor.ShortcutKeys.StartStopRecording, WebInspector.UIString("Start/stop recording")); if (InspectorFrontendHost.canSave()) section.addAlternateKeys(WebInspector.TimelinePanelDescriptor.ShortcutKeys.SaveToFile, WebInspector.UIString("Save timeline data")); section.addAlternateKeys(WebInspector.TimelinePanelDescriptor.ShortcutKeys.LoadFromFile, WebInspector.UIString("Load timeline data")); }, __proto__: WebInspector.PanelDescriptor.prototype } WebInspector.TimelinePanelDescriptor.ShortcutKeys = { StartStopRecording: [ WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ], SaveToFile: [ WebInspector.KeyboardShortcut.makeDescriptor("s", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ], LoadFromFile: [ WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta) ] } WebInspector.DockController = function() { this._dockToggleButton = new WebInspector.StatusBarButton("", "dock-status-bar-item", 3); this._dockToggleButtonOption = new WebInspector.StatusBarButton("", "dock-status-bar-item", 3); this._dockToggleButton.addEventListener("click", this._toggleDockState, this); this._dockToggleButtonOption.addEventListener("click", this._toggleDockState, this); if (Preferences.showDockToRight) this._dockToggleButton.makeLongClickEnabled(this._createDockOptions.bind(this)); this.setDockSide(WebInspector.queryParamsObject["dockSide"] || "bottom"); WebInspector.settings.showToolbarIcons.addChangeListener(this._updateUI.bind(this)); } WebInspector.DockController.State = { DockedToBottom: "bottom", DockedToRight: "right", Undocked: "undocked" } WebInspector.DockController.prototype = { get element() { return this._dockToggleButton.element; }, setDockSide: function(dockSide) { if (this._dockSide === dockSide) return; if (this._dockSide) WebInspector.settings.lastDockState.set(this._dockSide); this._dockSide = dockSide; if (dockSide === WebInspector.DockController.State.Undocked) WebInspector.userMetrics.WindowDocked.record(); else WebInspector.userMetrics.WindowUndocked.record(); this._updateUI(); }, setDockingUnavailable: function(unavailable) { this._isDockingUnavailable = unavailable; this._updateUI(); }, _updateUI: function() { var body = document.body; switch (this._dockSide) { case WebInspector.DockController.State.DockedToBottom: body.removeStyleClass("undocked"); body.removeStyleClass("dock-to-right"); body.addStyleClass("dock-to-bottom"); break; case WebInspector.DockController.State.DockedToRight: body.removeStyleClass("undocked"); body.addStyleClass("dock-to-right"); body.removeStyleClass("dock-to-bottom"); break; case WebInspector.DockController.State.Undocked: body.addStyleClass("undocked"); body.removeStyleClass("dock-to-right"); body.removeStyleClass("dock-to-bottom"); break; } if (WebInspector.toolbar) WebInspector.toolbar.setDockedToBottom(this._dockSide === WebInspector.DockController.State.DockedToBottom); if (WebInspector.settings.showToolbarIcons.get()) document.body.addStyleClass("show-toolbar-icons"); else document.body.removeStyleClass("show-toolbar-icons"); if (this._isDockingUnavailable) { this._dockToggleButton.state = "undock"; this._dockToggleButton.setEnabled(false); return; } this._dockToggleButton.setEnabled(true); var sides = [WebInspector.DockController.State.DockedToBottom, WebInspector.DockController.State.Undocked, WebInspector.DockController.State.DockedToRight]; sides.remove(this._dockSide); var lastState = WebInspector.settings.lastDockState.get(); sides.remove(lastState); if (sides.length === 2) { lastState = sides[0]; sides.remove(lastState); } this._decorateButtonForTargetState(this._dockToggleButton, lastState); this._decorateButtonForTargetState(this._dockToggleButtonOption, sides[0]); }, _decorateButtonForTargetState: function(button, state) { switch (state) { case WebInspector.DockController.State.DockedToBottom: button.title = WebInspector.UIString("Dock to main window."); button.state = "bottom"; break; case WebInspector.DockController.State.DockedToRight: button.title = WebInspector.UIString("Dock to main window."); button.state = "right"; break; case WebInspector.DockController.State.Undocked: button.title = WebInspector.UIString("Undock into separate window."); button.state = "undock"; break; } }, _createDockOptions: function() { return [this._dockToggleButtonOption]; }, _toggleDockState: function(e) { var action; switch (e.target.state) { case "bottom": action = "bottom"; break; case "right": action = "right"; break; case "undock": action = "undocked"; break; } InspectorFrontendHost.requestSetDockSide(action); } } {(function () { Preferences.useLowerCaseMenuTitlesOnWindows = true; Preferences.sharedWorkersDebugNote = "Shared workers can be inspected in the Task Manager"; Preferences.localizeUI = false; Preferences.applicationTitle = "Developer Tools - %s"; Preferences.exposeDisableCache = true; Preferences.showDockToRight = true; Preferences.exposeFileSystemInspection = true; Preferences.experimentsEnabled = false; })();} function buildPlatformExtensionAPI(extensionInfo) { return "var extensionInfo = " + JSON.stringify(extensionInfo) + ";" + "var tabId = " + WebInspector._inspectedTabId + ";" + platformExtensionAPI.toString(); } WebInspector.setInspectedTabId = function(tabId) { WebInspector._inspectedTabId = tabId; } WebInspector.clipboardAccessDeniedMessage = function() { return "You need to install a Chrome extension that grants clipboard access to Developer Tools."; } function platformExtensionAPI(coreAPI) { function getTabId() { return tabId; } chrome = window.chrome || {}; var devtools_descriptor = Object.getOwnPropertyDescriptor(chrome, "devtools"); if (!devtools_descriptor || devtools_descriptor.get) Object.defineProperty(chrome, "devtools", { value: {}, enumerable: true }); chrome.devtools.inspectedWindow = {}; chrome.devtools.inspectedWindow.__defineGetter__("tabId", getTabId); chrome.devtools.inspectedWindow.__proto__ = coreAPI.inspectedWindow; chrome.devtools.network = coreAPI.network; chrome.devtools.panels = coreAPI.panels; if (extensionInfo.exposeExperimentalAPIs !== false) { chrome.experimental = chrome.experimental || {}; chrome.experimental.devtools = chrome.experimental.devtools || {}; var properties = Object.getOwnPropertyNames(coreAPI); for (var i = 0; i < properties.length; ++i) { var descriptor = Object.getOwnPropertyDescriptor(coreAPI, properties[i]); Object.defineProperty(chrome.experimental.devtools, properties[i], descriptor); } chrome.experimental.devtools.inspectedWindow = chrome.devtools.inspectedWindow; } if (extensionInfo.exposeWebInspectorNamespace) window.webInspector = coreAPI; } if (window.domAutomationController) { var ___interactiveUiTestsMode = true; TestSuite = function() { this.controlTaken_ = false; this.timerId_ = -1; }; TestSuite.prototype.fail = function(message) { if (this.controlTaken_) this.reportFailure_(message); else throw message; }; TestSuite.prototype.assertEquals = function(expected, actual, opt_message) { if (expected !== actual) { var message = "Expected: '" + expected + "', but was '" + actual + "'"; if (opt_message) message = opt_message + "(" + message + ")"; this.fail(message); } }; TestSuite.prototype.assertTrue = function(value, opt_message) { this.assertEquals(true, !!value, opt_message); }; TestSuite.prototype.assertContains = function(string, substring) { if (string.indexOf(substring) === -1) this.fail("Expected to: '" + string + "' to contain '" + substring + "'"); }; TestSuite.prototype.takeControl = function() { this.controlTaken_ = true; var self = this; this.timerId_ = setTimeout(function() { self.reportFailure_("Timeout exceeded: 20 sec"); }, 20000); }; TestSuite.prototype.releaseControl = function() { if (this.timerId_ !== -1) { clearTimeout(this.timerId_); this.timerId_ = -1; } this.reportOk_(); }; TestSuite.prototype.reportOk_ = function() { window.domAutomationController.send("[OK]"); }; TestSuite.prototype.reportFailure_ = function(error) { if (this.timerId_ !== -1) { clearTimeout(this.timerId_); this.timerId_ = -1; } window.domAutomationController.send("[FAILED] " + error); }; TestSuite.prototype.runTest = function(testName) { try { this[testName](); if (!this.controlTaken_) this.reportOk_(); } catch (e) { this.reportFailure_(e); } }; TestSuite.prototype.showPanel = function(panelName) { var toolbar = document.getElementById("toolbar"); var button = toolbar.getElementsByClassName(panelName)[0]; button.click(); this.assertEquals(WebInspector.panels[panelName], WebInspector.inspectorView.currentPanel()); }; TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) { var orig = receiver[methodName]; if (typeof orig !== "function") this.fail("Cannot find method to override: " + methodName); var test = this; receiver[methodName] = function(var_args) { try { var result = orig.apply(this, arguments); } finally { if (!opt_sticky) receiver[methodName] = orig; } try { override.apply(this, arguments); } catch (e) { test.fail("Exception in overriden method '" + methodName + "': " + e); } return result; }; }; TestSuite.prototype.testEnableResourcesTab = function() { } TestSuite.prototype.testCompletionOnPause = function() { } TestSuite.prototype.testShowScriptsTab = function() { this.showPanel("scripts"); var test = this; this._waitUntilScriptsAreParsed(["debugger_test_page.html"], function() { test.releaseControl(); }); this.takeControl(); }; TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() { var test = this; this.assertEquals(WebInspector.panels.elements, WebInspector.inspectorView.currentPanel(), "Elements panel should be current one."); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); test.evaluateInConsole_("window.location.reload(true);", function(resultText) {}); function waitUntilScriptIsParsed() { WebInspector.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); test.showPanel("scripts"); test._waitUntilScriptsAreParsed(["debugger_test_page.html"], function() { test.releaseControl(); }); } this.takeControl(); }; TestSuite.prototype.testContentScriptIsPresent = function() { this.showPanel("scripts"); var test = this; test._waitUntilScriptsAreParsed( ["page_with_content_script.html", "simple_content_script.js"], function() { test.releaseControl(); }); this.takeControl(); }; TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() { var test = this; var expectedScriptsCount = 2; var parsedScripts = []; this.showPanel("scripts"); function switchToElementsTab() { test.showPanel("elements"); setTimeout(switchToScriptsTab, 0); } function switchToScriptsTab() { test.showPanel("scripts"); setTimeout(checkScriptsPanel, 0); } function checkScriptsPanel() { test.assertTrue(test._scriptsAreParsed(["debugger_test_page.html"]), "Some scripts are missing."); checkNoDuplicates(); test.releaseControl(); } function checkNoDuplicates() { var uiSourceCodes = test.nonAnonymousUISourceCodes_(); for (var i = 0; i < uiSourceCodes.length; i++) { var scriptName = uiSourceCodes[i].fileName; for (var j = i + 1; j < uiSourceCodes.length; j++) test.assertTrue(scriptName !== uiSourceCodes[j].fileName, "Found script duplicates: " + test.uiSourceCodesToString_(uiSourceCodes)); } } test._waitUntilScriptsAreParsed( ["debugger_test_page.html"], function() { checkNoDuplicates(); setTimeout(switchToElementsTab, 0); }); this.takeControl(); }; TestSuite.prototype.testPauseWhenLoadingDevTools = function() { this.showPanel("scripts"); if (WebInspector.debuggerModel.debuggerPausedDetails) return; this._waitForScriptPause(this.releaseControl.bind(this)); this.takeControl(); }; TestSuite.prototype.testPauseWhenScriptIsRunning = function() { this.showPanel("scripts"); this.evaluateInConsole_( 'setTimeout("handleClick()" , 0)', didEvaluateInConsole.bind(this)); function didEvaluateInConsole(resultText) { this.assertTrue(!isNaN(resultText), "Failed to get timer id: " + resultText); setTimeout(testScriptPause.bind(this), 300); } function testScriptPause() { WebInspector.panels.scripts.pauseButton.click(); this._waitForScriptPause(this.releaseControl.bind(this)); } this.takeControl(); }; TestSuite.prototype.testNetworkSize = function() { var test = this; function finishResource(resource, finishTime) { test.assertEquals(219, resource.transferSize, "Incorrect total encoded data length"); test.assertEquals(25, resource.resourceSize, "Incorrect total data length"); test.releaseControl(); } this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource); test.evaluateInConsole_("window.location.reload(true);", function(resultText) {}); this.takeControl(); }; TestSuite.prototype.testNetworkSyncSize = function() { var test = this; function finishResource(resource, finishTime) { test.assertEquals(219, resource.transferSize, "Incorrect total encoded data length"); test.assertEquals(25, resource.resourceSize, "Incorrect total data length"); test.releaseControl(); } this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource); test.evaluateInConsole_("var xhr = new XMLHttpRequest(); xhr.open(\"GET\", \"chunked\", false); xhr.send(null);", function() {}); this.takeControl(); }; TestSuite.prototype.testNetworkRawHeadersText = function() { var test = this; function finishResource(resource, finishTime) { if (!resource.responseHeadersText) test.fail("Failure: resource does not have response headers text"); test.assertEquals(164, resource.responseHeadersText.length, "Incorrect response headers text length"); test.releaseControl(); } this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource); test.evaluateInConsole_("window.location.reload(true);", function(resultText) {}); this.takeControl(); }; TestSuite.prototype.testNetworkTiming = function() { var test = this; function finishResource(resource, finishTime) { test.assertTrue(resource.timing.receiveHeadersEnd - resource.timing.connectStart >= 70, "Time between receiveHeadersEnd and connectStart should be >=70ms, but was " + "receiveHeadersEnd=" + resource.timing.receiveHeadersEnd + ", connectStart=" + resource.timing.connectStart + "."); test.assertTrue(resource.responseReceivedTime - resource.startTime >= 0.07, "Time between responseReceivedTime and startTime should be >=0.07s, but was " + "responseReceivedTime=" + resource.responseReceivedTime + ", startTime=" + resource.startTime + "."); test.assertTrue(resource.endTime - resource.startTime >= 0.14, "Time between endTime and startTime should be >=0.14s, but was " + "endtime=" + resource.endTime + ", startTime=" + resource.startTime + "."); test.releaseControl(); } this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource); test.evaluateInConsole_("window.location.reload(true);", function(resultText) {}); this.takeControl(); }; TestSuite.prototype.testConsoleOnNavigateBack = function() { if (WebInspector.console.messages.length === 1) firstConsoleMessageReceived.call(this); else WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); function firstConsoleMessageReceived() { this.evaluateInConsole_("clickLink();", didClickLink.bind(this)); } function didClickLink() { this.assertEquals(1, WebInspector.console.messages.length); this.assertEquals(1, WebInspector.console.messages[0].totalRepeatCount); this.evaluateInConsole_("history.back();", didNavigateBack.bind(this)); } function didNavigateBack() { this.evaluateInConsole_("void 0;", didCompleteNavigation.bind(this)); } function didCompleteNavigation() { this.assertEquals(1, WebInspector.console.messages.length); this.assertEquals(1, WebInspector.console.messages[0].totalRepeatCount); this.releaseControl(); } this.takeControl(); }; TestSuite.prototype.testReattachAfterCrash = function() { this.evaluateInConsole_("1+1;", this.releaseControl.bind(this)); this.takeControl(); }; TestSuite.prototype.testSharedWorker = function() { function didEvaluateInConsole(resultText) { this.assertEquals("2011", resultText); this.releaseControl(); } this.evaluateInConsole_("globalVar", didEvaluateInConsole.bind(this)); this.takeControl(); }; TestSuite.prototype.testPauseInSharedWorkerInitialization = function() { if (WebInspector.debuggerModel.debuggerPausedDetails) return; this._waitForScriptPause(this.releaseControl.bind(this)); this.takeControl(); }; TestSuite.prototype.testPageOverlayUpdate = function() { var test = this; var records = []; var dispatchOnRecordType = {} function addRecord(event) { innerAddRecord(event.data); } function innerAddRecord(record) { records.push(record); if (typeof dispatchOnRecordType[record.type] === "function") dispatchOnRecordType[record.type](record); if (record.children) record.children.forEach(innerAddRecord); } function populatePage() { var div1 = document.createElement("div"); div1.id = "div1"; div1.style.webkitTransform = "translateZ(0)"; document.body.appendChild(div1); var div2 = document.createElement("div"); div2.id = "div2"; document.body.appendChild(div2); } function step1() { WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, addRecord); WebInspector.timelineManager.start(); test.evaluateInConsole_(populatePage.toString() + "; populatePage();" + "inspect(document.getElementById('div1'))", function() {}); WebInspector.notifications.addEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, step2); } function step2() { WebInspector.notifications.removeEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, step2); setTimeout(step3, 500); } function step3() { test.evaluateInConsole_("inspect(document.getElementById('div2'))", function() {}); WebInspector.notifications.addEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, step4); } function step4() { WebInspector.notifications.removeEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, step4); dispatchOnRecordType.TimeStamp = step5; test.evaluateInConsole_("console.timeStamp('ready')", function() {}); } function step5() { var types = {}; WebInspector.timelineManager.stop(); WebInspector.timelineManager.removeEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, addRecord); for (var i = 0; i < records.length; ++i) types[records[i].type] = (types[records[i].type] || 0) + 1; var frameCount = types["BeginFrame"]; test.assertTrue(frameCount >= 2, "Not enough DevTools overlay updates"); test.assertTrue(frameCount < 6, "Too many updates caused by DevTools overlay"); test.releaseControl(); } step1(); this.takeControl(); } TestSuite.prototype.waitForTestResultsInConsole = function() { var messages = WebInspector.console.messages; for (var i = 0; i < messages.length; ++i) { var text = messages[i].text; if (text === "PASS") return; else if (/^FAIL/.test(text)) this.fail(text); } function onConsoleMessage(event) { var text = event.data.text; if (text === "PASS") this.releaseControl(); else if (/^FAIL/.test(text)) this.fail(text); } WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); this.takeControl(); }; TestSuite.prototype.checkLogAndErrorMessages = function() { var messages = WebInspector.console.messages; var matchesCount = 0; function validMessage(message) { if (message.text === "log" && message.level === WebInspector.ConsoleMessage.MessageLevel.Log) { ++matchesCount; return true; } if (message.text === "error" && message.level === WebInspector.ConsoleMessage.MessageLevel.Error) { ++matchesCount; return true; } return false; } for (var i = 0; i < messages.length; ++i) { if (validMessage(messages[i])) continue; this.fail(messages[i].text + ":" + messages[i].level); } if (matchesCount === 2) return; function onConsoleMessage(event) { var message = event.data; if (validMessage(message)) { if (matchesCount === 2) { this.releaseControl(); return; } } else this.fail(message.text + ":" + messages[i].level); } WebInspector.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); this.takeControl(); }; TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) { var names = []; for (var i = 0; i < uiSourceCodes.length; i++) names.push('"' + uiSourceCodes[i].fileName + '"'); return names.join(","); }; TestSuite.prototype.nonAnonymousUISourceCodes_ = function() { function filterOutAnonymous(uiSourceCode) { return !!uiSourceCode.url; } var uiSourceCodes = WebInspector.workspace.uiSourceCodes(); return uiSourceCodes.filter(filterOutAnonymous); }; TestSuite.prototype.evaluateInConsole_ = function(code, callback) { WebInspector.showConsole(); WebInspector.consoleView.prompt.text = code; WebInspector.consoleView.promptElement.dispatchEvent(TestSuite.createKeyEvent("Enter")); this.addSniffer(WebInspector.ConsoleView.prototype, "_appendConsoleMessage", function(commandResult) { callback(commandResult.toMessageElement().textContent); }); }; TestSuite.prototype._scriptsAreParsed = function(expected) { var uiSourceCodes = this.nonAnonymousUISourceCodes_(); var missing = expected.slice(0); for (var i = 0; i < uiSourceCodes.length; ++i) { for (var j = 0; j < missing.length; ++j) { if (uiSourceCodes[i].parsedURL.lastPathComponent.search(missing[j]) !== -1) { missing.splice(j, 1); break; } } } return missing.length === 0; }; TestSuite.prototype._waitForScriptPause = function(callback) { function pauseListener(event) { WebInspector.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, pauseListener, this); callback(); } WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, pauseListener, this); }; TestSuite.prototype._executeCodeWhenScriptsAreParsed = function(code, expectedScripts) { var test = this; function executeFunctionInInspectedPage() { test.evaluateInConsole_( 'setTimeout("' + code + '" , 0)', function(resultText) { test.assertTrue(!isNaN(resultText), "Failed to get timer id: " + resultText + ". Code: " + code); }); } test._waitUntilScriptsAreParsed(expectedScripts, executeFunctionInInspectedPage); }; TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) { var test = this; function waitForAllScripts() { if (test._scriptsAreParsed(expectedScripts)) callback(); else test.addSniffer(WebInspector.panels.scripts, "_addUISourceCode", waitForAllScripts); } waitForAllScripts(); }; TestSuite.createKeyEvent = function(keyIdentifier) { var evt = document.createEvent("KeyboardEvent"); evt.initKeyboardEvent("keydown", true , true , null , keyIdentifier, ""); return evt; }; var uiTests = {}; uiTests.runAllTests = function() { for (var name in TestSuite.prototype) { if (name.substring(0, 4) === "test" && typeof TestSuite.prototype[name] === "function") uiTests.runTest(name); } }; uiTests.runTest = function(name) { if (uiTests._populatedInterface) new TestSuite().runTest(name); else uiTests._pendingTestName = name; }; (function() { function runTests() { uiTests._populatedInterface = true; var name = uiTests._pendingTestName; delete uiTests._pendingTestName; if (name) new TestSuite().runTest(name); } var oldLoadCompleted = InspectorFrontendAPI.loadCompleted; InspectorFrontendAPI.loadCompleted = function() { oldLoadCompleted.call(InspectorFrontendAPI); runTests(); } })(); }
JavaScript
WebInspector.JavaScriptBreakpointsSidebarPane = function(breakpointManager, showSourceLineDelegate) { WebInspector.SidebarPane.call(this, WebInspector.UIString("Breakpoints")); this._breakpointManager = breakpointManager; this._showSourceLineDelegate = showSourceLineDelegate; this.listElement = document.createElement("ol"); this.listElement.className = "breakpoint-list"; this.emptyElement = document.createElement("div"); this.emptyElement.className = "info"; this.emptyElement.textContent = WebInspector.UIString("No Breakpoints"); this.bodyElement.appendChild(this.emptyElement); this._items = new Map(); var breakpointLocations = this._breakpointManager.allBreakpointLocations(); for (var i = 0; i < breakpointLocations.length; ++i) this._addBreakpoint(breakpointLocations[i].breakpoint, breakpointLocations[i].uiLocation); this._breakpointManager.addEventListener(WebInspector.BreakpointManager.Events.BreakpointAdded, this._breakpointAdded, this); this._breakpointManager.addEventListener(WebInspector.BreakpointManager.Events.BreakpointRemoved, this._breakpointRemoved, this); this.emptyElement.addEventListener("contextmenu", this._emptyElementContextMenu.bind(this), true); } WebInspector.JavaScriptBreakpointsSidebarPane.prototype = { _emptyElementContextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); var breakpointActive = WebInspector.debuggerModel.breakpointsActive(); var breakpointActiveTitle = WebInspector.UIString(breakpointActive ? "Deactivate Breakpoints" : "Activate Breakpoints"); contextMenu.appendItem(breakpointActiveTitle, WebInspector.debuggerModel.setBreakpointsActive.bind(WebInspector.debuggerModel, !breakpointActive)); contextMenu.show(); }, _breakpointAdded: function(event) { this._breakpointRemoved(event); var breakpoint = (event.data.breakpoint); var uiLocation = (event.data.uiLocation); this._addBreakpoint(breakpoint, uiLocation); }, _addBreakpoint: function(breakpoint, uiLocation) { var element = document.createElement("li"); element.addStyleClass("cursor-pointer"); element.addEventListener("contextmenu", this._breakpointContextMenu.bind(this, breakpoint), true); element.addEventListener("click", this._breakpointClicked.bind(this, uiLocation), false); var checkbox = document.createElement("input"); checkbox.className = "checkbox-elem"; checkbox.type = "checkbox"; checkbox.checked = breakpoint.enabled(); checkbox.addEventListener("click", this._breakpointCheckboxClicked.bind(this, breakpoint), false); element.appendChild(checkbox); var labelElement = document.createTextNode(WebInspector.formatLinkText(uiLocation.uiSourceCode.url, uiLocation.lineNumber)); element.appendChild(labelElement); var snippetElement = document.createElement("div"); snippetElement.className = "source-text monospace"; element.appendChild(snippetElement); function didRequestContent(content, contentEncoded, mimeType) { var lineEndings = content.lineEndings(); if (uiLocation.lineNumber < lineEndings.length) snippetElement.textContent = content.substring(lineEndings[uiLocation.lineNumber - 1], lineEndings[uiLocation.lineNumber]); } uiLocation.uiSourceCode.requestContent(didRequestContent.bind(this)); element._data = uiLocation; var currentElement = this.listElement.firstChild; while (currentElement) { if (currentElement._data && this._compareBreakpoints(currentElement._data, element._data) > 0) break; currentElement = currentElement.nextSibling; } this._addListElement(element, currentElement); var breakpointItem = {}; breakpointItem.element = element; breakpointItem.checkbox = checkbox; this._items.put(breakpoint, breakpointItem); if (!this.expanded) this.expanded = true; }, _breakpointRemoved: function(event) { var breakpoint = (event.data.breakpoint); var uiLocation = (event.data.uiLocation); var breakpointItem = this._items.get(breakpoint); if (!breakpointItem) return; this._items.remove(breakpoint); this._removeListElement(breakpointItem.element); }, highlightBreakpoint: function(breakpoint) { var breakpointItem = this._items.get(breakpoint); if (!breakpointItem) return; breakpointItem.element.addStyleClass("breakpoint-hit"); this._highlightedBreakpointItem = breakpointItem; }, clearBreakpointHighlight: function() { if (this._highlightedBreakpointItem) { this._highlightedBreakpointItem.element.removeStyleClass("breakpoint-hit"); delete this._highlightedBreakpointItem; } }, _breakpointClicked: function(uiLocation, event) { this._showSourceLineDelegate(uiLocation.uiSourceCode, uiLocation.lineNumber); }, _breakpointCheckboxClicked: function(breakpoint, event) { event.consume(); breakpoint.setEnabled(event.target.checked); }, _breakpointContextMenu: function(breakpoint, event) { var breakpoints = this._items.values(); var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Remove Breakpoint"), breakpoint.remove.bind(breakpoint)); if (breakpoints.length > 1) { var removeAllTitle = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Remove all breakpoints" : "Remove All Breakpoints"); contextMenu.appendItem(removeAllTitle, this._breakpointManager.removeAllBreakpoints.bind(this._breakpointManager)); } contextMenu.appendSeparator(); var breakpointActive = WebInspector.debuggerModel.breakpointsActive(); var breakpointActiveTitle = WebInspector.UIString(breakpointActive ? "Deactivate Breakpoints" : "Activate Breakpoints"); contextMenu.appendItem(breakpointActiveTitle, WebInspector.debuggerModel.setBreakpointsActive.bind(WebInspector.debuggerModel, !breakpointActive)); function enabledBreakpointCount(breakpoints) { var count = 0; for (var i = 0; i < breakpoints.length; ++i) { if (breakpoints[i].checkbox.checked) count++; } return count; } if (breakpoints.length > 1) { var enableBreakpointCount = enabledBreakpointCount(breakpoints); var enableTitle = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Enable all breakpoints" : "Enable All Breakpoints"); var disableTitle = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Disable all breakpoints" : "Disable All Breakpoints"); contextMenu.appendSeparator(); contextMenu.appendItem(enableTitle, this._breakpointManager.toggleAllBreakpoints.bind(this._breakpointManager, true), !(enableBreakpointCount != breakpoints.length)); contextMenu.appendItem(disableTitle, this._breakpointManager.toggleAllBreakpoints.bind(this._breakpointManager, false), !(enableBreakpointCount > 1)); } contextMenu.show(); }, _addListElement: function(element, beforeElement) { if (beforeElement) this.listElement.insertBefore(element, beforeElement); else { if (!this.listElement.firstChild) { this.bodyElement.removeChild(this.emptyElement); this.bodyElement.appendChild(this.listElement); } this.listElement.appendChild(element); } }, _removeListElement: function(element) { this.listElement.removeChild(element); if (!this.listElement.firstChild) { this.bodyElement.removeChild(this.listElement); this.bodyElement.appendChild(this.emptyElement); } }, _compare: function(x, y) { if (x !== y) return x < y ? -1 : 1; return 0; }, _compareBreakpoints: function(b1, b2) { return this._compare(b1.url, b2.url) || this._compare(b1.lineNumber, b2.lineNumber); }, reset: function() { this.listElement.removeChildren(); if (this.listElement.parentElement) { this.bodyElement.removeChild(this.listElement); this.bodyElement.appendChild(this.emptyElement); } this._items.clear(); }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.XHRBreakpointsSidebarPane = function() { WebInspector.NativeBreakpointsSidebarPane.call(this, WebInspector.UIString("XHR Breakpoints")); this._breakpointElements = {}; var addButton = document.createElement("button"); addButton.className = "pane-title-button add"; addButton.addEventListener("click", this._addButtonClicked.bind(this), false); addButton.title = WebInspector.UIString("Add XHR breakpoint"); this.titleElement.appendChild(addButton); this.emptyElement.addEventListener("contextmenu", this._emptyElementContextMenu.bind(this), true); this._restoreBreakpoints(); } WebInspector.XHRBreakpointsSidebarPane.prototype = { _emptyElementContextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Add Breakpoint"), this._addButtonClicked.bind(this)); contextMenu.show(); }, _addButtonClicked: function(event) { if (event) event.consume(); this.expanded = true; var inputElementContainer = document.createElement("p"); inputElementContainer.className = "breakpoint-condition"; var inputElement = document.createElement("span"); inputElementContainer.textContent = WebInspector.UIString("Break when URL contains:"); inputElement.className = "editing"; inputElement.id = "breakpoint-condition-input"; inputElementContainer.appendChild(inputElement); this._addListElement(inputElementContainer, this.listElement.firstChild); function finishEditing(accept, e, text) { this._removeListElement(inputElementContainer); if (accept) { this._setBreakpoint(text, true); this._saveBreakpoints(); } } var config = new WebInspector.EditingConfig(finishEditing.bind(this, true), finishEditing.bind(this, false)); WebInspector.startEditing(inputElement, config); }, _setBreakpoint: function(url, enabled) { if (url in this._breakpointElements) return; var element = document.createElement("li"); element._url = url; element.addEventListener("contextmenu", this._contextMenu.bind(this, url), true); var checkboxElement = document.createElement("input"); checkboxElement.className = "checkbox-elem"; checkboxElement.type = "checkbox"; checkboxElement.checked = enabled; checkboxElement.addEventListener("click", this._checkboxClicked.bind(this, url), false); element._checkboxElement = checkboxElement; element.appendChild(checkboxElement); var labelElement = document.createElement("span"); if (!url) labelElement.textContent = WebInspector.UIString("Any XHR"); else labelElement.textContent = WebInspector.UIString("URL contains \"%s\"", url); labelElement.addStyleClass("cursor-auto"); labelElement.addEventListener("dblclick", this._labelClicked.bind(this, url), false); element.appendChild(labelElement); var currentElement = this.listElement.firstChild; while (currentElement) { if (currentElement._url && currentElement._url < element._url) break; currentElement = currentElement.nextSibling; } this._addListElement(element, currentElement); this._breakpointElements[url] = element; if (enabled) DOMDebuggerAgent.setXHRBreakpoint(url); }, _removeBreakpoint: function(url) { var element = this._breakpointElements[url]; if (!element) return; this._removeListElement(element); delete this._breakpointElements[url]; if (element._checkboxElement.checked) DOMDebuggerAgent.removeXHRBreakpoint(url); }, _contextMenu: function(url, event) { var contextMenu = new WebInspector.ContextMenu(event); function removeBreakpoint() { this._removeBreakpoint(url); this._saveBreakpoints(); } function removeAllBreakpoints() { for (var url in this._breakpointElements) this._removeBreakpoint(url); this._saveBreakpoints(); } var removeAllTitle = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Remove all breakpoints" : "Remove All Breakpoints"); contextMenu.appendItem(WebInspector.UIString("Add Breakpoint"), this._addButtonClicked.bind(this)); contextMenu.appendItem(WebInspector.UIString("Remove Breakpoint"), removeBreakpoint.bind(this)); contextMenu.appendItem(removeAllTitle, removeAllBreakpoints.bind(this)); contextMenu.show(); }, _checkboxClicked: function(url, event) { if (event.target.checked) DOMDebuggerAgent.setXHRBreakpoint(url); else DOMDebuggerAgent.removeXHRBreakpoint(url); this._saveBreakpoints(); }, _labelClicked: function(url) { var element = this._breakpointElements[url]; var inputElement = document.createElement("span"); inputElement.className = "breakpoint-condition editing"; inputElement.textContent = url; this.listElement.insertBefore(inputElement, element); element.addStyleClass("hidden"); function finishEditing(accept, e, text) { this._removeListElement(inputElement); if (accept) { this._removeBreakpoint(url); this._setBreakpoint(text, element._checkboxElement.checked); this._saveBreakpoints(); } else element.removeStyleClass("hidden"); } WebInspector.startEditing(inputElement, new WebInspector.EditingConfig(finishEditing.bind(this, true), finishEditing.bind(this, false))); }, highlightBreakpoint: function(url) { var element = this._breakpointElements[url]; if (!element) return; this.expanded = true; element.addStyleClass("breakpoint-hit"); this._highlightedElement = element; }, clearBreakpointHighlight: function() { if (this._highlightedElement) { this._highlightedElement.removeStyleClass("breakpoint-hit"); delete this._highlightedElement; } }, _saveBreakpoints: function() { var breakpoints = []; for (var url in this._breakpointElements) breakpoints.push({ url: url, enabled: this._breakpointElements[url]._checkboxElement.checked }); WebInspector.settings.xhrBreakpoints.set(breakpoints); }, _restoreBreakpoints: function() { var breakpoints = WebInspector.settings.xhrBreakpoints.get(); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; if (breakpoint && typeof breakpoint.url === "string") this._setBreakpoint(breakpoint.url, breakpoint.enabled); } }, __proto__: WebInspector.NativeBreakpointsSidebarPane.prototype } WebInspector.EventListenerBreakpointsSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Event Listener Breakpoints")); this.categoriesElement = document.createElement("ol"); this.categoriesElement.tabIndex = 0; this.categoriesElement.addStyleClass("properties-tree"); this.categoriesElement.addStyleClass("event-listener-breakpoints"); this.categoriesTreeOutline = new TreeOutline(this.categoriesElement); this.bodyElement.appendChild(this.categoriesElement); this._breakpointItems = {}; this._createCategory(WebInspector.UIString("Animation"), false, ["requestAnimationFrame", "cancelAnimationFrame", "animationFrameFired"]); this._createCategory(WebInspector.UIString("Control"), true, ["resize", "scroll", "zoom", "focus", "blur", "select", "change", "submit", "reset"]); this._createCategory(WebInspector.UIString("Clipboard"), true, ["copy", "cut", "paste", "beforecopy", "beforecut", "beforepaste"]); this._createCategory(WebInspector.UIString("DOM Mutation"), true, ["DOMActivate", "DOMFocusIn", "DOMFocusOut", "DOMAttrModified", "DOMCharacterDataModified", "DOMNodeInserted", "DOMNodeInsertedIntoDocument", "DOMNodeRemoved", "DOMNodeRemovedFromDocument", "DOMSubtreeModified", "DOMContentLoaded"]); this._createCategory(WebInspector.UIString("Device"), true, ["deviceorientation", "devicemotion"]); this._createCategory(WebInspector.UIString("Keyboard"), true, ["keydown", "keyup", "keypress", "input"]); this._createCategory(WebInspector.UIString("Load"), true, ["load", "unload", "abort", "error"]); this._createCategory(WebInspector.UIString("Mouse"), true, ["click", "dblclick", "mousedown", "mouseup", "mouseover", "mousemove", "mouseout", "mousewheel"]); this._createCategory(WebInspector.UIString("Timer"), false, ["setTimer", "clearTimer", "timerFired"]); this._createCategory(WebInspector.UIString("Touch"), true, ["touchstart", "touchmove", "touchend", "touchcancel"]); this._restoreBreakpoints(); } WebInspector.EventListenerBreakpointsSidebarPane.categotyListener = "listener:"; WebInspector.EventListenerBreakpointsSidebarPane.categotyInstrumentation = "instrumentation:"; WebInspector.EventListenerBreakpointsSidebarPane.eventNameForUI = function(eventName) { if (!WebInspector.EventListenerBreakpointsSidebarPane._eventNamesForUI) { WebInspector.EventListenerBreakpointsSidebarPane._eventNamesForUI = { "instrumentation:setTimer": WebInspector.UIString("Set Timer"), "instrumentation:clearTimer": WebInspector.UIString("Clear Timer"), "instrumentation:timerFired": WebInspector.UIString("Timer Fired"), "instrumentation:requestAnimationFrame": WebInspector.UIString("Request Animation Frame"), "instrumentation:cancelAnimationFrame": WebInspector.UIString("Cancel Animation Frame"), "instrumentation:animationFrameFired": WebInspector.UIString("Animation Frame Fired") }; } return WebInspector.EventListenerBreakpointsSidebarPane._eventNamesForUI[eventName] || eventName.substring(eventName.indexOf(":") + 1); } WebInspector.EventListenerBreakpointsSidebarPane.prototype = { _createCategory: function(name, isDOMEvent, eventNames) { var categoryItem = {}; categoryItem.element = new TreeElement(name); this.categoriesTreeOutline.appendChild(categoryItem.element); categoryItem.element.listItemElement.addStyleClass("event-category"); categoryItem.element.selectable = true; categoryItem.checkbox = this._createCheckbox(categoryItem.element); categoryItem.checkbox.addEventListener("click", this._categoryCheckboxClicked.bind(this, categoryItem), true); categoryItem.children = {}; for (var i = 0; i < eventNames.length; ++i) { var eventName = (isDOMEvent ? WebInspector.EventListenerBreakpointsSidebarPane.categotyListener : WebInspector.EventListenerBreakpointsSidebarPane.categotyInstrumentation) + eventNames[i]; var breakpointItem = {}; var title = WebInspector.EventListenerBreakpointsSidebarPane.eventNameForUI(eventName); breakpointItem.element = new TreeElement(title); categoryItem.element.appendChild(breakpointItem.element); var hitMarker = document.createElement("div"); hitMarker.className = "breakpoint-hit-marker"; breakpointItem.element.listItemElement.appendChild(hitMarker); breakpointItem.element.listItemElement.addStyleClass("source-code"); breakpointItem.element.selectable = true; breakpointItem.checkbox = this._createCheckbox(breakpointItem.element); breakpointItem.checkbox.addEventListener("click", this._breakpointCheckboxClicked.bind(this, eventName), true); breakpointItem.parent = categoryItem; this._breakpointItems[eventName] = breakpointItem; categoryItem.children[eventName] = breakpointItem; } }, _createCheckbox: function(treeElement) { var checkbox = document.createElement("input"); checkbox.className = "checkbox-elem"; checkbox.type = "checkbox"; treeElement.listItemElement.insertBefore(checkbox, treeElement.listItemElement.firstChild); return checkbox; }, _categoryCheckboxClicked: function(categoryItem) { var checked = categoryItem.checkbox.checked; for (var eventName in categoryItem.children) { var breakpointItem = categoryItem.children[eventName]; if (breakpointItem.checkbox.checked === checked) continue; if (checked) this._setBreakpoint(eventName); else this._removeBreakpoint(eventName); } this._saveBreakpoints(); }, _breakpointCheckboxClicked: function(eventName, event) { if (event.target.checked) this._setBreakpoint(eventName); else this._removeBreakpoint(eventName); this._saveBreakpoints(); }, _setBreakpoint: function(eventName) { var breakpointItem = this._breakpointItems[eventName]; if (!breakpointItem) return; breakpointItem.checkbox.checked = true; if (eventName.startsWith(WebInspector.EventListenerBreakpointsSidebarPane.categotyListener)) DOMDebuggerAgent.setEventListenerBreakpoint(eventName.substring(WebInspector.EventListenerBreakpointsSidebarPane.categotyListener.length)); else if (eventName.startsWith(WebInspector.EventListenerBreakpointsSidebarPane.categotyInstrumentation)) DOMDebuggerAgent.setInstrumentationBreakpoint(eventName.substring(WebInspector.EventListenerBreakpointsSidebarPane.categotyInstrumentation.length)); this._updateCategoryCheckbox(breakpointItem.parent); }, _removeBreakpoint: function(eventName) { var breakpointItem = this._breakpointItems[eventName]; if (!breakpointItem) return; breakpointItem.checkbox.checked = false; if (eventName.startsWith(WebInspector.EventListenerBreakpointsSidebarPane.categotyListener)) DOMDebuggerAgent.removeEventListenerBreakpoint(eventName.substring(WebInspector.EventListenerBreakpointsSidebarPane.categotyListener.length)); else if (eventName.startsWith(WebInspector.EventListenerBreakpointsSidebarPane.categotyInstrumentation)) DOMDebuggerAgent.removeInstrumentationBreakpoint(eventName.substring(WebInspector.EventListenerBreakpointsSidebarPane.categotyInstrumentation.length)); this._updateCategoryCheckbox(breakpointItem.parent); }, _updateCategoryCheckbox: function(categoryItem) { var hasEnabled = false, hasDisabled = false; for (var eventName in categoryItem.children) { var breakpointItem = categoryItem.children[eventName]; if (breakpointItem.checkbox.checked) hasEnabled = true; else hasDisabled = true; } categoryItem.checkbox.checked = hasEnabled; categoryItem.checkbox.indeterminate = hasEnabled && hasDisabled; }, highlightBreakpoint: function(eventName) { var breakpointItem = this._breakpointItems[eventName]; if (!breakpointItem) return; this.expanded = true; breakpointItem.parent.element.expand(); breakpointItem.element.listItemElement.addStyleClass("breakpoint-hit"); this._highlightedElement = breakpointItem.element.listItemElement; }, clearBreakpointHighlight: function() { if (this._highlightedElement) { this._highlightedElement.removeStyleClass("breakpoint-hit"); delete this._highlightedElement; } }, _saveBreakpoints: function() { var breakpoints = []; for (var eventName in this._breakpointItems) { if (this._breakpointItems[eventName].checkbox.checked) breakpoints.push({ eventName: eventName }); } WebInspector.settings.eventListenerBreakpoints.set(breakpoints); }, _restoreBreakpoints: function() { var breakpoints = WebInspector.settings.eventListenerBreakpoints.get(); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; if (breakpoint && typeof breakpoint.eventName === "string") this._setBreakpoint(breakpoint.eventName); } }, __proto__: WebInspector.SidebarPane.prototype } ; WebInspector.CallStackSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Call Stack")); this._model = WebInspector.debuggerModel; this.bodyElement.addEventListener("keydown", this._keyDown.bind(this), true); this.bodyElement.tabIndex = 0; } WebInspector.CallStackSidebarPane.prototype = { update: function(callFrames) { this.bodyElement.removeChildren(); this.placards = []; if (!callFrames) { var infoElement = document.createElement("div"); infoElement.className = "info"; infoElement.textContent = WebInspector.UIString("Not Paused"); this.bodyElement.appendChild(infoElement); return; } for (var i = 0; i < callFrames.length; ++i) { var callFrame = callFrames[i]; var placard = new WebInspector.CallStackSidebarPane.Placard(callFrame, this); placard.element.addEventListener("click", this._placardSelected.bind(this, placard), false); this.placards.push(placard); this.bodyElement.appendChild(placard.element); } }, setSelectedCallFrame: function(x) { for (var i = 0; i < this.placards.length; ++i) { var placard = this.placards[i]; placard.selected = (placard._callFrame === x); } }, _selectNextCallFrameOnStack: function() { var index = this._selectedCallFrameIndex(); if (index == -1) return; this._selectedPlacardByIndex(index + 1); }, _selectPreviousCallFrameOnStack: function() { var index = this._selectedCallFrameIndex(); if (index == -1) return; this._selectedPlacardByIndex(index - 1); }, _selectedPlacardByIndex: function(index) { if (index < 0 || index >= this.placards.length) return; this._placardSelected(this.placards[index]) }, _selectedCallFrameIndex: function() { if (!this._model.selectedCallFrame()) return -1; for (var i = 0; i < this.placards.length; ++i) { var placard = this.placards[i]; if (placard._callFrame === this._model.selectedCallFrame()) return i; } return -1; }, _placardSelected: function(placard) { this._model.setSelectedCallFrame(placard._callFrame); }, _copyStackTrace: function() { var text = ""; for (var i = 0; i < this.placards.length; ++i) text += this.placards[i].title + " (" + this.placards[i].subtitle + ")\n"; InspectorFrontendHost.copyText(text); }, registerShortcuts: function(registerShortcutDelegate) { registerShortcutDelegate(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.NextCallFrame, this._selectNextCallFrameOnStack.bind(this)); registerShortcutDelegate(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.PrevCallFrame, this._selectPreviousCallFrameOnStack.bind(this)); }, setStatus: function(status) { if (!this._statusMessageElement) { this._statusMessageElement = document.createElement("div"); this._statusMessageElement.className = "info"; this.bodyElement.appendChild(this._statusMessageElement); } if (typeof status === "string") this._statusMessageElement.textContent = status; else { this._statusMessageElement.removeChildren(); this._statusMessageElement.appendChild(status); } }, _keyDown: function(event) { if (event.altKey || event.shiftKey || event.metaKey || event.ctrlKey) return; if (event.keyIdentifier === "Up") { this._selectPreviousCallFrameOnStack(); event.consume(); } else if (event.keyIdentifier === "Down") { this._selectNextCallFrameOnStack(); event.consume(); } }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.CallStackSidebarPane.Placard = function(callFrame, pane) { WebInspector.Placard.call(this, callFrame.functionName || WebInspector.UIString("(anonymous function)"), ""); callFrame.createLiveLocation(this._update.bind(this)); this.element.addEventListener("contextmenu", this._placardContextMenu.bind(this), true); this._callFrame = callFrame; this._pane = pane; } WebInspector.CallStackSidebarPane.Placard.prototype = { _update: function(uiLocation) { this.subtitle = WebInspector.formatLinkText(uiLocation.uiSourceCode.url, uiLocation.lineNumber).trimMiddle(100); }, _placardContextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); if (WebInspector.debuggerModel.canSetScriptSource()) { contextMenu.appendItem(WebInspector.UIString("Restart Frame"), this._restartFrame.bind(this)); contextMenu.appendSeparator(); } contextMenu.appendItem(WebInspector.UIString("Copy Stack Trace"), this._pane._copyStackTrace.bind(this._pane)); contextMenu.show(); }, _restartFrame: function() { this._callFrame.restart(undefined); }, __proto__: WebInspector.Placard.prototype } ; WebInspector.FilteredItemSelectionDialog = function(delegate) { WebInspector.DialogDelegate.call(this); var xhr = new XMLHttpRequest(); xhr.open("GET", "filteredItemSelectionDialog.css", false); xhr.send(null); this.element = document.createElement("div"); this.element.className = "js-outline-dialog"; this.element.addEventListener("keydown", this._onKeyDown.bind(this), false); this.element.addEventListener("mousemove", this._onMouseMove.bind(this), false); this.element.addEventListener("click", this._onClick.bind(this), false); var styleElement = this.element.createChild("style"); styleElement.type = "text/css"; styleElement.textContent = xhr.responseText; this._itemElements = []; this._elementIndexes = new Map(); this._elementHighlightChanges = new Map(); this._promptElement = this.element.createChild("input", "monospace"); this._promptElement.type = "text"; this._promptElement.setAttribute("spellcheck", "false"); this._progressElement = this.element.createChild("div", "progress"); this._itemElementsContainer = document.createElement("div"); this._itemElementsContainer.className = "container monospace"; this._itemElementsContainer.addEventListener("scroll", this._onScroll.bind(this), false); this.element.appendChild(this._itemElementsContainer); this._delegate = delegate; this._delegate.requestItems(this._itemsLoaded.bind(this)); } WebInspector.FilteredItemSelectionDialog.prototype = { position: function(element, relativeToElement) { const minWidth = 500; const minHeight = 204; var width = Math.max(relativeToElement.offsetWidth * 2 / 3, minWidth); var height = Math.max(relativeToElement.offsetHeight * 2 / 3, minHeight); this.element.style.width = width + "px"; this.element.style.height = height + "px"; const shadowPadding = 20; element.positionAt( relativeToElement.totalOffsetLeft() + Math.max((relativeToElement.offsetWidth - width - 2 * shadowPadding) / 2, shadowPadding), relativeToElement.totalOffsetTop() + Math.max((relativeToElement.offsetHeight - height - 2 * shadowPadding) / 2, shadowPadding)); }, focus: function() { WebInspector.setCurrentFocusElement(this._promptElement); }, willHide: function() { if (this._isHiding) return; this._isHiding = true; if (this._filterTimer) clearTimeout(this._filterTimer); }, onEnter: function() { if (!this._selectedElement) return; this._delegate.selectItem(this._elementIndexes.get(this._selectedElement), this._promptElement.value.trim()); }, _itemsLoaded: function(index, chunkLength, chunkIndex, chunkCount) { for (var i = index; i < index + chunkLength; ++i) this._itemElementsContainer.appendChild(this._createItemElement(i)); this._filterItems(); if (chunkIndex === chunkCount) this._progressElement.style.backgroundImage = ""; else { const color = "rgb(66, 129, 235)"; const percent = ((chunkIndex / chunkCount) * 100) + "%"; this._progressElement.style.backgroundImage = "-webkit-linear-gradient(left, " + color + ", " + color + " " + percent + ", transparent " + percent + ")"; } }, _createItemElement: function(index) { if (this._itemElements[index]) return this._itemElements[index]; var itemElement = document.createElement("div"); itemElement.className = "item"; itemElement._titleElement = itemElement.createChild("span"); itemElement._titleElement.textContent = this._delegate.itemTitleAt(index); itemElement._titleSuffixElement = itemElement.createChild("span"); itemElement._subtitleElement = itemElement.createChild("span", "subtitle"); itemElement._subtitleElement.textContent = this._delegate.itemSubtitleAt(index); this._elementIndexes.put(itemElement, index); this._itemElements.push(itemElement); return itemElement; }, _hideItemElement: function(itemElement) { itemElement.style.display = "none"; }, _itemElementVisible: function(itemElement) { return itemElement.style.display !== "none"; }, _showItemElement: function(itemElement) { itemElement.style.display = ""; }, _createSearchRegExp: function(query, isGlobal) { return this._innerCreateSearchRegExp(this._delegate.rewriteQuery(query), isGlobal); }, _innerCreateSearchRegExp: function(query, isGlobal) { if (!query) return new RegExp(".*"); query = query.trim(); var ignoreCase = (query === query.toLowerCase()); var regExpString = query.escapeForRegExp().replace(/\\\*/g, ".*").replace(/\\\?/g, ".") if (ignoreCase) regExpString = regExpString.replace(/(?!^)(\\\.|[_:-])/g, "[^._:-]*$1"); else regExpString = regExpString.replace(/(?!^)(\\\.|[A-Z_:-])/g, "[^.A-Z_:-]*$1"); regExpString = regExpString; return new RegExp(regExpString, (ignoreCase ? "i" : "") + (isGlobal ? "g" : "")); }, _filterItems: function() { delete this._filterTimer; var query = this._promptElement.value; query = query.trim(); var regex = this._createSearchRegExp(query); var firstElement; for (var i = 0; i < this._itemElements.length; ++i) { var itemElement = this._itemElements[i]; itemElement._titleSuffixElement.textContent = this._delegate.itemSuffixAt(i); if (regex.test(this._delegate.itemKeyAt(i))) { this._showItemElement(itemElement); if (!firstElement) firstElement = itemElement; } else this._hideItemElement(itemElement); } if (!this._selectedElement || !this._itemElementVisible(this._selectedElement)) this._updateSelection(firstElement); if (query) { this._highlightItems(query); this._query = query; } else { this._clearHighlight(); delete this._query; } }, _onKeyDown: function(event) { function nextItem(itemElement, isPageScroll, forward) { var scrollItemsLeft = isPageScroll && this._rowsPerViewport ? this._rowsPerViewport : 1; var candidate = itemElement; var lastVisibleCandidate = candidate; do { candidate = forward ? candidate.nextSibling : candidate.previousSibling; if (!candidate) { if (isPageScroll) return lastVisibleCandidate; else candidate = forward ? this._itemElementsContainer.firstChild : this._itemElementsContainer.lastChild; } if (!this._itemElementVisible(candidate)) continue; lastVisibleCandidate = candidate; --scrollItemsLeft; } while (scrollItemsLeft && candidate !== this._selectedElement); return candidate; } if (this._selectedElement) { var candidate; switch (event.keyCode) { case WebInspector.KeyboardShortcut.Keys.Down.code: candidate = nextItem.call(this, this._selectedElement, false, true); break; case WebInspector.KeyboardShortcut.Keys.Up.code: candidate = nextItem.call(this, this._selectedElement, false, false); break; case WebInspector.KeyboardShortcut.Keys.PageDown.code: candidate = nextItem.call(this, this._selectedElement, true, true); break; case WebInspector.KeyboardShortcut.Keys.PageUp.code: candidate = nextItem.call(this, this._selectedElement, true, false); break; } if (candidate) { this._updateSelection(candidate); event.preventDefault(); return; } } if (event.keyIdentifier !== "Shift" && event.keyIdentifier !== "Ctrl" && event.keyIdentifier !== "Meta" && event.keyIdentifier !== "Left" && event.keyIdentifier !== "Right") this._scheduleFilter(); }, _scheduleFilter: function() { if (this._filterTimer) return; this._filterTimer = setTimeout(this._filterItems.bind(this), 0); }, _updateSelection: function(newSelectedElement) { if (this._selectedElement === newSelectedElement) return; if (this._selectedElement) this._selectedElement.removeStyleClass("selected"); this._selectedElement = newSelectedElement; if (newSelectedElement) { newSelectedElement.addStyleClass("selected"); newSelectedElement.scrollIntoViewIfNeeded(false); if (!this._itemHeight) { this._itemHeight = newSelectedElement.offsetHeight; this._rowsPerViewport = Math.floor(this._itemElementsContainer.offsetHeight / this._itemHeight); } } }, _onClick: function(event) { var itemElement = event.target.enclosingNodeOrSelfWithClass("item"); if (!itemElement) return; this._updateSelection(itemElement); this._delegate.selectItem(this._elementIndexes.get(this._selectedElement), this._promptElement.value.trim()); WebInspector.Dialog.hide(); }, _onMouseMove: function(event) { var itemElement = event.target.enclosingNodeOrSelfWithClass("item"); if (!itemElement) return; this._updateSelection(itemElement); }, _onScroll: function() { if (this._query) this._highlightItems(this._query); else this._clearHighlight(); }, _highlightItems: function(query) { var regex = this._createSearchRegExp(query, true); for (var i = 0; i < this._delegate.itemsCount(); ++i) { var itemElement = this._itemElements[i]; if (this._itemElementVisible(itemElement) && this._itemElementInViewport(itemElement)) this._highlightItem(itemElement, regex); } }, _clearHighlight: function() { for (var i = 0; i < this._delegate.itemsCount(); ++i) this._clearElementHighlight(this._itemElements[i]); }, _clearElementHighlight: function(itemElement) { var changes = this._elementHighlightChanges.get(itemElement) if (changes) { WebInspector.revertDomChanges(changes); this._elementHighlightChanges.remove(itemElement); } }, _highlightItem: function(itemElement, regex) { this._clearElementHighlight(itemElement); var key = this._delegate.itemKeyAt(this._elementIndexes.get(itemElement)); var ranges = []; var match; while ((match = regex.exec(key)) !== null && match[0]) { ranges.push({ offset: match.index, length: regex.lastIndex - match.index }); } var changes = []; WebInspector.highlightRangesWithStyleClass(itemElement, ranges, "highlight", changes); if (changes.length) this._elementHighlightChanges.put(itemElement, changes); }, _itemElementInViewport: function(itemElement) { if (itemElement.offsetTop + this._itemHeight < this._itemElementsContainer.scrollTop) return false; if (itemElement.offsetTop > this._itemElementsContainer.scrollTop + this._itemHeight * (this._rowsPerViewport + 1)) return false; return true; }, __proto__: WebInspector.DialogDelegate.prototype } WebInspector.SelectionDialogContentProvider = function() { } WebInspector.SelectionDialogContentProvider.prototype = { itemTitleAt: function(itemIndex) { }, itemSuffixAt: function(itemIndex) { }, itemSubtitleAt: function(itemIndex) { }, itemKeyAt: function(itemIndex) { }, itemsCount: function() { }, requestItems: function(callback) { }, selectItem: function(itemIndex, promptValue) { }, rewriteQuery: function(query) { }, } WebInspector.JavaScriptOutlineDialog = function(view, contentProvider) { WebInspector.SelectionDialogContentProvider.call(this); this._functionItems = []; this._view = view; this._contentProvider = contentProvider; } WebInspector.JavaScriptOutlineDialog.show = function(view, contentProvider) { if (WebInspector.Dialog.currentInstance()) return null; var delegate = new WebInspector.JavaScriptOutlineDialog(view, contentProvider); var filteredItemSelectionDialog = new WebInspector.FilteredItemSelectionDialog(delegate); WebInspector.Dialog.show(view.element, filteredItemSelectionDialog); } WebInspector.JavaScriptOutlineDialog.prototype = { itemTitleAt: function(itemIndex) { var functionItem = this._functionItems[itemIndex]; return functionItem.name + (functionItem.arguments ? functionItem.arguments : ""); }, itemSuffixAt: function(itemIndex) { return ""; }, itemSubtitleAt: function(itemIndex) { return ":" + (this._functionItems[itemIndex].line + 1); }, itemKeyAt: function(itemIndex) { return this._functionItems[itemIndex].name; }, itemsCount: function() { return this._functionItems.length; }, requestItems: function(callback) { function contentCallback(content, contentEncoded, mimeType) { if (this._outlineWorker) this._outlineWorker.terminate(); this._outlineWorker = new Worker("ScriptFormatterWorker.js"); this._outlineWorker.onmessage = this._didBuildOutlineChunk.bind(this, callback); const method = "outline"; this._outlineWorker.postMessage({ method: method, params: { content: content } }); } this._contentProvider.requestContent(contentCallback.bind(this)); }, _didBuildOutlineChunk: function(callback, event) { var data = event.data; var index = this._functionItems.length; var chunk = data["chunk"]; for (var i = 0; i < chunk.length; ++i) this._functionItems.push(chunk[i]); callback(index, chunk.length, data.index, data.total); if (data.total === data.index && this._outlineWorker) { this._outlineWorker.terminate(); delete this._outlineWorker; } }, selectItem: function(itemIndex, promptValue) { var lineNumber = this._functionItems[itemIndex].line; if (!isNaN(lineNumber) && lineNumber >= 0) this._view.highlightLine(lineNumber); this._view.focus(); }, rewriteQuery: function(query) { return query; }, __proto__: WebInspector.SelectionDialogContentProvider.prototype } WebInspector.OpenResourceDialog = function(panel, uiSourceCodeProvider) { WebInspector.SelectionDialogContentProvider.call(this); this._panel = panel; this._uiSourceCodes = uiSourceCodeProvider.uiSourceCodes(); function filterOutEmptyURLs(uiSourceCode) { return !!uiSourceCode.parsedURL.lastPathComponent; } this._uiSourceCodes = this._uiSourceCodes.filter(filterOutEmptyURLs); function compareFunction(uiSourceCode1, uiSourceCode2) { return uiSourceCode1.parsedURL.lastPathComponent.localeCompare(uiSourceCode2.parsedURL.lastPathComponent); } this._uiSourceCodes.sort(compareFunction); } WebInspector.OpenResourceDialog.prototype = { itemTitleAt: function(itemIndex) { return this._uiSourceCodes[itemIndex].parsedURL.lastPathComponent; }, itemSuffixAt: function(itemIndex) { return this._queryLineNumber || ""; }, itemSubtitleAt: function(itemIndex) { return this._uiSourceCodes[itemIndex].parsedURL.folderPathComponents; }, itemKeyAt: function(itemIndex) { return this._uiSourceCodes[itemIndex].parsedURL.lastPathComponent; }, itemsCount: function() { return this._uiSourceCodes.length; }, requestItems: function(callback) { callback(0, this._uiSourceCodes.length, 1, 1); }, selectItem: function(itemIndex, promptValue) { var lineNumberMatch = promptValue.match(/[^:]+\:([\d]*)$/); var lineNumber = lineNumberMatch ? Math.max(parseInt(lineNumberMatch[1], 10) - 1, 0) : 0; this._panel.showUISourceCode(this._uiSourceCodes[itemIndex], lineNumber); }, rewriteQuery: function(query) { if (!query) return query; query = query.trim(); var lineNumberMatch = query.match(/([^:]+)(\:[\d]*)$/); this._queryLineNumber = lineNumberMatch ? lineNumberMatch[2] : ""; return lineNumberMatch ? lineNumberMatch[1] : query; }, __proto__: WebInspector.SelectionDialogContentProvider.prototype } WebInspector.OpenResourceDialog.show = function(panel, uiSourceCodeProvider, relativeToElement) { if (WebInspector.Dialog.currentInstance()) return; var filteredItemSelectionDialog = new WebInspector.FilteredItemSelectionDialog(new WebInspector.OpenResourceDialog(panel, uiSourceCodeProvider)); WebInspector.Dialog.show(relativeToElement, filteredItemSelectionDialog); } ; WebInspector.JavaScriptSourceFrame = function(scriptsPanel, uiSourceCode) { this._scriptsPanel = scriptsPanel; this._breakpointManager = WebInspector.breakpointManager; this._uiSourceCode = uiSourceCode; var locations = this._breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode); for (var i = 0; i < locations.length; ++i) this._breakpointAdded({data:locations[i]}); WebInspector.SourceFrame.call(this, uiSourceCode); this._popoverHelper = new WebInspector.ObjectPopoverHelper(this.textEditor.element, this._getPopoverAnchor.bind(this), this._resolveObjectForPopover.bind(this), this._onHidePopover.bind(this), true); this.textEditor.element.addEventListener("keydown", this._onKeyDown.bind(this), true); this.textEditor.addEventListener(WebInspector.TextEditor.Events.GutterClick, this._handleGutterClick.bind(this), this); this._breakpointManager.addEventListener(WebInspector.BreakpointManager.Events.BreakpointAdded, this._breakpointAdded, this); this._breakpointManager.addEventListener(WebInspector.BreakpointManager.Events.BreakpointRemoved, this._breakpointRemoved, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._onFormattedChanged, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._onWorkingCopyChanged, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._onWorkingCopyCommitted, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.ConsoleMessageAdded, this._consoleMessageAdded, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.ConsoleMessageRemoved, this._consoleMessageRemoved, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.ConsoleMessagesCleared, this._consoleMessagesCleared, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.SourceMappingChanged, this._onSourceMappingChanged, this); this._updateScriptFile(); } WebInspector.JavaScriptSourceFrame.prototype = { wasShown: function() { WebInspector.SourceFrame.prototype.wasShown.call(this); }, willHide: function() { WebInspector.SourceFrame.prototype.willHide.call(this); this._popoverHelper.hidePopover(); }, canEditSource: function() { return this._uiSourceCode.isEditable(); }, commitEditing: function(text) { if (!this._uiSourceCode.isDirty()) return; this._isCommittingEditing = true; this._uiSourceCode.commitWorkingCopy(function() { }); delete this._isCommittingEditing; }, _onFormattedChanged: function(event) { var content = (event.data.content); this._textEditor.setReadOnly(this._uiSourceCode.formatted()); this.setContent(content, false, this._uiSourceCode.mimeType()); }, _onWorkingCopyChanged: function(event) { this._innerSetContent(this._uiSourceCode.workingCopy()); }, _onWorkingCopyCommitted: function(event) { this._innerSetContent(this._uiSourceCode.workingCopy()); }, _innerSetContent: function(content) { if (this._isSettingWorkingCopy || this._isCommittingEditing) return; var breakpointLocations = this._breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode); for (var i = 0; i < breakpointLocations.length; ++i) breakpointLocations[i].breakpoint.remove(); this.setContent(content, false, this._uiSourceCode.mimeType()); }, populateLineGutterContextMenu: function(contextMenu, lineNumber) { contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Continue to here" : "Continue to Here"), this._continueToLine.bind(this, lineNumber)); var breakpoint = this._breakpointManager.findBreakpoint(this._uiSourceCode, lineNumber); if (!breakpoint) { contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Add breakpoint" : "Add Breakpoint"), this._setBreakpoint.bind(this, lineNumber, "", true)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Add conditional breakpoint…" : "Add Conditional Breakpoint…"), this._editBreakpointCondition.bind(this, lineNumber)); } else { contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Remove breakpoint" : "Remove Breakpoint"), breakpoint.remove.bind(breakpoint)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Edit breakpoint…" : "Edit Breakpoint…"), this._editBreakpointCondition.bind(this, lineNumber, breakpoint)); if (breakpoint.enabled()) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Disable breakpoint" : "Disable Breakpoint"), breakpoint.setEnabled.bind(breakpoint, false)); else contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Enable breakpoint" : "Enable Breakpoint"), breakpoint.setEnabled.bind(breakpoint, true)); } }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { WebInspector.SourceFrame.prototype.populateTextAreaContextMenu.call(this, contextMenu, lineNumber); var selection = window.getSelection(); if (selection.type === "Range" && !selection.isCollapsed) { var addToWatchLabel = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Add to watch" : "Add to Watch"); contextMenu.appendItem(addToWatchLabel, this._scriptsPanel.addToWatch.bind(this._scriptsPanel, selection.toString())); var evaluateLabel = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Evaluate in console" : "Evaluate in Console"); contextMenu.appendItem(evaluateLabel, WebInspector.evaluateInConsole.bind(WebInspector, selection.toString())); contextMenu.appendSeparator(); } contextMenu.appendApplicableItems(this._uiSourceCode); }, onTextChanged: function(oldRange, newRange) { WebInspector.SourceFrame.prototype.onTextChanged.call(this, oldRange, newRange); this._isSettingWorkingCopy = true; this._uiSourceCode.setWorkingCopy(this._textEditor.text()); delete this._isSettingWorkingCopy; }, _willMergeToVM: function() { if (this._supportsEnabledBreakpointsWhileEditing()) return; this._preserveDecorations = true; }, _didMergeToVM: function() { if (this._supportsEnabledBreakpointsWhileEditing()) return; delete this._preserveDecorations; this._restoreBreakpointsAfterEditing(); }, _willDivergeFromVM: function() { if (this._supportsEnabledBreakpointsWhileEditing()) return; this._preserveDecorations = true; }, _didDivergeFromVM: function() { if (this._supportsEnabledBreakpointsWhileEditing()) return; delete this._preserveDecorations; this._muteBreakpointsWhileEditing(); }, _muteBreakpointsWhileEditing: function() { for (var lineNumber = 0; lineNumber < this._textEditor.linesCount; ++lineNumber) { var breakpointDecoration = this._textEditor.getAttribute(lineNumber, "breakpoint"); if (!breakpointDecoration) continue; this._removeBreakpointDecoration(lineNumber); this._addBreakpointDecoration(lineNumber, breakpointDecoration.condition, breakpointDecoration.enabled, true); } }, _supportsEnabledBreakpointsWhileEditing: function() { return this._uiSourceCode.isSnippet; }, _restoreBreakpointsAfterEditing: function() { var breakpoints = {}; for (var lineNumber = 0; lineNumber < this._textEditor.linesCount; ++lineNumber) { var breakpointDecoration = this._textEditor.getAttribute(lineNumber, "breakpoint"); if (breakpointDecoration) { breakpoints[lineNumber] = breakpointDecoration; this._removeBreakpointDecoration(lineNumber); } } var breakpointLocations = this._breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode); var lineNumbers = {}; for (var i = 0; i < breakpointLocations.length; ++i) { var breakpoint = breakpointLocations[i].breakpoint; breakpointLocations[i].breakpoint.remove(); } for (var lineNumberString in breakpoints) { var lineNumber = parseInt(lineNumberString, 10); if (isNaN(lineNumber)) continue; var breakpointDecoration = breakpoints[lineNumberString]; this._setBreakpoint(lineNumber, breakpointDecoration.condition, breakpointDecoration.enabled); } }, _getPopoverAnchor: function(element, event) { if (!WebInspector.debuggerModel.isPaused()) return null; if (window.getSelection().type === "Range") return null; var lineElement = element.enclosingNodeOrSelfWithClass("webkit-line-content"); if (!lineElement) return null; if (element.hasStyleClass("webkit-javascript-ident")) return element; if (element.hasStyleClass("source-frame-token")) return element; if (element.hasStyleClass("webkit-javascript-keyword")) return element.textContent === "this" ? element : null; if (element !== lineElement || lineElement.childElementCount) return null; var lineContent = lineElement.textContent; var ranges = []; var regex = new RegExp("[a-zA-Z_\$0-9]+", "g"); var match; while (regex.lastIndex < lineContent.length && (match = regex.exec(lineContent))) ranges.push({offset: match.index, length: regex.lastIndex - match.index}); var changes = []; this.textEditor.highlightRangesWithStyleClass(lineElement, ranges, "source-frame-token", changes); var lineOffsetLeft = lineElement.totalOffsetLeft(); for (var child = lineElement.firstChild; child; child = child.nextSibling) { if (child.nodeType !== Node.ELEMENT_NODE || !child.hasStyleClass("source-frame-token")) continue; if (event.x > lineOffsetLeft + child.offsetLeft && event.x < lineOffsetLeft + child.offsetLeft + child.offsetWidth) { var text = child.textContent; return (text === "this" || !WebInspector.SourceJavaScriptTokenizer.Keywords[text]) ? child : null; } } return null; }, _resolveObjectForPopover: function(element, showCallback, objectGroupName) { this._highlightElement = this._highlightExpression(element); function showObjectPopover(result, wasThrown) { if (!WebInspector.debuggerModel.isPaused()) { this._popoverHelper.hidePopover(); return; } showCallback(WebInspector.RemoteObject.fromPayload(result), wasThrown, this._highlightElement); if (this._highlightElement) this._highlightElement.addStyleClass("source-frame-eval-expression"); } if (!WebInspector.debuggerModel.isPaused()) { this._popoverHelper.hidePopover(); return; } var selectedCallFrame = WebInspector.debuggerModel.selectedCallFrame(); selectedCallFrame.evaluate(this._highlightElement.textContent, objectGroupName, false, true, false, false, showObjectPopover.bind(this)); }, _onHidePopover: function() { var highlightElement = this._highlightElement; if (!highlightElement) return; this.textEditor.hideHighlightedExpression(highlightElement); delete this._highlightElement; }, _highlightExpression: function(element) { return this.textEditor.highlightExpression(element, { "webkit-javascript-ident": true, "source-frame-token": true, "webkit-javascript-keyword": true }, { ".": true }); }, _addBreakpointDecoration: function(lineNumber, condition, enabled, mutedWhileEditing) { if (this._preserveDecorations) return; var breakpoint = { condition: condition, enabled: enabled }; this.textEditor.setAttribute(lineNumber, "breakpoint", breakpoint); var disabled = !enabled || mutedWhileEditing; this.textEditor.addBreakpoint(lineNumber, disabled, !!condition); }, _removeBreakpointDecoration: function(lineNumber) { if (this._preserveDecorations) return; this.textEditor.removeAttribute(lineNumber, "breakpoint"); this.textEditor.removeBreakpoint(lineNumber); }, _onKeyDown: function(event) { if (event.keyIdentifier === "U+001B") { if (this._popoverHelper.isPopoverVisible()) { this._popoverHelper.hidePopover(); event.consume(); } } }, _editBreakpointCondition: function(lineNumber, breakpoint) { this._conditionElement = this._createConditionElement(lineNumber); this.textEditor.addDecoration(lineNumber, this._conditionElement); function finishEditing(committed, element, newText) { this.textEditor.removeDecoration(lineNumber, this._conditionElement); delete this._conditionEditorElement; delete this._conditionElement; if (breakpoint) breakpoint.setCondition(newText); else this._setBreakpoint(lineNumber, newText, true); } var config = new WebInspector.EditingConfig(finishEditing.bind(this, true), finishEditing.bind(this, false)); WebInspector.startEditing(this._conditionEditorElement, config); this._conditionEditorElement.value = breakpoint ? breakpoint.condition() : ""; this._conditionEditorElement.select(); }, _createConditionElement: function(lineNumber) { var conditionElement = document.createElement("div"); conditionElement.className = "source-frame-breakpoint-condition"; var labelElement = document.createElement("label"); labelElement.className = "source-frame-breakpoint-message"; labelElement.htmlFor = "source-frame-breakpoint-condition"; labelElement.appendChild(document.createTextNode(WebInspector.UIString("The breakpoint on line %d will stop only if this expression is true:", lineNumber))); conditionElement.appendChild(labelElement); var editorElement = document.createElement("input"); editorElement.id = "source-frame-breakpoint-condition"; editorElement.className = "monospace"; editorElement.type = "text"; conditionElement.appendChild(editorElement); this._conditionEditorElement = editorElement; return conditionElement; }, setExecutionLine: function(lineNumber) { this._executionLineNumber = lineNumber; if (this.loaded) { this.textEditor.setExecutionLine(lineNumber); this.revealLine(this._executionLineNumber); if (this.canEditSource()) this.setSelection(WebInspector.TextRange.createFromLocation(lineNumber, 0)); } }, clearExecutionLine: function() { if (this.loaded && typeof this._executionLineNumber === "number") this.textEditor.clearExecutionLine(); delete this._executionLineNumber; }, _lineNumberAfterEditing: function(lineNumber, oldRange, newRange) { var shiftOffset = lineNumber <= oldRange.startLine ? 0 : newRange.linesCount - oldRange.linesCount; if (lineNumber === oldRange.startLine) { var whiteSpacesRegex = /^[\s\xA0]*$/; for (var i = 0; lineNumber + i <= newRange.endLine; ++i) { if (!whiteSpacesRegex.test(this.textEditor.line(lineNumber + i))) { shiftOffset = i; break; } } } var newLineNumber = Math.max(0, lineNumber + shiftOffset); if (oldRange.startLine < lineNumber && lineNumber < oldRange.endLine) newLineNumber = oldRange.startLine; return newLineNumber; }, _breakpointAdded: function(event) { var uiLocation = (event.data.uiLocation); if (uiLocation.uiSourceCode !== this._uiSourceCode) return; var breakpoint = (event.data.breakpoint); if (this.loaded) this._addBreakpointDecoration(uiLocation.lineNumber, breakpoint.condition(), breakpoint.enabled(), false); }, _breakpointRemoved: function(event) { var uiLocation = (event.data.uiLocation); if (uiLocation.uiSourceCode !== this._uiSourceCode) return; var breakpoint = (event.data.breakpoint); var remainingBreakpoint = this._breakpointManager.findBreakpoint(this._uiSourceCode, uiLocation.lineNumber); if (!remainingBreakpoint && this.loaded) this._removeBreakpointDecoration(uiLocation.lineNumber); }, _consoleMessageAdded: function(event) { var message = (event.data); if (this.loaded) this.addMessageToSource(message.lineNumber, message.originalMessage); }, _consoleMessageRemoved: function(event) { var message = (event.data); if (this.loaded) this.removeMessageFromSource(message.lineNumber, message.originalMessage); }, _consoleMessagesCleared: function(event) { this.clearMessages(); }, _onSourceMappingChanged: function(event) { this._updateScriptFile(); }, _updateScriptFile: function() { if (this._scriptFile) { this._scriptFile.removeEventListener(WebInspector.ScriptFile.Events.WillMergeToVM, this._willMergeToVM, this); this._scriptFile.removeEventListener(WebInspector.ScriptFile.Events.DidMergeToVM, this._didMergeToVM, this); this._scriptFile.removeEventListener(WebInspector.ScriptFile.Events.WillDivergeFromVM, this._willDivergeFromVM, this); this._scriptFile.removeEventListener(WebInspector.ScriptFile.Events.DidDivergeFromVM, this._didDivergeFromVM, this); } this._scriptFile = this._uiSourceCode.scriptFile(); if (this._scriptFile) { this._scriptFile.addEventListener(WebInspector.ScriptFile.Events.WillMergeToVM, this._willMergeToVM, this); this._scriptFile.addEventListener(WebInspector.ScriptFile.Events.DidMergeToVM, this._didMergeToVM, this); this._scriptFile.addEventListener(WebInspector.ScriptFile.Events.WillDivergeFromVM, this._willDivergeFromVM, this); this._scriptFile.addEventListener(WebInspector.ScriptFile.Events.DidDivergeFromVM, this._didDivergeFromVM, this); } }, onTextEditorContentLoaded: function() { if (typeof this._executionLineNumber === "number") this.setExecutionLine(this._executionLineNumber); var breakpointLocations = this._breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode); for (var i = 0; i < breakpointLocations.length; ++i) { var breakpoint = breakpointLocations[i].breakpoint; this._addBreakpointDecoration(breakpointLocations[i].uiLocation.lineNumber, breakpoint.condition(), breakpoint.enabled(), false); } var messages = this._uiSourceCode.consoleMessages(); for (var i = 0; i < messages.length; ++i) { var message = messages[i]; this.addMessageToSource(message.lineNumber, message.originalMessage); } }, _handleGutterClick: function(event) { if (this._uiSourceCode.isDirty() && !this._supportsEnabledBreakpointsWhileEditing()) return; var lineNumber = event.data.lineNumber; var eventObject = (event.data.event); if (eventObject.button != 0 || eventObject.altKey || eventObject.ctrlKey || eventObject.metaKey) return; this._toggleBreakpoint(lineNumber, eventObject.shiftKey); eventObject.consume(true); }, _toggleBreakpoint: function(lineNumber, onlyDisable) { var breakpoint = this._breakpointManager.findBreakpoint(this._uiSourceCode, lineNumber); if (breakpoint) { if (onlyDisable) breakpoint.setEnabled(!breakpoint.enabled()); else breakpoint.remove(); } else this._setBreakpoint(lineNumber, "", true); }, toggleBreakpointOnCurrentLine: function() { var selection = this.textEditor.selection(); if (!selection) return; this._toggleBreakpoint(selection.startLine, false); }, _setBreakpoint: function(lineNumber, condition, enabled) { this._breakpointManager.setBreakpoint(this._uiSourceCode, lineNumber, condition, enabled); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.SetBreakpoint, url: this._uiSourceCode.url, line: lineNumber, enabled: enabled }); }, _continueToLine: function(lineNumber) { var rawLocation = (this._uiSourceCode.uiLocationToRawLocation(lineNumber, 0)); WebInspector.debuggerModel.continueToLocation(rawLocation); }, __proto__: WebInspector.SourceFrame.prototype } ; WebInspector.NavigatorOverlayController = function(parentSidebarView, navigatorView, editorView) { this._parentSidebarView = parentSidebarView; this._navigatorView = navigatorView; this._editorView = editorView; this._navigatorSidebarResizeWidgetElement = document.createElement("div"); this._navigatorSidebarResizeWidgetElement.addStyleClass("scripts-navigator-resizer-widget"); this._parentSidebarView.installResizer(this._navigatorSidebarResizeWidgetElement); this._navigatorView.element.appendChild(this._navigatorSidebarResizeWidgetElement); this._navigatorShowHideButton = new WebInspector.StatusBarButton(WebInspector.UIString("Hide navigator"), "scripts-navigator-show-hide-button", 3); this._navigatorShowHideButton.state = "pinned"; this._navigatorShowHideButton.addEventListener("click", this._toggleNavigator, this); this._editorView.element.appendChild(this._navigatorShowHideButton.element); WebInspector.settings.navigatorHidden = WebInspector.settings.createSetting("navigatorHidden", true); if (WebInspector.settings.navigatorHidden.get()) this._toggleNavigator(); } WebInspector.NavigatorOverlayController.prototype = { wasShown: function() { window.setTimeout(this._maybeShowNavigatorOverlay.bind(this), 0); }, _maybeShowNavigatorOverlay: function() { if (WebInspector.settings.navigatorHidden.get() && !WebInspector.settings.navigatorWasOnceHidden.get()) this.showNavigatorOverlay(); }, _toggleNavigator: function() { if (this._navigatorShowHideButton.state === "overlay") this._pinNavigator(); else if (this._navigatorShowHideButton.state === "hidden") this.showNavigatorOverlay(); else this._hidePinnedNavigator(); }, _hidePinnedNavigator: function() { this._navigatorShowHideButton.state = "hidden"; this._navigatorShowHideButton.title = WebInspector.UIString("Show navigator"); this._parentSidebarView.element.appendChild(this._navigatorShowHideButton.element); this._editorView.element.addStyleClass("navigator-hidden"); this._navigatorSidebarResizeWidgetElement.addStyleClass("hidden"); this._parentSidebarView.hideSidebarElement(); this._navigatorView.detach(); this._editorView.focus(); WebInspector.settings.navigatorWasOnceHidden.set(true); WebInspector.settings.navigatorHidden.set(true); }, _pinNavigator: function() { this._navigatorShowHideButton.state = "pinned"; this._navigatorShowHideButton.title = WebInspector.UIString("Hide navigator"); this._editorView.element.removeStyleClass("navigator-hidden"); this._navigatorSidebarResizeWidgetElement.removeStyleClass("hidden"); this._editorView.element.appendChild(this._navigatorShowHideButton.element); this._innerHideNavigatorOverlay(); this._parentSidebarView.showSidebarElement(); this._navigatorView.show(this._parentSidebarView.sidebarElement); this._navigatorView.focus(); WebInspector.settings.navigatorHidden.set(false); }, showNavigatorOverlay: function() { if (this._navigatorShowHideButton.state === "overlay") return; this._navigatorShowHideButton.state = "overlay"; this._navigatorShowHideButton.title = WebInspector.UIString("Pin navigator"); this._sidebarOverlay = new WebInspector.SidebarOverlay(this._navigatorView, "scriptsPanelNavigatorOverlayWidth", Preferences.minScriptsSidebarWidth); this._boundKeyDown = this._keyDown.bind(this); this._sidebarOverlay.element.addEventListener("keydown", this._boundKeyDown, false); var navigatorOverlayResizeWidgetElement = document.createElement("div"); navigatorOverlayResizeWidgetElement.addStyleClass("scripts-navigator-resizer-widget"); this._sidebarOverlay.resizerWidgetElement = navigatorOverlayResizeWidgetElement; this._navigatorView.element.appendChild(this._navigatorShowHideButton.element); this._boundContainingElementFocused = this._containingElementFocused.bind(this); this._parentSidebarView.element.addEventListener("mousedown", this._boundContainingElementFocused, false); this._sidebarOverlay.show(this._parentSidebarView.element); this._navigatorView.focus(); }, _keyDown: function(event) { if (event.handled) return; if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) { this.hideNavigatorOverlay(); event.consume(true); } }, hideNavigatorOverlay: function() { if (this._navigatorShowHideButton.state !== "overlay") return; this._navigatorShowHideButton.state = "hidden"; this._navigatorShowHideButton.title = WebInspector.UIString("Show navigator"); this._parentSidebarView.element.appendChild(this._navigatorShowHideButton.element); this._innerHideNavigatorOverlay(); this._editorView.focus(); }, _innerHideNavigatorOverlay: function() { this._parentSidebarView.element.removeEventListener("mousedown", this._boundContainingElementFocused, false); this._sidebarOverlay.element.removeEventListener("keydown", this._boundKeyDown, false); this._sidebarOverlay.hide(); }, _containingElementFocused: function(event) { if (!event.target.isSelfOrDescendant(this._sidebarOverlay.element)) this.hideNavigatorOverlay(); }, isNavigatorPinned: function() { return this._navigatorShowHideButton.state === "pinned"; }, isNavigatorHidden: function() { return this._navigatorShowHideButton.state === "hidden"; } } ; WebInspector.NavigatorView = function() { WebInspector.View.call(this); this.registerRequiredCSS("navigatorView.css"); this._treeSearchBoxElement = document.createElement("div"); this._treeSearchBoxElement.className = "navigator-tree-search-box"; this.element.appendChild(this._treeSearchBoxElement); var scriptsTreeElement = document.createElement("ol"); this._scriptsTree = new WebInspector.NavigatorTreeOutline(this._treeSearchBoxElement, scriptsTreeElement); var scriptsOutlineElement = document.createElement("div"); scriptsOutlineElement.addStyleClass("outline-disclosure"); scriptsOutlineElement.addStyleClass("navigator"); scriptsOutlineElement.appendChild(scriptsTreeElement); this.element.addStyleClass("fill"); this.element.addStyleClass("navigator-container"); this.element.appendChild(scriptsOutlineElement); this.setDefaultFocusedElement(this._scriptsTree.element); this._folderTreeElements = {}; this._scriptTreeElementsByUISourceCode = new Map(); WebInspector.settings.showScriptFolders.addChangeListener(this._showScriptFoldersSettingChanged.bind(this)); } WebInspector.NavigatorView.Events = { ItemSelected: "ItemSelected", FileRenamed: "FileRenamed" } WebInspector.NavigatorView.prototype = { addUISourceCode: function(uiSourceCode) { if (this._scriptTreeElementsByUISourceCode.get(uiSourceCode)) return; var scriptTreeElement = new WebInspector.NavigatorSourceTreeElement(this, uiSourceCode, ""); this._scriptTreeElementsByUISourceCode.put(uiSourceCode, scriptTreeElement); this._updateScriptTitle(uiSourceCode); this._addUISourceCodeListeners(uiSourceCode); var folderTreeElement = this.getOrCreateFolderTreeElement(uiSourceCode); folderTreeElement.appendChild(scriptTreeElement); }, _uiSourceCodeTitleChanged: function(event) { var uiSourceCode = (event.target); this._updateScriptTitle(uiSourceCode) }, _uiSourceCodeWorkingCopyChanged: function(event) { var uiSourceCode = (event.target); this._updateScriptTitle(uiSourceCode) }, _uiSourceCodeWorkingCopyCommitted: function(event) { var uiSourceCode = (event.target); this._updateScriptTitle(uiSourceCode) }, _uiSourceCodeFormattedChanged: function(event) { var uiSourceCode = (event.target); this._updateScriptTitle(uiSourceCode); }, _updateScriptTitle: function(uiSourceCode, ignoreIsDirty) { var scriptTreeElement = this._scriptTreeElementsByUISourceCode.get(uiSourceCode); if (!scriptTreeElement) return; var titleText; if (uiSourceCode.parsedURL.isValid) { titleText = uiSourceCode.parsedURL.lastPathComponent; if (uiSourceCode.parsedURL.queryParams) titleText += "?" + uiSourceCode.parsedURL.queryParams; } else if (uiSourceCode.parsedURL) titleText = uiSourceCode.parsedURL.url; if (!titleText) titleText = WebInspector.UIString("(program)"); if (!ignoreIsDirty && uiSourceCode.isDirty()) titleText = "*" + titleText; scriptTreeElement.titleText = titleText; }, isScriptSourceAdded: function(uiSourceCode) { var scriptTreeElement = this._scriptTreeElementsByUISourceCode.get(uiSourceCode); return !!scriptTreeElement; }, revealUISourceCode: function(uiSourceCode) { if (this._scriptsTree.selectedTreeElement) this._scriptsTree.selectedTreeElement.deselect(); this._lastSelectedUISourceCode = uiSourceCode; var scriptTreeElement = this._scriptTreeElementsByUISourceCode.get(uiSourceCode); scriptTreeElement.revealAndSelect(true); }, _scriptSelected: function(uiSourceCode, focusSource) { this._lastSelectedUISourceCode = uiSourceCode; var data = { uiSourceCode: uiSourceCode, focusSource: focusSource}; this.dispatchEventToListeners(WebInspector.NavigatorView.Events.ItemSelected, data); }, removeUISourceCode: function(uiSourceCode) { var treeElement = this._scriptTreeElementsByUISourceCode.get(uiSourceCode); while (treeElement) { var parent = treeElement.parent; if (parent) { if (treeElement instanceof WebInspector.NavigatorFolderTreeElement) delete this._folderTreeElements[treeElement.folderIdentifier]; parent.removeChild(treeElement); if (parent.children.length) break; } treeElement = parent; } this._scriptTreeElementsByUISourceCode.remove(uiSourceCode); this._removeUISourceCodeListeners(uiSourceCode); }, _addUISourceCodeListeners: function(uiSourceCode) { uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._uiSourceCodeWorkingCopyChanged, this); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._uiSourceCodeWorkingCopyCommitted, this); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._uiSourceCodeFormattedChanged, this); }, _removeUISourceCodeListeners: function(uiSourceCode) { uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._uiSourceCodeWorkingCopyChanged, this); uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._uiSourceCodeWorkingCopyCommitted, this); uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._uiSourceCodeFormattedChanged, this); }, _showScriptFoldersSettingChanged: function() { var uiSourceCodes = this._scriptsTree.scriptTreeElements(); this.reset(); for (var i = 0; i < uiSourceCodes.length; ++i) this.addUISourceCode(uiSourceCodes[i]); if (this._lastSelectedUISourceCode) this.revealUISourceCode(this._lastSelectedUISourceCode); }, _fileRenamed: function(uiSourceCode, newTitle) { var data = { uiSourceCode: uiSourceCode, name: newTitle }; this.dispatchEventToListeners(WebInspector.NavigatorView.Events.FileRenamed, data); }, rename: function(uiSourceCode, callback) { var scriptTreeElement = this._scriptTreeElementsByUISourceCode.get(uiSourceCode); if (!scriptTreeElement) return; var treeOutlineElement = scriptTreeElement.treeOutline.element; WebInspector.markBeingEdited(treeOutlineElement, true); function commitHandler(element, newTitle, oldTitle) { if (newTitle && newTitle !== oldTitle) this._fileRenamed(uiSourceCode, newTitle); afterEditing.call(this, true); } function cancelHandler() { afterEditing.call(this, false); } function afterEditing(committed) { WebInspector.markBeingEdited(treeOutlineElement, false); this._updateScriptTitle(uiSourceCode); if (callback) callback(committed); } var editingConfig = new WebInspector.EditingConfig(commitHandler.bind(this), cancelHandler.bind(this)); this._updateScriptTitle(uiSourceCode, true); WebInspector.startEditing(scriptTreeElement.titleElement, editingConfig); window.getSelection().setBaseAndExtent(scriptTreeElement.titleElement, 0, scriptTreeElement.titleElement, 1); }, reset: function() { var uiSourceCodes = this._scriptsTree.scriptTreeElements; for (var i = 0; i < uiSourceCodes.length; ++i) this._removeUISourceCodeListeners(uiSourceCodes[i]); this._scriptsTree.stopSearch(); this._scriptsTree.removeChildren(); this._folderTreeElements = {}; this._scriptTreeElementsByUISourceCode.clear(); }, createFolderTreeElement: function(parentFolderElement, folderIdentifier, domain, folderName) { var folderTreeElement = new WebInspector.NavigatorFolderTreeElement(folderIdentifier, domain, folderName); parentFolderElement.appendChild(folderTreeElement); this._folderTreeElements[folderIdentifier] = folderTreeElement; return folderTreeElement; }, getOrCreateFolderTreeElement: function(uiSourceCode) { return this._getOrCreateFolderTreeElement(uiSourceCode.parsedURL.host, uiSourceCode.parsedURL.folderPathComponents); }, _getOrCreateFolderTreeElement: function(domain, folderName) { var folderIdentifier = domain + "/" + folderName; if (this._folderTreeElements[folderIdentifier]) return this._folderTreeElements[folderIdentifier]; var showScriptFolders = WebInspector.settings.showScriptFolders.get(); if ((!domain && !folderName) || !showScriptFolders) return this._scriptsTree; var parentFolderElement; if (!folderName) parentFolderElement = this._scriptsTree; else parentFolderElement = this._getOrCreateFolderTreeElement(domain, ""); return this.createFolderTreeElement(parentFolderElement, folderIdentifier, domain, folderName); }, handleContextMenu: function(event, uiSourceCode) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendApplicableItems(uiSourceCode); contextMenu.show(); }, __proto__: WebInspector.View.prototype } WebInspector.NavigatorTreeOutline = function(treeSearchBoxElement, element) { TreeOutline.call(this, element); this.element = element; this._treeSearchBoxElement = treeSearchBoxElement; this.comparator = WebInspector.NavigatorTreeOutline._treeElementsCompare; this.searchable = true; this.searchInputElement = document.createElement("input"); } WebInspector.NavigatorTreeOutline._treeElementsCompare = function compare(treeElement1, treeElement2) { function typeWeight(treeElement) { if (treeElement instanceof WebInspector.NavigatorFolderTreeElement) { if (treeElement.isDomain) { if (treeElement.titleText === WebInspector.inspectedPageDomain) return 1; return 2; } return 3; } return 4; } var typeWeight1 = typeWeight(treeElement1); var typeWeight2 = typeWeight(treeElement2); var result; if (typeWeight1 > typeWeight2) result = 1; else if (typeWeight1 < typeWeight2) result = -1; else { var title1 = treeElement1.titleText; var title2 = treeElement2.titleText; result = title1.localeCompare(title2); } return result; } WebInspector.NavigatorTreeOutline.prototype = { scriptTreeElements: function() { var result = []; if (this.children.length) { for (var treeElement = this.children[0]; treeElement; treeElement = treeElement.traverseNextTreeElement(false, this, true)) { if (treeElement instanceof WebInspector.NavigatorSourceTreeElement) result.push(treeElement.uiSourceCode); } } return result; }, searchStarted: function() { this._treeSearchBoxElement.appendChild(this.searchInputElement); this._treeSearchBoxElement.addStyleClass("visible"); }, searchFinished: function() { this._treeSearchBoxElement.removeChild(this.searchInputElement); this._treeSearchBoxElement.removeStyleClass("visible"); }, __proto__: TreeOutline.prototype } WebInspector.BaseNavigatorTreeElement = function(title, iconClasses, hasChildren, noIcon) { TreeElement.call(this, "", null, hasChildren); this._titleText = title; this._iconClasses = iconClasses; this._noIcon = noIcon; } WebInspector.BaseNavigatorTreeElement.prototype = { onattach: function() { this.listItemElement.removeChildren(); if (this._iconClasses) { for (var i = 0; i < this._iconClasses.length; ++i) this.listItemElement.addStyleClass(this._iconClasses[i]); } var selectionElement = document.createElement("div"); selectionElement.className = "selection"; this.listItemElement.appendChild(selectionElement); if (!this._noIcon) { this.imageElement = document.createElement("img"); this.imageElement.className = "icon"; this.listItemElement.appendChild(this.imageElement); } this.titleElement = document.createElement("div"); this.titleElement.className = "base-navigator-tree-element-title"; this._titleTextNode = document.createTextNode(""); this._titleTextNode.textContent = this._titleText; this.titleElement.appendChild(this._titleTextNode); this.listItemElement.appendChild(this.titleElement); this.expand(); }, onreveal: function() { if (this.listItemElement) this.listItemElement.scrollIntoViewIfNeeded(true); }, get titleText() { return this._titleText; }, set titleText(titleText) { if (this._titleText === titleText) return; this._titleText = titleText || ""; if (this.titleElement) this.titleElement.textContent = this._titleText; }, matchesSearchText: function(searchText) { return this.titleText.match(new RegExp("^" + searchText.escapeForRegExp(), "i")); }, __proto__: TreeElement.prototype } WebInspector.NavigatorFolderTreeElement = function(folderIdentifier, domain, folderName) { this._folderIdentifier = folderIdentifier; this._folderName = folderName; var iconClass = this.isDomain ? "navigator-domain-tree-item" : "navigator-folder-tree-item"; var title = this.isDomain ? domain : folderName.substring(1); WebInspector.BaseNavigatorTreeElement.call(this, title, [iconClass], true); this.tooltip = folderName; } WebInspector.NavigatorFolderTreeElement.prototype = { get folderIdentifier() { return this._folderIdentifier; }, get isDomain() { return this._folderName === ""; }, onattach: function() { WebInspector.BaseNavigatorTreeElement.prototype.onattach.call(this); if (this.isDomain && this.titleText != WebInspector.inspectedPageDomain) this.collapse(); else this.expand(); }, __proto__: WebInspector.BaseNavigatorTreeElement.prototype } WebInspector.NavigatorSourceTreeElement = function(navigatorView, uiSourceCode, title) { WebInspector.BaseNavigatorTreeElement.call(this, title, ["navigator-" + uiSourceCode.contentType().name() + "-tree-item"], false); this._navigatorView = navigatorView; this._uiSourceCode = uiSourceCode; this.tooltip = uiSourceCode.url; } WebInspector.NavigatorSourceTreeElement.prototype = { get uiSourceCode() { return this._uiSourceCode; }, onattach: function() { WebInspector.BaseNavigatorTreeElement.prototype.onattach.call(this); this.listItemElement.draggable = true; this.listItemElement.addEventListener("click", this._onclick.bind(this), false); this.listItemElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), false); this.listItemElement.addEventListener("mousedown", this._onmousedown.bind(this), false); this.listItemElement.addEventListener("dragstart", this._ondragstart.bind(this), false); }, _onmousedown: function(event) { if (event.which === 1) this._uiSourceCode.requestContent(callback.bind(this)); function callback(content, contentEncoded, mimeType) { this._warmedUpContent = content; } }, _ondragstart: function(event) { event.dataTransfer.setData("text/plain", this._warmedUpContent); event.dataTransfer.effectAllowed = "copy"; return true; }, onspace: function() { this._navigatorView._scriptSelected(this.uiSourceCode, true); return true; }, _onclick: function(event) { this._navigatorView._scriptSelected(this.uiSourceCode, false); }, ondblclick: function(event) { var middleClick = event.button === 1; this._navigatorView._scriptSelected(this.uiSourceCode, !middleClick); }, onenter: function() { this._navigatorView._scriptSelected(this.uiSourceCode, true); return true; }, _handleContextMenuEvent: function(event) { this._navigatorView.handleContextMenu(event, this._uiSourceCode); }, __proto__: WebInspector.BaseNavigatorTreeElement.prototype } ; WebInspector.RevisionHistoryView = function() { WebInspector.View.call(this); this.registerRequiredCSS("revisionHistory.css"); this.element.addStyleClass("revision-history-drawer"); this.element.addStyleClass("fill"); this.element.addStyleClass("outline-disclosure"); this._uiSourceCodeItems = new Map(); var olElement = this.element.createChild("ol"); this._treeOutline = new TreeOutline(olElement); function populateRevisions(uiSourceCode) { if (uiSourceCode.history.length) this._createUISourceCodeItem(uiSourceCode); } WebInspector.workspace.uiSourceCodes().forEach(populateRevisions.bind(this)); WebInspector.workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted, this._revisionAdded, this); WebInspector.workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); WebInspector.workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.TemporaryUISourceCodeRemoved, this._uiSourceCodeRemoved, this); WebInspector.workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._reset, this); this._statusElement = document.createElement("span"); this._statusElement.textContent = WebInspector.UIString("Local modifications"); } WebInspector.RevisionHistoryView.showHistory = function(uiSourceCode) { if (!WebInspector.RevisionHistoryView._view) WebInspector.RevisionHistoryView._view = new WebInspector.RevisionHistoryView(); var view = WebInspector.RevisionHistoryView._view; WebInspector.showViewInDrawer(view._statusElement, view); view._revealUISourceCode(uiSourceCode); } WebInspector.RevisionHistoryView.prototype = { _createUISourceCodeItem: function(uiSourceCode) { var uiSourceCodeItem = new TreeElement(uiSourceCode.parsedURL.displayName, null, true); uiSourceCodeItem.selectable = false; for (var i = 0; i < this._treeOutline.children.length; ++i) { if (this._treeOutline.children[i].title.localeCompare(uiSourceCode.parsedURL.displayName) > 0) { this._treeOutline.insertChild(uiSourceCodeItem, i); break; } } if (i === this._treeOutline.children.length) this._treeOutline.appendChild(uiSourceCodeItem); this._uiSourceCodeItems.put(uiSourceCode, uiSourceCodeItem); var revisionCount = uiSourceCode.history.length; for (var i = revisionCount - 1; i >= 0; --i) { var revision = uiSourceCode.history[i]; var historyItem = new WebInspector.RevisionHistoryTreeElement(revision, uiSourceCode.history[i - 1], i !== revisionCount - 1); uiSourceCodeItem.appendChild(historyItem); } var linkItem = new TreeElement("", null, false); linkItem.selectable = false; uiSourceCodeItem.appendChild(linkItem); var revertToOriginal = linkItem.listItemElement.createChild("span", "revision-history-link revision-history-link-row"); revertToOriginal.textContent = WebInspector.UIString("apply original content"); revertToOriginal.addEventListener("click", uiSourceCode.revertToOriginal.bind(uiSourceCode)); var clearHistoryElement = uiSourceCodeItem.listItemElement.createChild("span", "revision-history-link"); clearHistoryElement.textContent = WebInspector.UIString("revert"); clearHistoryElement.addEventListener("click", this._clearHistory.bind(this, uiSourceCode)); return uiSourceCodeItem; }, _clearHistory: function(uiSourceCode) { uiSourceCode.revertAndClearHistory(this._removeUISourceCode.bind(this)); }, _revisionAdded: function(event) { var uiSourceCode = (event.data.uiSourceCode); var uiSourceCodeItem = this._uiSourceCodeItems.get(uiSourceCode); if (!uiSourceCodeItem) { uiSourceCodeItem = this._createUISourceCodeItem(uiSourceCode); return; } var historyLength = uiSourceCode.history.length; var historyItem = new WebInspector.RevisionHistoryTreeElement(uiSourceCode.history[historyLength - 1], uiSourceCode.history[historyLength - 2], false); if (uiSourceCodeItem.children.length) uiSourceCodeItem.children[0].allowRevert(); uiSourceCodeItem.insertChild(historyItem, 0); }, _revealUISourceCode: function(uiSourceCode) { var uiSourceCodeItem = this._uiSourceCodeItems.get(uiSourceCode); if (uiSourceCodeItem) { uiSourceCodeItem.reveal(); uiSourceCodeItem.expand(); } }, _uiSourceCodeRemoved: function(event) { var uiSourceCode = (event.data); this._removeUISourceCode(uiSourceCode); }, _removeUISourceCode: function(uiSourceCode) { var uiSourceCodeItem = this._uiSourceCodeItems.get(uiSourceCode); if (!uiSourceCodeItem) return; this._treeOutline.removeChild(uiSourceCodeItem); this._uiSourceCodeItems.remove(uiSourceCode); }, _reset: function() { this._treeOutline.removeChildren(); this._uiSourceCodeItems.clear(); }, __proto__: WebInspector.View.prototype } WebInspector.RevisionHistoryTreeElement = function(revision, baseRevision, allowRevert) { TreeElement.call(this, revision.timestamp.toLocaleTimeString(), null, true); this.selectable = false; this._revision = revision; this._baseRevision = baseRevision; this._revertElement = document.createElement("span"); this._revertElement.className = "revision-history-link"; this._revertElement.textContent = WebInspector.UIString("apply revision content"); this._revertElement.addEventListener("click", this._revision.revertToThis.bind(this._revision), false); if (!allowRevert) this._revertElement.addStyleClass("hidden"); } WebInspector.RevisionHistoryTreeElement.prototype = { onattach: function() { this.listItemElement.addStyleClass("revision-history-revision"); }, onexpand: function() { this.listItemElement.appendChild(this._revertElement); if (this._wasExpandedOnce) return; this._wasExpandedOnce = true; this.childrenListElement.addStyleClass("source-code"); if (this._baseRevision) this._baseRevision.requestContent(step1.bind(this)); else this._revision.uiSourceCode.requestOriginalContent(step1.bind(this)); function step1(baseContent) { this._revision.requestContent(step2.bind(this, baseContent)); } function step2(baseContent, newContent) { var baseLines = difflib.stringAsLines(baseContent); var newLines = difflib.stringAsLines(newContent); var sm = new difflib.SequenceMatcher(baseLines, newLines); var opcodes = sm.get_opcodes(); var lastWasSeparator = false; for (var idx = 0; idx < opcodes.length; idx++) { var code = opcodes[idx]; var change = code[0]; var b = code[1]; var be = code[2]; var n = code[3]; var ne = code[4]; var rowCount = Math.max(be - b, ne - n); var topRows = []; var bottomRows = []; for (var i = 0; i < rowCount; i++) { if (change === "delete" || (change === "replace" && b < be)) { var lineNumber = b++; this._createLine(lineNumber, null, baseLines[lineNumber], "removed"); lastWasSeparator = false; } if (change === "insert" || (change === "replace" && n < ne)) { var lineNumber = n++; this._createLine(null, lineNumber, newLines[lineNumber], "added"); lastWasSeparator = false; } if (change === "equal") { b++; n++; if (!lastWasSeparator) this._createLine(null, null, " \u2026", "separator"); lastWasSeparator = true; } } } } }, oncollapse: function() { if (this._revertElement.parentElement) this._revertElement.parentElement.removeChild(this._revertElement); }, _createLine: function(baseLineNumber, newLineNumber, lineContent, changeType) { var child = new TreeElement("", null, false); child.selectable = false; this.appendChild(child); var lineElement = document.createElement("span"); function appendLineNumber(lineNumber) { var numberString = lineNumber !== null ? numberToStringWithSpacesPadding(lineNumber + 1, 4) : " "; var lineNumberSpan = document.createElement("span"); lineNumberSpan.addStyleClass("webkit-line-number"); lineNumberSpan.textContent = numberString; child.listItemElement.appendChild(lineNumberSpan); } appendLineNumber(baseLineNumber); appendLineNumber(newLineNumber); var contentSpan = document.createElement("span"); contentSpan.textContent = lineContent; child.listItemElement.appendChild(contentSpan); child.listItemElement.addStyleClass("revision-history-line"); child.listItemElement.addStyleClass("revision-history-line-" + changeType); }, allowRevert: function() { this._revertElement.removeStyleClass("hidden"); }, __proto__: TreeElement.prototype } ; WebInspector.ScopeChainSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Scope Variables")); this._sections = []; this._expandedSections = {}; this._expandedProperties = []; } WebInspector.ScopeChainSidebarPane.prototype = { update: function(callFrame) { this.bodyElement.removeChildren(); if (!callFrame) { var infoElement = document.createElement("div"); infoElement.className = "info"; infoElement.textContent = WebInspector.UIString("Not Paused"); this.bodyElement.appendChild(infoElement); return; } for (var i = 0; i < this._sections.length; ++i) { var section = this._sections[i]; if (!section.title) continue; if (section.expanded) this._expandedSections[section.title] = true; else delete this._expandedSections[section.title]; } this._sections = []; var foundLocalScope = false; var scopeChain = callFrame.scopeChain; for (var i = 0; i < scopeChain.length; ++i) { var scope = scopeChain[i]; var title = null; var subtitle = scope.object.description; var emptyPlaceholder = null; var extraProperties = null; switch (scope.type) { case "local": foundLocalScope = true; title = WebInspector.UIString("Local"); emptyPlaceholder = WebInspector.UIString("No Variables"); subtitle = null; if (callFrame.this) extraProperties = [ new WebInspector.RemoteObjectProperty("this", WebInspector.RemoteObject.fromPayload(callFrame.this)) ]; if (i == 0) { var details = WebInspector.debuggerModel.debuggerPausedDetails(); var exception = details.reason === WebInspector.DebuggerModel.BreakReason.Exception ? details.auxData : 0; if (exception) { extraProperties = extraProperties || []; var exceptionObject = (exception); extraProperties.push(new WebInspector.RemoteObjectProperty("<exception>", WebInspector.RemoteObject.fromPayload(exceptionObject))); } } break; case "closure": title = WebInspector.UIString("Closure"); emptyPlaceholder = WebInspector.UIString("No Variables"); subtitle = null; break; case "catch": title = WebInspector.UIString("Catch"); subtitle = null; break; case "with": title = WebInspector.UIString("With Block"); break; case "global": title = WebInspector.UIString("Global"); break; } if (!title || title === subtitle) subtitle = null; var section = new WebInspector.ObjectPropertiesSection(WebInspector.RemoteObject.fromPayload(scope.object), title, subtitle, emptyPlaceholder, true, extraProperties, WebInspector.ScopeVariableTreeElement); section.editInSelectedCallFrameWhenPaused = true; section.pane = this; if (scope.type === "global") section.expanded = false; else if (!foundLocalScope || scope.type === "local" || title in this._expandedSections) section.expanded = true; this._sections.push(section); this.bodyElement.appendChild(section.element); } }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.ScopeVariableTreeElement = function(property) { WebInspector.ObjectPropertyTreeElement.call(this, property); } WebInspector.ScopeVariableTreeElement.prototype = { onattach: function() { WebInspector.ObjectPropertyTreeElement.prototype.onattach.call(this); if (this.hasChildren && this.propertyIdentifier in this.treeOutline.section.pane._expandedProperties) this.expand(); }, onexpand: function() { this.treeOutline.section.pane._expandedProperties[this.propertyIdentifier] = true; }, oncollapse: function() { delete this.treeOutline.section.pane._expandedProperties[this.propertyIdentifier]; }, get propertyIdentifier() { if ("_propertyIdentifier" in this) return this._propertyIdentifier; var section = this.treeOutline.section; this._propertyIdentifier = section.title + ":" + (section.subtitle ? section.subtitle + ":" : "") + this.propertyPath(); return this._propertyIdentifier; }, __proto__: WebInspector.ObjectPropertyTreeElement.prototype } ; WebInspector.ScriptsNavigator = function() { WebInspector.Object.call(this); this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.shrinkableTabs = true; this._tabbedPane.element.addStyleClass("navigator-tabbed-pane"); this._scriptsView = new WebInspector.NavigatorView(); this._scriptsView.addEventListener(WebInspector.NavigatorView.Events.ItemSelected, this._scriptSelected, this); this._contentScriptsView = new WebInspector.NavigatorView(); this._contentScriptsView.addEventListener(WebInspector.NavigatorView.Events.ItemSelected, this._scriptSelected, this); this._snippetsView = new WebInspector.SnippetsNavigatorView(); this._snippetsView.addEventListener(WebInspector.NavigatorView.Events.ItemSelected, this._scriptSelected, this); this._snippetsView.addEventListener(WebInspector.NavigatorView.Events.FileRenamed, this._fileRenamed, this); this._snippetsView.addEventListener(WebInspector.SnippetsNavigatorView.Events.SnippetCreationRequested, this._snippetCreationRequested, this); this._snippetsView.addEventListener(WebInspector.SnippetsNavigatorView.Events.ItemRenamingRequested, this._itemRenamingRequested, this); this._tabbedPane.appendTab(WebInspector.ScriptsNavigator.ScriptsTab, WebInspector.UIString("Sources"), this._scriptsView); this._tabbedPane.selectTab(WebInspector.ScriptsNavigator.ScriptsTab); this._tabbedPane.appendTab(WebInspector.ScriptsNavigator.ContentScriptsTab, WebInspector.UIString("Content scripts"), this._contentScriptsView); if (WebInspector.experimentsSettings.snippetsSupport.isEnabled()) this._tabbedPane.appendTab(WebInspector.ScriptsNavigator.SnippetsTab, WebInspector.UIString("Snippets"), this._snippetsView); } WebInspector.ScriptsNavigator.Events = { ScriptSelected: "ScriptSelected", SnippetCreationRequested: "SnippetCreationRequested", ItemRenamingRequested: "ItemRenamingRequested", FileRenamed: "FileRenamed" } WebInspector.ScriptsNavigator.ScriptsTab = "scripts"; WebInspector.ScriptsNavigator.ContentScriptsTab = "contentScripts"; WebInspector.ScriptsNavigator.SnippetsTab = "snippets"; WebInspector.ScriptsNavigator.prototype = { get view() { return this._tabbedPane; }, _snippetsNavigatorViewForUISourceCode: function(uiSourceCode) { if (uiSourceCode.isContentScript) return this._contentScriptsView; else if (uiSourceCode.isSnippet) return this._snippetsView; else return this._scriptsView; }, addUISourceCode: function(uiSourceCode) { this._snippetsNavigatorViewForUISourceCode(uiSourceCode).addUISourceCode(uiSourceCode); }, removeUISourceCode: function(uiSourceCode) { this._snippetsNavigatorViewForUISourceCode(uiSourceCode).removeUISourceCode(uiSourceCode); }, isScriptSourceAdded: function(uiSourceCode) { return this._snippetsNavigatorViewForUISourceCode(uiSourceCode).isScriptSourceAdded(uiSourceCode); }, revealUISourceCode: function(uiSourceCode) { this._snippetsNavigatorViewForUISourceCode(uiSourceCode).revealUISourceCode(uiSourceCode); if (uiSourceCode.isContentScript) this._tabbedPane.selectTab(WebInspector.ScriptsNavigator.ContentScriptsTab); else if (uiSourceCode.isSnippet) this._tabbedPane.selectTab(WebInspector.ScriptsNavigator.SnippetsTab); else this._tabbedPane.selectTab(WebInspector.ScriptsNavigator.ScriptsTab); }, rename: function(uiSourceCode, callback) { this._snippetsNavigatorViewForUISourceCode(uiSourceCode).rename(uiSourceCode, callback); }, _scriptSelected: function(event) { this.dispatchEventToListeners(WebInspector.ScriptsNavigator.Events.ScriptSelected, event.data); }, _fileRenamed: function(event) { this.dispatchEventToListeners(WebInspector.ScriptsNavigator.Events.FileRenamed, event.data); }, _itemRenamingRequested: function(event) { this.dispatchEventToListeners(WebInspector.ScriptsNavigator.Events.ItemRenamingRequested, event.data); }, _snippetCreationRequested: function(event) { this.dispatchEventToListeners(WebInspector.ScriptsNavigator.Events.SnippetCreationRequested, event.data); }, reset: function() { this._scriptsView.reset(); this._contentScriptsView.reset(); this._snippetsView.reset(); }, __proto__: WebInspector.Object.prototype } WebInspector.SnippetsNavigatorView = function() { WebInspector.NavigatorView.call(this); this.element.addEventListener("contextmenu", this.handleContextMenu.bind(this), false); } WebInspector.SnippetsNavigatorView.Events = { SnippetCreationRequested: "SnippetCreationRequested", ItemRenamingRequested: "ItemRenamingRequested" } WebInspector.SnippetsNavigatorView.prototype = { getOrCreateFolderTreeElement: function(uiSourceCode) { return this._scriptsTree; }, handleContextMenu: function(event, uiSourceCode) { var contextMenu = new WebInspector.ContextMenu(event); if (uiSourceCode) { contextMenu.appendItem(WebInspector.UIString("Run"), this._handleEvaluateSnippet.bind(this, uiSourceCode)); contextMenu.appendItem(WebInspector.UIString("Rename"), this._handleRenameSnippet.bind(this, uiSourceCode)); contextMenu.appendItem(WebInspector.UIString("Remove"), this._handleRemoveSnippet.bind(this, uiSourceCode)); contextMenu.appendSeparator(); } contextMenu.appendItem(WebInspector.UIString("New"), this._handleCreateSnippet.bind(this)); contextMenu.show(); }, _handleEvaluateSnippet: function(uiSourceCode, event) { if (!uiSourceCode.isSnippet) return; WebInspector.scriptSnippetModel.evaluateScriptSnippet(uiSourceCode); }, _handleRenameSnippet: function(uiSourceCode, event) { this.dispatchEventToListeners(WebInspector.ScriptsNavigator.Events.ItemRenamingRequested, uiSourceCode); }, _handleRemoveSnippet: function(uiSourceCode, event) { if (!uiSourceCode.isSnippet) return; WebInspector.scriptSnippetModel.deleteScriptSnippet(uiSourceCode); }, _handleCreateSnippet: function(event) { this._snippetCreationRequested(); }, _snippetCreationRequested: function() { this.dispatchEventToListeners(WebInspector.SnippetsNavigatorView.Events.SnippetCreationRequested, null); }, __proto__: WebInspector.NavigatorView.prototype } ; WebInspector.ScriptsSearchScope = function(uiSourceCodeProvider) { WebInspector.SearchScope.call(this) this._searchId = 0; this._uiSourceCodeProvider = uiSourceCodeProvider; } WebInspector.ScriptsSearchScope.prototype = { performSearch: function(searchConfig, searchResultCallback, searchFinishedCallback) { this.stopSearch(); var uiSourceCodes = this._sortedUISourceCodes(); var uiSourceCodeIndex = 0; function filterOutContentScripts(uiSourceCode) { return !uiSourceCode.isContentScript; } if (!WebInspector.settings.searchInContentScripts.get()) uiSourceCodes = uiSourceCodes.filter(filterOutContentScripts); function continueSearch() { if (uiSourceCodeIndex < uiSourceCodes.length) { var uiSourceCode = uiSourceCodes[uiSourceCodeIndex++]; uiSourceCode.searchInContent(searchConfig.query, !searchConfig.ignoreCase, searchConfig.isRegex, searchCallbackWrapper.bind(this, this._searchId, uiSourceCode)); } else searchFinishedCallback(true); } function searchCallbackWrapper(searchId, uiSourceCode, searchMatches) { if (searchId !== this._searchId) { searchFinishedCallback(false); return; } var searchResult = new WebInspector.FileBasedSearchResultsPane.SearchResult(uiSourceCode, searchMatches); searchResultCallback(searchResult); if (searchId !== this._searchId) { searchFinishedCallback(false); return; } continueSearch.call(this); } continueSearch.call(this); return uiSourceCodes.length; }, stopSearch: function() { ++this._searchId; }, createSearchResultsPane: function(searchConfig) { return new WebInspector.FileBasedSearchResultsPane(searchConfig); }, _sortedUISourceCodes: function() { function filterOutAnonymous(uiSourceCode) { return !!uiSourceCode.url; } function comparator(a, b) { return a.url.localeCompare(b.url); } var uiSourceCodes = this._uiSourceCodeProvider.uiSourceCodes(); uiSourceCodes = uiSourceCodes.filter(filterOutAnonymous); uiSourceCodes.sort(comparator); return uiSourceCodes; }, __proto__: WebInspector.SearchScope.prototype } ; WebInspector.SnippetJavaScriptSourceFrame = function(scriptsPanel, uiSourceCode) { WebInspector.JavaScriptSourceFrame.call(this, scriptsPanel, uiSourceCode); this._uiSourceCode = uiSourceCode; this._runButton = new WebInspector.StatusBarButton(WebInspector.UIString("Run"), "evaluate-snippet-status-bar-item"); this._runButton.addEventListener("click", this._runButtonClicked, this); } WebInspector.SnippetJavaScriptSourceFrame.prototype = { statusBarItems: function() { return [this._runButton.element]; }, _runButtonClicked: function() { WebInspector.scriptSnippetModel.evaluateScriptSnippet(this._uiSourceCode); }, __proto__: WebInspector.JavaScriptSourceFrame.prototype } ; WebInspector.StyleSheetOutlineDialog = function(view, uiSourceCode) { WebInspector.SelectionDialogContentProvider.call(this); this._rules = []; this._view = view; this._uiSourceCode = uiSourceCode; } WebInspector.StyleSheetOutlineDialog.show = function(view, uiSourceCode) { if (WebInspector.Dialog.currentInstance()) return null; var delegate = new WebInspector.StyleSheetOutlineDialog(view, uiSourceCode); var filteredItemSelectionDialog = new WebInspector.FilteredItemSelectionDialog(delegate); WebInspector.Dialog.show(view.element, filteredItemSelectionDialog); } WebInspector.StyleSheetOutlineDialog.prototype = { itemTitleAt: function(itemIndex) { return this._rules[itemIndex].selectorText; }, itemSuffixAt: function(itemIndex) { return ""; }, itemSubtitleAt: function(itemIndex) { return ":" + (this._rules[itemIndex].sourceLine + 1); }, itemKeyAt: function(itemIndex) { return this._rules[itemIndex].selectorText; }, itemsCount: function() { return this._rules.length; }, requestItems: function(callback) { function didGetAllStyleSheets(error, infos) { if (error) { callback(0, 0, 0, 0); return; } for (var i = 0; i < infos.length; ++i) { var info = infos[i]; if (info.sourceURL === this._uiSourceCode.contentURL()) { WebInspector.CSSStyleSheet.createForId(info.styleSheetId, didGetStyleSheet.bind(this)); return; } } callback(0, 0, 0, 0); } CSSAgent.getAllStyleSheets(didGetAllStyleSheets.bind(this)); function didGetStyleSheet(styleSheet) { if (!styleSheet) { callback(0, 0, 0, 0); return; } this._rules = styleSheet.rules; callback(0, this._rules.length, 0, 1); } }, selectItem: function(itemIndex, promptValue) { var lineNumber = this._rules[itemIndex].sourceLine; if (!isNaN(lineNumber) && lineNumber >= 0) this._view.highlightLine(lineNumber); this._view.focus(); }, rewriteQuery: function(query) { return query; }, __proto__: WebInspector.SelectionDialogContentProvider.prototype } ; WebInspector.TabbedEditorContainerDelegate = function() { } WebInspector.TabbedEditorContainerDelegate.prototype = { viewForFile: function(uiSourceCode) { } } WebInspector.TabbedEditorContainer = function(delegate, settingName) { WebInspector.Object.call(this); this._delegate = delegate; this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.closeableTabs = true; this._tabbedPane.element.id = "scripts-editor-container-tabbed-pane"; this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabClosed, this._tabClosed, this); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this._tabIds = new Map(); this._files = {}; this._loadedURLs = {}; this._previouslyViewedFilesSetting = WebInspector.settings.createSetting(settingName, []); this._history = WebInspector.TabbedEditorContainer.History.fromObject(this._previouslyViewedFilesSetting.get()); } WebInspector.TabbedEditorContainer.Events = { EditorSelected: "EditorSelected", EditorClosed: "EditorClosed" } WebInspector.TabbedEditorContainer._tabId = 0; WebInspector.TabbedEditorContainer.maximalPreviouslyViewedFilesCount = 30; WebInspector.TabbedEditorContainer.prototype = { get view() { return this._tabbedPane; }, get visibleView() { return this._tabbedPane.visibleView; }, show: function(parentElement) { this._tabbedPane.show(parentElement); }, showFile: function(uiSourceCode) { this._innerShowFile(uiSourceCode, true); }, _addScrollAndSelectionListeners: function() { console.assert(this._currentFile); var sourceFrame = this._delegate.viewForFile(this._currentFile); sourceFrame.addEventListener(WebInspector.SourceFrame.Events.ScrollChanged, this._scrollChanged, this); sourceFrame.addEventListener(WebInspector.SourceFrame.Events.SelectionChanged, this._selectionChanged, this); }, _removeScrollAndSelectionListeners: function() { if (!this._currentFile) return; var sourceFrame = this._delegate.viewForFile(this._currentFile); sourceFrame.removeEventListener(WebInspector.SourceFrame.Events.ScrollChanged, this._scrollChanged, this); sourceFrame.removeEventListener(WebInspector.SourceFrame.Events.SelectionChanged, this._selectionChanged, this); }, _scrollChanged: function(event) { var lineNumber = (event.data); this._history.updateScrollLineNumber(this._currentFile.url, lineNumber); this._history.save(this._previouslyViewedFilesSetting); }, _selectionChanged: function(event) { var range = (event.data); this._history.updateSelectionRange(this._currentFile.url, range); this._history.save(this._previouslyViewedFilesSetting); }, _innerShowFile: function(uiSourceCode, userGesture) { if (this._currentFile === uiSourceCode) return; this._removeScrollAndSelectionListeners(); this._currentFile = uiSourceCode; var tabId = this._tabIds.get(uiSourceCode) || this._appendFileTab(uiSourceCode, userGesture); this._tabbedPane.selectTab(tabId, userGesture); if (userGesture) this._editorSelectedByUserAction(); this._addScrollAndSelectionListeners(); this.dispatchEventToListeners(WebInspector.TabbedEditorContainer.Events.EditorSelected, this._currentFile); }, _titleForFile: function(uiSourceCode) { const maxDisplayNameLength = 30; const minDisplayQueryParamLength = 5; var title; var parsedURL = uiSourceCode.parsedURL; if (!parsedURL.isValid) title = parsedURL.url ? parsedURL.url.trimMiddle(maxDisplayNameLength) : WebInspector.UIString("(program)"); else { var maxDisplayQueryParamLength = Math.max(minDisplayQueryParamLength, maxDisplayNameLength - parsedURL.lastPathComponent.length); var displayQueryParams = parsedURL.queryParams ? "?" + parsedURL.queryParams.trimEnd(maxDisplayQueryParamLength - 1) : ""; var displayLastPathComponent = parsedURL.lastPathComponent.trimMiddle(maxDisplayNameLength - displayQueryParams.length); var displayName = displayLastPathComponent + displayQueryParams; title = displayName || WebInspector.UIString("(program)"); } if (uiSourceCode.isDirty()) title += "*"; return title; }, addUISourceCode: function(uiSourceCode) { if (this._userSelectedFiles || this._loadedURLs[uiSourceCode.url]) return; this._loadedURLs[uiSourceCode.url] = true; var index = this._history.index(uiSourceCode.url) if (index === -1) return; var tabId = this._tabIds.get(uiSourceCode) || this._appendFileTab(uiSourceCode, false); if (!index) this._innerShowFile(uiSourceCode, true); }, removeUISourceCode: function(uiSourceCode) { this.removeUISourceCodes([uiSourceCode]); }, removeUISourceCodes: function(uiSourceCodes) { var tabIds = []; for (var i = 0; i < uiSourceCodes.length; ++i) { var uiSourceCode = uiSourceCodes[i]; var tabId = this._tabIds.get(uiSourceCode); if (tabId) tabIds.push(tabId); } this._tabbedPane.closeTabs(tabIds); }, _editorClosedByUserAction: function(uiSourceCode) { this._userSelectedFiles = true; this._history.remove(uiSourceCode.url); this._updateHistory(); }, _editorSelectedByUserAction: function() { this._userSelectedFiles = true; this._updateHistory(); }, _updateHistory: function() { var tabIds = this._tabbedPane.lastOpenedTabIds(WebInspector.TabbedEditorContainer.maximalPreviouslyViewedFilesCount); function tabIdToURL(tabId) { return this._files[tabId].url; } this._history.update(tabIds.map(tabIdToURL.bind(this))); this._history.save(this._previouslyViewedFilesSetting); }, _tooltipForFile: function(uiSourceCode) { return uiSourceCode.url; }, _appendFileTab: function(uiSourceCode, userGesture) { var view = this._delegate.viewForFile(uiSourceCode); var title = this._titleForFile(uiSourceCode); var tooltip = this._tooltipForFile(uiSourceCode); var tabId = this._generateTabId(); this._tabIds.put(uiSourceCode, tabId); this._files[tabId] = uiSourceCode; var savedScrollLineNumber = this._history.scrollLineNumber(uiSourceCode.url); if (savedScrollLineNumber) view.scrollToLine(savedScrollLineNumber); var savedSelectionRange = this._history.selectionRange(uiSourceCode.url); if (savedSelectionRange) view.setSelection(savedSelectionRange); this._tabbedPane.appendTab(tabId, title, view, tooltip, userGesture); this._addUISourceCodeListeners(uiSourceCode); return tabId; }, _tabClosed: function(event) { var tabId = (event.data.tabId); var userGesture = (event.data.isUserGesture); var uiSourceCode = this._files[tabId]; if (this._currentFile === uiSourceCode) { this._removeScrollAndSelectionListeners(); delete this._currentFile; } this._tabIds.remove(uiSourceCode); delete this._files[tabId]; this._removeUISourceCodeListeners(uiSourceCode); this.dispatchEventToListeners(WebInspector.TabbedEditorContainer.Events.EditorClosed, uiSourceCode); if (userGesture) this._editorClosedByUserAction(uiSourceCode); }, _tabSelected: function(event) { var tabId = (event.data.tabId); var userGesture = (event.data.isUserGesture); var uiSourceCode = this._files[tabId]; this._innerShowFile(uiSourceCode, userGesture); }, _addUISourceCodeListeners: function(uiSourceCode) { uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._uiSourceCodeWorkingCopyChanged, this); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._uiSourceCodeWorkingCopyCommitted, this); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._uiSourceCodeFormattedChanged, this); }, _removeUISourceCodeListeners: function(uiSourceCode) { uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.TitleChanged, this._uiSourceCodeTitleChanged, this); uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._uiSourceCodeWorkingCopyChanged, this); uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._uiSourceCodeWorkingCopyCommitted, this); uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._uiSourceCodeFormattedChanged, this); }, _updateFileTitle: function(uiSourceCode) { var tabId = this._tabIds.get(uiSourceCode); if (tabId) { var title = this._titleForFile(uiSourceCode); this._tabbedPane.changeTabTitle(tabId, title); } }, _uiSourceCodeTitleChanged: function(event) { var uiSourceCode = (event.target); this._updateFileTitle(uiSourceCode); }, _uiSourceCodeWorkingCopyChanged: function(event) { var uiSourceCode = (event.target); this._updateFileTitle(uiSourceCode); }, _uiSourceCodeWorkingCopyCommitted: function(event) { var uiSourceCode = (event.target); this._updateFileTitle(uiSourceCode); }, _uiSourceCodeFormattedChanged: function(event) { var uiSourceCode = (event.target); this._updateFileTitle(uiSourceCode); }, reset: function() { this._tabbedPane.closeAllTabs(); this._tabIds = new Map(); this._files = {}; delete this._currentFile; delete this._userSelectedFiles; this._loadedURLs = {}; }, _generateTabId: function() { return "tab_" + (WebInspector.TabbedEditorContainer._tabId++); }, currentFile: function() { return this._currentFile; }, __proto__: WebInspector.Object.prototype } WebInspector.TabbedEditorContainer.HistoryItem = function(url, selectionRange, scrollLineNumber) { this.url = url; this.selectionRange = selectionRange; this.scrollLineNumber = scrollLineNumber; } WebInspector.TabbedEditorContainer.HistoryItem.fromObject = function (serializedHistoryItem) { var selectionRange = serializedHistoryItem.selectionRange ? WebInspector.TextRange.fromObject(serializedHistoryItem.selectionRange) : null; return new WebInspector.TabbedEditorContainer.HistoryItem(serializedHistoryItem.url, selectionRange, serializedHistoryItem.scrollLineNumber); } WebInspector.TabbedEditorContainer.HistoryItem.prototype = { serializeToObject: function() { var serializedHistoryItem = {}; serializedHistoryItem.url = this.url; serializedHistoryItem.selectionRange = this.selectionRange; serializedHistoryItem.scrollLineNumber = this.scrollLineNumber; return serializedHistoryItem; }, __proto__: WebInspector.Object.prototype } WebInspector.TabbedEditorContainer.History = function(items) { this._items = items; } WebInspector.TabbedEditorContainer.History.fromObject = function(serializedHistory) { var items = []; for (var i = 0; i < serializedHistory.length; ++i) items.push(WebInspector.TabbedEditorContainer.HistoryItem.fromObject(serializedHistory[i])); return new WebInspector.TabbedEditorContainer.History(items); } WebInspector.TabbedEditorContainer.History.prototype = { index: function(url) { for (var i = 0; i < this._items.length; ++i) { if (this._items[i].url === url) return i; } return -1; }, selectionRange: function(url) { var index = this.index(url); return index !== -1 ? this._items[index].selectionRange : undefined; }, updateSelectionRange: function(url, selectionRange) { if (!selectionRange) return; var index = this.index(url); if (index === -1) return; this._items[index].selectionRange = selectionRange; }, scrollLineNumber: function(url) { var index = this.index(url); return index !== -1 ? this._items[index].scrollLineNumber : undefined; }, updateScrollLineNumber: function(url, scrollLineNumber) { var index = this.index(url); if (index === -1) return; this._items[index].scrollLineNumber = scrollLineNumber; }, update: function(urls) { for (var i = urls.length - 1; i >= 0; --i) { var index = this.index(urls[i]); var item; if (index !== -1) { item = this._items[index]; this._items.splice(index, 1); } else item = new WebInspector.TabbedEditorContainer.HistoryItem(urls[i]); this._items.unshift(item); } }, remove: function(url) { var index = this.index(url); if (index !== -1) this._items.splice(index, 1); }, save: function(setting) { setting.set(this._serializeToObject()); }, _serializeToObject: function() { var serializedHistory = []; for (var i = 0; i < this._items.length; ++i) serializedHistory.push(this._items[i].serializeToObject()); return serializedHistory; }, __proto__: WebInspector.Object.prototype } ; WebInspector.UISourceCodeFrame = function(uiSourceCode) { this._uiSourceCode = uiSourceCode; WebInspector.SourceFrame.call(this, this._uiSourceCode); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._onFormattedChanged, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._onWorkingCopyChanged, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._onWorkingCopyCommitted, this); } WebInspector.UISourceCodeFrame.prototype = { canEditSource: function() { return true; }, commitEditing: function(text) { if (!this._uiSourceCode.isDirty()) return; this._isCommittingEditing = true; this._uiSourceCode.commitWorkingCopy(this._didEditContent.bind(this)); delete this._isCommittingEditing; }, onTextChanged: function(oldRange, newRange) { this._isSettingWorkingCopy = true; this._uiSourceCode.setWorkingCopy(this._textEditor.text()); delete this._isSettingWorkingCopy; }, _didEditContent: function(error) { if (error) { WebInspector.log(error, WebInspector.ConsoleMessage.MessageLevel.Error, true); return; } }, _onFormattedChanged: function(event) { var content = (event.data.content); this._textEditor.setReadOnly(this._uiSourceCode.formatted()); this._innerSetContent(content); }, _onWorkingCopyChanged: function(event) { this._innerSetContent(this._uiSourceCode.workingCopy()); }, _onWorkingCopyCommitted: function(event) { this._innerSetContent(this._uiSourceCode.workingCopy()); }, _innerSetContent: function(content) { if (this._isSettingWorkingCopy || this._isCommittingEditing) return; this.setContent(this._uiSourceCode.content() || "", false, this._uiSourceCode.contentType().canonicalMimeType()); }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { WebInspector.SourceFrame.prototype.populateTextAreaContextMenu.call(this, contextMenu, lineNumber); contextMenu.appendApplicableItems(this._uiSourceCode); contextMenu.appendSeparator(); }, __proto__: WebInspector.SourceFrame.prototype } ; WebInspector.WatchExpressionsSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Watch Expressions")); } WebInspector.WatchExpressionsSidebarPane.prototype = { show: function() { this._visible = true; if (this._wasShown) { this._refreshExpressionsIfNeeded(); return; } this._wasShown = true; this.section = new WebInspector.WatchExpressionsSection(); this.bodyElement.appendChild(this.section.element); var refreshButton = document.createElement("button"); refreshButton.className = "pane-title-button refresh"; refreshButton.addEventListener("click", this._refreshButtonClicked.bind(this), false); refreshButton.title = WebInspector.UIString("Refresh"); this.titleElement.appendChild(refreshButton); var addButton = document.createElement("button"); addButton.className = "pane-title-button add"; addButton.addEventListener("click", this._addButtonClicked.bind(this), false); this.titleElement.appendChild(addButton); addButton.title = WebInspector.UIString("Add watch expression"); this._requiresUpdate = true; if (WebInspector.settings.watchExpressions.get().length > 0) this.expanded = true; }, hide: function() { this._visible = false; }, reset: function() { this.refreshExpressions(); }, refreshExpressions: function() { this._requiresUpdate = true; this._refreshExpressionsIfNeeded(); }, addExpression: function(expression) { this.section.addExpression(expression); this.expanded = true; }, _refreshExpressionsIfNeeded: function() { if (this._requiresUpdate && this._visible) { this.section.update(); delete this._requiresUpdate; } else this._requiresUpdate = true; }, _addButtonClicked: function(event) { event.consume(); this.expanded = true; this.section.addNewExpressionAndEdit(); }, _refreshButtonClicked: function(event) { event.consume(); this.refreshExpressions(); }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.WatchExpressionsSection = function() { this._watchObjectGroupId = "watch-group"; WebInspector.ObjectPropertiesSection.call(this, WebInspector.RemoteObject.fromPrimitiveValue("")); this.treeElementConstructor = WebInspector.WatchedPropertyTreeElement; this._expandedExpressions = {}; this._expandedProperties = {}; this.emptyElement = document.createElement("div"); this.emptyElement.className = "info"; this.emptyElement.textContent = WebInspector.UIString("No Watch Expressions"); this.watchExpressions = WebInspector.settings.watchExpressions.get(); this.headerElement.className = "hidden"; this.editable = true; this.expanded = true; this.propertiesElement.addStyleClass("watch-expressions"); this.element.addEventListener("mousemove", this._mouseMove.bind(this), true); this.element.addEventListener("mouseout", this._mouseOut.bind(this), true); this.element.addEventListener("dblclick", this._sectionDoubleClick.bind(this), false); this.emptyElement.addEventListener("contextmenu", this._emptyElementContextMenu.bind(this), false); } WebInspector.WatchExpressionsSection.NewWatchExpression = "\xA0"; WebInspector.WatchExpressionsSection.prototype = { update: function(e) { if (e) e.consume(); function appendResult(expression, watchIndex, result, wasThrown) { if (!result) return; var property = new WebInspector.RemoteObjectProperty(expression, result); property.watchIndex = watchIndex; property.wasThrown = wasThrown; properties.push(property); if (properties.length == propertyCount) { this.updateProperties(properties, WebInspector.WatchExpressionTreeElement, WebInspector.WatchExpressionsSection.CompareProperties); if (this._newExpressionAdded) { delete this._newExpressionAdded; var treeElement = this.findAddedTreeElement(); if (treeElement) treeElement.startEditing(); } if (this._lastMouseMovePageY) this._updateHoveredElement(this._lastMouseMovePageY); } } RuntimeAgent.releaseObjectGroup(this._watchObjectGroupId) var properties = []; var propertyCount = 0; for (var i = 0; i < this.watchExpressions.length; ++i) { if (!this.watchExpressions[i]) continue; ++propertyCount; } for (var i = 0; i < this.watchExpressions.length; ++i) { var expression = this.watchExpressions[i]; if (!expression) continue; WebInspector.runtimeModel.evaluate(expression, this._watchObjectGroupId, false, true, false, false, appendResult.bind(this, expression, i)); } if (!propertyCount) { if (!this.emptyElement.parentNode) this.element.appendChild(this.emptyElement); } else { if (this.emptyElement.parentNode) this.element.removeChild(this.emptyElement); } this.expanded = (propertyCount != 0); }, addExpression: function(expression) { this.watchExpressions.push(expression); this.saveExpressions(); this.update(); }, addNewExpressionAndEdit: function() { this._newExpressionAdded = true; this.watchExpressions.push(WebInspector.WatchExpressionsSection.NewWatchExpression); this.update(); }, _sectionDoubleClick: function(event) { if (event.target !== this.element && event.target !== this.propertiesElement && event.target !== this.emptyElement) return; event.consume(); this.addNewExpressionAndEdit(); }, updateExpression: function(element, value) { if (value === null) { var index = element.property.watchIndex; this.watchExpressions.splice(index, 1); } else this.watchExpressions[element.property.watchIndex] = value; this.saveExpressions(); this.update(); }, _deleteAllExpressions: function() { this.watchExpressions = []; this.saveExpressions(); this.update(); }, findAddedTreeElement: function() { var children = this.propertiesTreeOutline.children; for (var i = 0; i < children.length; ++i) { if (children[i].property.name === WebInspector.WatchExpressionsSection.NewWatchExpression) return children[i]; } }, saveExpressions: function() { var toSave = []; for (var i = 0; i < this.watchExpressions.length; i++) if (this.watchExpressions[i]) toSave.push(this.watchExpressions[i]); WebInspector.settings.watchExpressions.set(toSave); return toSave.length; }, _mouseMove: function(e) { if (this.propertiesElement.firstChild) this._updateHoveredElement(e.pageY); }, _mouseOut: function() { if (this._hoveredElement) { this._hoveredElement.removeStyleClass("hovered"); delete this._hoveredElement; } delete this._lastMouseMovePageY; }, _updateHoveredElement: function(pageY) { var candidateElement = this.propertiesElement.firstChild; while (true) { var next = candidateElement.nextSibling; while (next && !next.clientHeight) next = next.nextSibling; if (!next || next.totalOffsetTop() > pageY) break; candidateElement = next; } if (this._hoveredElement !== candidateElement) { if (this._hoveredElement) this._hoveredElement.removeStyleClass("hovered"); if (candidateElement) candidateElement.addStyleClass("hovered"); this._hoveredElement = candidateElement; } this._lastMouseMovePageY = pageY; }, _emptyElementContextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString("Add watch expression"), this.addNewExpressionAndEdit.bind(this)); contextMenu.show(); }, __proto__: WebInspector.ObjectPropertiesSection.prototype } WebInspector.WatchExpressionsSection.CompareProperties = function(propertyA, propertyB) { if (propertyA.watchIndex == propertyB.watchIndex) return 0; else if (propertyA.watchIndex < propertyB.watchIndex) return -1; else return 1; } WebInspector.WatchExpressionTreeElement = function(property) { WebInspector.ObjectPropertyTreeElement.call(this, property); } WebInspector.WatchExpressionTreeElement.prototype = { onexpand: function() { WebInspector.ObjectPropertyTreeElement.prototype.onexpand.call(this); this.treeOutline.section._expandedExpressions[this._expression()] = true; }, oncollapse: function() { WebInspector.ObjectPropertyTreeElement.prototype.oncollapse.call(this); delete this.treeOutline.section._expandedExpressions[this._expression()]; }, onattach: function() { WebInspector.ObjectPropertyTreeElement.prototype.onattach.call(this); if (this.treeOutline.section._expandedExpressions[this._expression()]) this.expanded = true; }, _expression: function() { return this.property.name; }, update: function() { WebInspector.ObjectPropertyTreeElement.prototype.update.call(this); if (this.property.wasThrown) { this.valueElement.textContent = WebInspector.UIString("<not available>"); this.listItemElement.addStyleClass("dimmed"); } else this.listItemElement.removeStyleClass("dimmed"); var deleteButton = document.createElement("input"); deleteButton.type = "button"; deleteButton.title = WebInspector.UIString("Delete watch expression."); deleteButton.addStyleClass("enabled-button"); deleteButton.addStyleClass("delete-button"); deleteButton.addEventListener("click", this._deleteButtonClicked.bind(this), false); this.listItemElement.addEventListener("contextmenu", this._contextMenu.bind(this), false); this.listItemElement.insertBefore(deleteButton, this.listItemElement.firstChild); }, populateContextMenu: function(contextMenu) { if (!this.isEditing()) { contextMenu.appendItem(WebInspector.UIString("Add watch expression"), this.treeOutline.section.addNewExpressionAndEdit.bind(this.treeOutline.section)); contextMenu.appendItem(WebInspector.UIString("Delete watch expression"), this._deleteButtonClicked.bind(this)); } if (this.treeOutline.section.watchExpressions.length > 1) contextMenu.appendItem(WebInspector.UIString("Delete all watch expressions"), this._deleteAllButtonClicked.bind(this)); }, _contextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); this.populateContextMenu(contextMenu); contextMenu.show(); }, _deleteAllButtonClicked: function() { this.treeOutline.section._deleteAllExpressions(); }, _deleteButtonClicked: function() { this.treeOutline.section.updateExpression(this, null); }, renderPromptAsBlock: function() { return true; }, elementAndValueToEdit: function(event) { return [this.nameElement, this.property.name.trim()]; }, editingCancelled: function(element, context) { if (!context.elementToEdit.textContent) this.treeOutline.section.updateExpression(this, null); WebInspector.ObjectPropertyTreeElement.prototype.editingCancelled.call(this, element, context); }, applyExpression: function(expression, updateInterface) { expression = expression.trim(); if (!expression) expression = null; this.property.name = expression; this.treeOutline.section.updateExpression(this, expression); }, __proto__: WebInspector.ObjectPropertyTreeElement.prototype } WebInspector.WatchedPropertyTreeElement = function(property) { WebInspector.ObjectPropertyTreeElement.call(this, property); } WebInspector.WatchedPropertyTreeElement.prototype = { onattach: function() { WebInspector.ObjectPropertyTreeElement.prototype.onattach.call(this); if (this.hasChildren && this.propertyPath() in this.treeOutline.section._expandedProperties) this.expand(); }, onexpand: function() { WebInspector.ObjectPropertyTreeElement.prototype.onexpand.call(this); this.treeOutline.section._expandedProperties[this.propertyPath()] = true; }, oncollapse: function() { WebInspector.ObjectPropertyTreeElement.prototype.oncollapse.call(this); delete this.treeOutline.section._expandedProperties[this.propertyPath()]; }, __proto__: WebInspector.ObjectPropertyTreeElement.prototype } ; WebInspector.Worker = function(id, url, shared) { this.id = id; this.url = url; this.shared = shared; } WebInspector.WorkersSidebarPane = function(workerManager) { WebInspector.SidebarPane.call(this, WebInspector.UIString("Workers")); this._enableWorkersCheckbox = new WebInspector.Checkbox( WebInspector.UIString("Pause on start"), "sidebar-label", WebInspector.UIString("Automatically attach to new workers and pause them. Enabling this option will force opening inspector for all new workers.")); this._enableWorkersCheckbox.element.id = "pause-workers-checkbox"; this.bodyElement.appendChild(this._enableWorkersCheckbox.element); this._enableWorkersCheckbox.addEventListener(this._autoattachToWorkersClicked.bind(this)); this._enableWorkersCheckbox.checked = false; if (Preferences.sharedWorkersDebugNote) { var note = this.bodyElement.createChild("div"); note.id = "shared-workers-list"; note.addStyleClass("sidebar-label") note.textContent = Preferences.sharedWorkersDebugNote; } var separator = this.bodyElement.createChild("div", "sidebar-separator"); separator.textContent = WebInspector.UIString("Dedicated worker inspectors"); this._workerListElement = document.createElement("ol"); this._workerListElement.tabIndex = 0; this._workerListElement.addStyleClass("properties-tree"); this._workerListElement.addStyleClass("sidebar-label"); this.bodyElement.appendChild(this._workerListElement); this._idToWorkerItem = {}; this._workerManager = workerManager; workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerAdded, this._workerAdded, this); workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerRemoved, this._workerRemoved, this); workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkersCleared, this._workersCleared, this); } WebInspector.WorkersSidebarPane.prototype = { _workerAdded: function(event) { this._addWorker(event.data.workerId, event.data.url, event.data.inspectorConnected); }, _workerRemoved: function(event) { var workerItem = this._idToWorkerItem[event.data]; delete this._idToWorkerItem[event.data]; workerItem.parentElement.removeChild(workerItem); }, _workersCleared: function(event) { this._idToWorkerItem = {}; this._workerListElement.removeChildren(); }, _addWorker: function(workerId, url, inspectorConnected) { var item = this._workerListElement.createChild("div", "dedicated-worker-item"); var link = item.createChild("a"); link.textContent = url; link.href = "#"; link.target = "_blank"; link.addEventListener("click", this._workerItemClicked.bind(this, workerId), true); this._idToWorkerItem[workerId] = item; }, _workerItemClicked: function(workerId, event) { event.preventDefault(); this._workerManager.openWorkerInspector(workerId); }, _autoattachToWorkersClicked: function(event) { WorkerAgent.setAutoconnectToWorkers(this._enableWorkersCheckbox.checked); }, __proto__: WebInspector.SidebarPane.prototype } ; WebInspector.ScriptsPanel = function(workspaceForTest) { WebInspector.Panel.call(this, "scripts"); this.registerRequiredCSS("scriptsPanel.css"); WebInspector.settings.navigatorWasOnceHidden = WebInspector.settings.createSetting("navigatorWasOnceHidden", false); WebInspector.settings.debuggerSidebarHidden = WebInspector.settings.createSetting("debuggerSidebarHidden", false); this._workspace = workspaceForTest || WebInspector.workspace; function viewGetter() { return this.visibleView; } WebInspector.GoToLineDialog.install(this, viewGetter.bind(this)); var helpSection = WebInspector.shortcutsScreen.section(WebInspector.UIString("Sources Panel")); this.debugToolbar = this._createDebugToolbar(); const initialDebugSidebarWidth = 225; const minimumDebugSidebarWidthPercent = 50; this.createSidebarView(this.element, WebInspector.SidebarView.SidebarPosition.Right, initialDebugSidebarWidth); this.splitView.element.id = "scripts-split-view"; this.splitView.setMinimumSidebarWidth(Preferences.minScriptsSidebarWidth); this.splitView.setMinimumMainWidthPercent(minimumDebugSidebarWidthPercent); this.sidebarElement.appendChild(this.debugToolbar); this.debugSidebarResizeWidgetElement = document.createElement("div"); this.debugSidebarResizeWidgetElement.id = "scripts-debug-sidebar-resizer-widget"; this.splitView.installResizer(this.debugSidebarResizeWidgetElement); const initialNavigatorWidth = 225; const minimumViewsContainerWidthPercent = 50; this.editorView = new WebInspector.SidebarView(WebInspector.SidebarView.SidebarPosition.Left, "scriptsPanelNavigatorSidebarWidth", initialNavigatorWidth); this.editorView.element.tabIndex = 0; this.editorView.setMinimumSidebarWidth(Preferences.minScriptsSidebarWidth); this.editorView.setMinimumMainWidthPercent(minimumViewsContainerWidthPercent); this.editorView.show(this.splitView.mainElement); this._navigator = new WebInspector.ScriptsNavigator(); this._navigator.view.show(this.editorView.sidebarElement); this._editorContainer = new WebInspector.TabbedEditorContainer(this, "previouslyViewedFiles"); this._editorContainer.show(this.editorView.mainElement); this._navigatorController = new WebInspector.NavigatorOverlayController(this.editorView, this._navigator.view, this._editorContainer.view); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ScriptSelected, this._scriptSelected, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.SnippetCreationRequested, this._snippetCreationRequested, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ItemRenamingRequested, this._itemRenamingRequested, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.FileRenamed, this._fileRenamed, this); this._editorContainer.addEventListener(WebInspector.TabbedEditorContainer.Events.EditorSelected, this._editorSelected, this); this._editorContainer.addEventListener(WebInspector.TabbedEditorContainer.Events.EditorClosed, this._editorClosed, this); this.splitView.mainElement.appendChild(this.debugSidebarResizeWidgetElement); this.sidebarPanes = {}; this.sidebarPanes.watchExpressions = new WebInspector.WatchExpressionsSidebarPane(); this.sidebarPanes.callstack = new WebInspector.CallStackSidebarPane(); this.sidebarPanes.scopechain = new WebInspector.ScopeChainSidebarPane(); this.sidebarPanes.jsBreakpoints = new WebInspector.JavaScriptBreakpointsSidebarPane(WebInspector.breakpointManager, this._showSourceLine.bind(this)); this.sidebarPanes.domBreakpoints = WebInspector.domBreakpointsSidebarPane; this.sidebarPanes.xhrBreakpoints = new WebInspector.XHRBreakpointsSidebarPane(); this.sidebarPanes.eventListenerBreakpoints = new WebInspector.EventListenerBreakpointsSidebarPane(); if (InspectorFrontendHost.canInspectWorkers() && !WebInspector.WorkerManager.isWorkerFrontend()) { WorkerAgent.enable(); this.sidebarPanes.workerList = new WebInspector.WorkersSidebarPane(WebInspector.workerManager); } this._debugSidebarContentsElement = document.createElement("div"); this._debugSidebarContentsElement.id = "scripts-debug-sidebar-contents"; this.sidebarElement.appendChild(this._debugSidebarContentsElement); for (var pane in this.sidebarPanes) { if (this.sidebarPanes[pane] === this.sidebarPanes.domBreakpoints) continue; this._debugSidebarContentsElement.appendChild(this.sidebarPanes[pane].element); } this.sidebarPanes.callstack.expanded = true; this.sidebarPanes.scopechain.expanded = true; this.sidebarPanes.jsBreakpoints.expanded = true; this.sidebarPanes.callstack.registerShortcuts(this.registerShortcuts.bind(this)); this.registerShortcuts(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.EvaluateSelectionInConsole, this._evaluateSelectionInConsole.bind(this)); this.registerShortcuts(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.GoToMember, this._showOutlineDialog.bind(this)); this.registerShortcuts(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.ToggleBreakpoint, this._toggleBreakpoint.bind(this)); var panelEnablerHeading = WebInspector.UIString("You need to enable debugging before you can use the Scripts panel."); var panelEnablerDisclaimer = WebInspector.UIString("Enabling debugging will make scripts run slower."); var panelEnablerButton = WebInspector.UIString("Enable Debugging"); this.panelEnablerView = new WebInspector.PanelEnablerView("scripts", panelEnablerHeading, panelEnablerDisclaimer, panelEnablerButton); this.panelEnablerView.addEventListener("enable clicked", this._enableDebugging, this); this.enableToggleButton = new WebInspector.StatusBarButton("", "enable-toggle-status-bar-item"); this.enableToggleButton.addEventListener("click", this._toggleDebugging, this); if (!Capabilities.debuggerCausesRecompilation) this.enableToggleButton.element.addStyleClass("hidden"); this._pauseOnExceptionButton = new WebInspector.StatusBarButton("", "scripts-pause-on-exceptions-status-bar-item", 3); this._pauseOnExceptionButton.addEventListener("click", this._togglePauseOnExceptions, this); this._toggleFormatSourceButton = new WebInspector.StatusBarButton(WebInspector.UIString("Pretty print"), "scripts-toggle-pretty-print-status-bar-item"); this._toggleFormatSourceButton.toggled = false; this._toggleFormatSourceButton.addEventListener("click", this._toggleFormatSource, this); this._scriptViewStatusBarItemsContainer = document.createElement("div"); this._scriptViewStatusBarItemsContainer.style.display = "inline-block"; this._installDebuggerSidebarController(); this._sourceFramesByUISourceCode = new Map(); this._updateDebuggerButtons(); this._pauseOnExceptionStateChanged(); if (WebInspector.debuggerModel.isPaused()) this._debuggerPaused(); WebInspector.settings.pauseOnExceptionStateString.addChangeListener(this._pauseOnExceptionStateChanged, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasEnabled, this._debuggerWasEnabled, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasDisabled, this._debuggerWasDisabled, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.CallFrameSelected, this._callFrameSelected, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ConsoleCommandEvaluatedInSelectedCallFrame, this._consoleCommandEvaluatedInSelectedCallFrame, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ExecutionLineChanged, this._executionLineChanged, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.BreakpointsActiveStateChanged, this._breakpointsActiveStateChanged, this); WebInspector.startBatchUpdate(); var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) this._addUISourceCode(uiSourceCodes[i]); WebInspector.endBatchUpdate(); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.TemporaryUISourceCodeRemoved, this._uiSourceCodeRemoved, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._reset.bind(this), this); WebInspector.advancedSearchController.registerSearchScope(new WebInspector.ScriptsSearchScope(this._workspace)); } WebInspector.ScriptsPanel.prototype = { get statusBarItems() { return [this.enableToggleButton.element, this._pauseOnExceptionButton.element, this._toggleFormatSourceButton.element, this._scriptViewStatusBarItemsContainer]; }, defaultFocusedElement: function() { return this._navigator.view.defaultFocusedElement(); }, get paused() { return this._paused; }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); this._debugSidebarContentsElement.insertBefore(this.sidebarPanes.domBreakpoints.element, this.sidebarPanes.xhrBreakpoints.element); this.sidebarPanes.watchExpressions.show(); this._navigatorController.wasShown(); }, willHide: function() { WebInspector.Panel.prototype.willHide.call(this); WebInspector.closeViewInDrawer(); }, _uiSourceCodeAdded: function(event) { var uiSourceCode = (event.data); this._addUISourceCode(uiSourceCode); }, _addUISourceCode: function(uiSourceCode) { if (this._toggleFormatSourceButton.toggled) uiSourceCode.setFormatted(true); this._navigator.addUISourceCode(uiSourceCode); this._editorContainer.addUISourceCode(uiSourceCode); }, _uiSourceCodeRemoved: function(event) { var uiSourceCode = (event.data); var wasCurrent = uiSourceCode === this._currentUISourceCode; this._editorContainer.removeUISourceCode(uiSourceCode); this._navigator.removeUISourceCode(uiSourceCode); this._removeSourceFrame(uiSourceCode); if (wasCurrent && uiSourceCode.isTemporary) { var newUISourceCode = WebInspector.workspace.uiSourceCodeForURL(uiSourceCode.url); if (newUISourceCode) this._showFile(newUISourceCode); } }, _consoleCommandEvaluatedInSelectedCallFrame: function(event) { this.sidebarPanes.scopechain.update(WebInspector.debuggerModel.selectedCallFrame()); }, _debuggerPaused: function() { var details = WebInspector.debuggerModel.debuggerPausedDetails(); this._paused = true; this._waitingToPause = false; this._stepping = false; this._updateDebuggerButtons(); WebInspector.inspectorView.setCurrentPanel(this); this.sidebarPanes.callstack.update(details.callFrames); if (details.reason === WebInspector.DebuggerModel.BreakReason.DOM) { this.sidebarPanes.domBreakpoints.highlightBreakpoint(details.auxData); function didCreateBreakpointHitStatusMessage(element) { this.sidebarPanes.callstack.setStatus(element); } this.sidebarPanes.domBreakpoints.createBreakpointHitStatusMessage(details.auxData, didCreateBreakpointHitStatusMessage.bind(this)); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.EventListener) { var eventName = details.auxData.eventName; this.sidebarPanes.eventListenerBreakpoints.highlightBreakpoint(details.auxData.eventName); var eventNameForUI = WebInspector.EventListenerBreakpointsSidebarPane.eventNameForUI(eventName); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a \"%s\" Event Listener.", eventNameForUI)); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.XHR) { this.sidebarPanes.xhrBreakpoints.highlightBreakpoint(details.auxData["breakpointURL"]); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a XMLHttpRequest.")); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.Exception) this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on exception: '%s'.", details.auxData.description)); else if (details.reason === WebInspector.DebuggerModel.BreakReason.Assert) this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on assertion.")); else if (details.reason === WebInspector.DebuggerModel.BreakReason.CSPViolation) this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a script blocked due to Content Security Policy directive: \"%s\".", details.auxData["directiveText"])); else { function didGetUILocation(uiLocation) { var breakpoint = WebInspector.breakpointManager.findBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber); if (!breakpoint) return; this.sidebarPanes.jsBreakpoints.highlightBreakpoint(breakpoint); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a JavaScript breakpoint.")); } details.callFrames[0].createLiveLocation(didGetUILocation.bind(this)); } this._showDebuggerSidebar(); this._toggleDebuggerSidebarButton.setEnabled(false); window.focus(); InspectorFrontendHost.bringToFront(); }, _debuggerResumed: function() { this._paused = false; this._waitingToPause = false; this._stepping = false; this._clearInterface(); this._toggleDebuggerSidebarButton.setEnabled(true); }, _debuggerWasEnabled: function() { this._updateDebuggerButtons(); }, _debuggerWasDisabled: function() { this._reset(); }, _reset: function() { delete this.currentQuery; this.searchCanceled(); this._debuggerResumed(); delete this._currentUISourceCode; this._navigator.reset(); this._editorContainer.reset(); this._updateScriptViewStatusBarItems(); this.sidebarPanes.jsBreakpoints.reset(); this.sidebarPanes.watchExpressions.reset(); var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) this._removeSourceFrame(uiSourceCodes[i]); }, get visibleView() { return this._editorContainer.visibleView; }, _updateScriptViewStatusBarItems: function() { this._scriptViewStatusBarItemsContainer.removeChildren(); var sourceFrame = this.visibleView; if (sourceFrame) { var statusBarItems = sourceFrame.statusBarItems() || []; for (var i = 0; i < statusBarItems.length; ++i) this._scriptViewStatusBarItemsContainer.appendChild(statusBarItems[i]); } }, canShowAnchorLocation: function(anchor) { if (WebInspector.debuggerModel.debuggerEnabled() && anchor.uiSourceCode) return true; var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) { if (uiSourceCodes[i].url === anchor.href) { anchor.uiSourceCode = uiSourceCodes[i]; return true; } } return false; }, showAnchorLocation: function(anchor) { this._showSourceLine(anchor.uiSourceCode, anchor.lineNumber); }, showUISourceCode: function(uiSourceCode, lineNumber) { this._showSourceLine(uiSourceCode, lineNumber); }, _showSourceLine: function(uiSourceCode, lineNumber) { var sourceFrame = this._showFile(uiSourceCode); if (typeof lineNumber === "number") sourceFrame.highlightLine(lineNumber); sourceFrame.focus(); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.OpenSourceLink, url: uiSourceCode.url, lineNumber: lineNumber }); }, _showFile: function(uiSourceCode) { var sourceFrame = this._getOrCreateSourceFrame(uiSourceCode); if (this._currentUISourceCode === uiSourceCode) return sourceFrame; this._currentUISourceCode = uiSourceCode; if (this._navigator.isScriptSourceAdded(uiSourceCode)) this._navigator.revealUISourceCode(uiSourceCode); this._editorContainer.showFile(uiSourceCode); this._updateScriptViewStatusBarItems(); return sourceFrame; }, _createSourceFrame: function(uiSourceCode) { var sourceFrame; switch (uiSourceCode.contentType()) { case WebInspector.resourceTypes.Script: if (uiSourceCode.isSnippet && !uiSourceCode.isTemporary) sourceFrame = new WebInspector.SnippetJavaScriptSourceFrame(this, uiSourceCode); else sourceFrame = new WebInspector.JavaScriptSourceFrame(this, uiSourceCode); break; case WebInspector.resourceTypes.Document: sourceFrame = new WebInspector.JavaScriptSourceFrame(this, uiSourceCode); break; case WebInspector.resourceTypes.Stylesheet: default: sourceFrame = new WebInspector.UISourceCodeFrame(uiSourceCode); break; } this._sourceFramesByUISourceCode.put(uiSourceCode, sourceFrame); return sourceFrame; }, _getOrCreateSourceFrame: function(uiSourceCode) { return this._sourceFramesByUISourceCode.get(uiSourceCode) || this._createSourceFrame(uiSourceCode); }, viewForFile: function(uiSourceCode) { return this._getOrCreateSourceFrame(uiSourceCode); }, _removeSourceFrame: function(uiSourceCode) { var sourceFrame = this._sourceFramesByUISourceCode.get(uiSourceCode); if (!sourceFrame) return; this._sourceFramesByUISourceCode.remove(uiSourceCode); sourceFrame.detach(); }, _clearCurrentExecutionLine: function() { if (this._executionSourceFrame) this._executionSourceFrame.clearExecutionLine(); delete this._executionSourceFrame; }, _executionLineChanged: function(event) { var uiLocation = event.data; this._clearCurrentExecutionLine(); if (!uiLocation) return; var sourceFrame = this._getOrCreateSourceFrame(uiLocation.uiSourceCode); sourceFrame.setExecutionLine(uiLocation.lineNumber); this._executionSourceFrame = sourceFrame; }, _revealExecutionLine: function(uiLocation) { var uiSourceCode = uiLocation.uiSourceCode; if (uiSourceCode.isTemporary) { if (this._currentUISourceCode && this._currentUISourceCode.scriptFile() && this._currentUISourceCode.scriptFile().isDivergingFromVM()) return; this._editorContainer.addUISourceCode(uiSourceCode); if (uiSourceCode.formatted() !== this._toggleFormatSourceButton.toggled) uiSourceCode.setFormatted(this._toggleFormatSourceButton.toggled); } var sourceFrame = this._showFile(uiSourceCode); sourceFrame.revealLine(uiLocation.lineNumber); sourceFrame.focus(); }, _callFrameSelected: function(event) { var callFrame = event.data; if (!callFrame) return; this.sidebarPanes.scopechain.update(callFrame); this.sidebarPanes.watchExpressions.refreshExpressions(); this.sidebarPanes.callstack.setSelectedCallFrame(callFrame); callFrame.createLiveLocation(this._revealExecutionLine.bind(this)); }, _editorClosed: function(event) { this._navigatorController.hideNavigatorOverlay(); var uiSourceCode = (event.data); if (this._currentUISourceCode === uiSourceCode) delete this._currentUISourceCode; this._updateScriptViewStatusBarItems(); WebInspector.searchController.resetSearch(); }, _editorSelected: function(event) { var uiSourceCode = (event.data); var sourceFrame = this._showFile(uiSourceCode); this._navigatorController.hideNavigatorOverlay(); sourceFrame.focus(); WebInspector.searchController.resetSearch(); }, _scriptSelected: function(event) { var uiSourceCode = (event.data.uiSourceCode); var sourceFrame = this._showFile(uiSourceCode); this._navigatorController.hideNavigatorOverlay(); if (sourceFrame && event.data.focusSource) sourceFrame.focus(); }, _pauseOnExceptionStateChanged: function() { var pauseOnExceptionsState = WebInspector.settings.pauseOnExceptionStateString.get(); switch (pauseOnExceptionsState) { case WebInspector.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions: this._pauseOnExceptionButton.title = WebInspector.UIString("Don't pause on exceptions.\nClick to Pause on all exceptions."); break; case WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions: this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on all exceptions.\nClick to Pause on uncaught exceptions."); break; case WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions: this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on uncaught exceptions.\nClick to Not pause on exceptions."); break; } this._pauseOnExceptionButton.state = pauseOnExceptionsState; }, _updateDebuggerButtons: function() { if (WebInspector.debuggerModel.debuggerEnabled()) { this.enableToggleButton.title = WebInspector.UIString("Debugging enabled. Click to disable."); this.enableToggleButton.toggled = true; this._pauseOnExceptionButton.visible = true; this.panelEnablerView.detach(); } else { this.enableToggleButton.title = WebInspector.UIString("Debugging disabled. Click to enable."); this.enableToggleButton.toggled = false; this._pauseOnExceptionButton.visible = false; this.panelEnablerView.show(this.element); } if (this._paused) { this._updateButtonTitle(this.pauseButton, WebInspector.UIString("Resume script execution (%s).")) this.pauseButton.addStyleClass("paused"); this.pauseButton.disabled = false; this.stepOverButton.disabled = false; this.stepIntoButton.disabled = false; this.stepOutButton.disabled = false; this.debuggerStatusElement.textContent = WebInspector.UIString("Paused"); } else { this._updateButtonTitle(this.pauseButton, WebInspector.UIString("Pause script execution (%s).")) this.pauseButton.removeStyleClass("paused"); this.pauseButton.disabled = this._waitingToPause; this.stepOverButton.disabled = true; this.stepIntoButton.disabled = true; this.stepOutButton.disabled = true; if (this._waitingToPause) this.debuggerStatusElement.textContent = WebInspector.UIString("Pausing"); else if (this._stepping) this.debuggerStatusElement.textContent = WebInspector.UIString("Stepping"); else this.debuggerStatusElement.textContent = ""; } }, _clearInterface: function() { this.sidebarPanes.callstack.update(null); this.sidebarPanes.scopechain.update(null); this.sidebarPanes.jsBreakpoints.clearBreakpointHighlight(); this.sidebarPanes.domBreakpoints.clearBreakpointHighlight(); this.sidebarPanes.eventListenerBreakpoints.clearBreakpointHighlight(); this.sidebarPanes.xhrBreakpoints.clearBreakpointHighlight(); this._clearCurrentExecutionLine(); this._updateDebuggerButtons(); }, _enableDebugging: function() { this._toggleDebugging(this.panelEnablerView.alwaysEnabled); }, _toggleDebugging: function(optionalAlways) { this._paused = false; this._waitingToPause = false; this._stepping = false; if (WebInspector.debuggerModel.debuggerEnabled()) { WebInspector.settings.debuggerEnabled.set(false); WebInspector.debuggerModel.disableDebugger(); } else { WebInspector.settings.debuggerEnabled.set(!!optionalAlways); WebInspector.debuggerModel.enableDebugger(); } }, _togglePauseOnExceptions: function() { var nextStateMap = {}; var stateEnum = WebInspector.DebuggerModel.PauseOnExceptionsState; nextStateMap[stateEnum.DontPauseOnExceptions] = stateEnum.PauseOnAllExceptions; nextStateMap[stateEnum.PauseOnAllExceptions] = stateEnum.PauseOnUncaughtExceptions; nextStateMap[stateEnum.PauseOnUncaughtExceptions] = stateEnum.DontPauseOnExceptions; WebInspector.settings.pauseOnExceptionStateString.set(nextStateMap[this._pauseOnExceptionButton.state]); }, _togglePause: function() { if (this._paused) { this._paused = false; this._waitingToPause = false; DebuggerAgent.resume(); } else { this._stepping = false; this._waitingToPause = true; DebuggerAgent.pause(); } this._clearInterface(); }, _stepOverClicked: function() { if (!this._paused) return; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepOver(); }, _stepIntoClicked: function() { if (!this._paused) return; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepInto(); }, _stepOutClicked: function() { if (!this._paused) return; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepOut(); }, _toggleBreakpointsClicked: function(event) { WebInspector.debuggerModel.setBreakpointsActive(!WebInspector.debuggerModel.breakpointsActive()); }, _breakpointsActiveStateChanged: function(event) { var active = event.data; this._toggleBreakpointsButton.toggled = active; if (active) { this._toggleBreakpointsButton.title = WebInspector.UIString("Deactivate breakpoints."); WebInspector.inspectorView.element.removeStyleClass("breakpoints-deactivated"); this.sidebarPanes.jsBreakpoints.listElement.removeStyleClass("breakpoints-list-deactivated"); } else { this._toggleBreakpointsButton.title = WebInspector.UIString("Activate breakpoints."); WebInspector.inspectorView.element.addStyleClass("breakpoints-deactivated"); this.sidebarPanes.jsBreakpoints.listElement.addStyleClass("breakpoints-list-deactivated"); } }, _evaluateSelectionInConsole: function() { var selection = window.getSelection(); if (selection.type === "Range" && !selection.isCollapsed) WebInspector.evaluateInConsole(selection.toString()); }, _createDebugToolbar: function() { var debugToolbar = document.createElement("div"); debugToolbar.className = "status-bar"; debugToolbar.id = "scripts-debug-toolbar"; var title, handler; var platformSpecificModifier = WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta; handler = this._togglePause.bind(this); this.pauseButton = this._createButtonAndRegisterShortcuts("scripts-pause", "", handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.PauseContinue); debugToolbar.appendChild(this.pauseButton); title = WebInspector.UIString("Step over next function call (%s)."); handler = this._stepOverClicked.bind(this); this.stepOverButton = this._createButtonAndRegisterShortcuts("scripts-step-over", title, handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOver); debugToolbar.appendChild(this.stepOverButton); title = WebInspector.UIString("Step into next function call (%s)."); handler = this._stepIntoClicked.bind(this); this.stepIntoButton = this._createButtonAndRegisterShortcuts("scripts-step-into", title, handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepInto); debugToolbar.appendChild(this.stepIntoButton); title = WebInspector.UIString("Step out of current function (%s)."); handler = this._stepOutClicked.bind(this); this.stepOutButton = this._createButtonAndRegisterShortcuts("scripts-step-out", title, handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOut); debugToolbar.appendChild(this.stepOutButton); this._toggleBreakpointsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Deactivate breakpoints."), "toggle-breakpoints"); this._toggleBreakpointsButton.toggled = true; this._toggleBreakpointsButton.addEventListener("click", this._toggleBreakpointsClicked, this); debugToolbar.appendChild(this._toggleBreakpointsButton.element); this.debuggerStatusElement = document.createElement("div"); this.debuggerStatusElement.id = "scripts-debugger-status"; debugToolbar.appendChild(this.debuggerStatusElement); return debugToolbar; }, _updateButtonTitle: function(button, buttonTitle) { button.buttonTitle = buttonTitle; var hasShortcuts = button.shortcuts && button.shortcuts.length; if (hasShortcuts) button.title = String.vsprintf(buttonTitle, [button.shortcuts[0].name]); else button.title = buttonTitle; }, _createButtonAndRegisterShortcuts: function(buttonId, buttonTitle, handler, shortcuts) { var button = document.createElement("button"); button.className = "status-bar-item"; button.id = buttonId; button.shortcuts = shortcuts; this._updateButtonTitle(button, buttonTitle); button.disabled = true; button.appendChild(document.createElement("img")); button.addEventListener("click", handler, false); this.registerShortcuts(shortcuts, handler); return button; }, searchCanceled: function() { if (this._searchView) this._searchView.searchCanceled(); delete this._searchView; delete this._searchQuery; }, performSearch: function(query) { WebInspector.searchController.updateSearchMatchesCount(0, this); if (!this.visibleView) return; this.searchCanceled(); this._searchView = this.visibleView; this._searchQuery = query; function finishedCallback(view, searchMatches) { if (!searchMatches) return; WebInspector.searchController.updateSearchMatchesCount(searchMatches, this); view.jumpToNextSearchResult(); WebInspector.searchController.updateCurrentMatchIndex(view.currentSearchResultIndex, this); } this._searchView.performSearch(query, finishedCallback.bind(this)); }, jumpToNextSearchResult: function() { if (!this._searchView) return; if (this._searchView !== this.visibleView) { this.performSearch(this._searchQuery); return; } if (this._searchView.showingLastSearchResult()) this._searchView.jumpToFirstSearchResult(); else this._searchView.jumpToNextSearchResult(); WebInspector.searchController.updateCurrentMatchIndex(this._searchView.currentSearchResultIndex, this); return true; }, jumpToPreviousSearchResult: function() { if (!this._searchView) return false; if (this._searchView !== this.visibleView) { this.performSearch(this._searchQuery); if (this._searchView) this._searchView.jumpToLastSearchResult(); return; } if (this._searchView.showingFirstSearchResult()) this._searchView.jumpToLastSearchResult(); else this._searchView.jumpToPreviousSearchResult(); WebInspector.searchController.updateCurrentMatchIndex(this._searchView.currentSearchResultIndex, this); }, canSearchAndReplace: function() { var view = (this.visibleView); return !!view && view.canEditSource(); }, replaceSelectionWith: function(text) { var view = (this.visibleView); view.replaceSearchMatchWith(text); }, replaceAllWith: function(query, text) { var view = (this.visibleView); view.replaceAllWith(query, text); }, _toggleFormatSource: function() { this._toggleFormatSourceButton.toggled = !this._toggleFormatSourceButton.toggled; var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) uiSourceCodes[i].setFormatted(this._toggleFormatSourceButton.toggled); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.TogglePrettyPrint, enabled: this._toggleFormatSourceButton.toggled, url: this._editorContainer.currentFile().url }); }, addToWatch: function(expression) { this.sidebarPanes.watchExpressions.addExpression(expression); }, _toggleBreakpoint: function() { var sourceFrame = this.visibleView; if (!sourceFrame) return; if (sourceFrame instanceof WebInspector.JavaScriptSourceFrame) { var javaScriptSourceFrame = (sourceFrame); javaScriptSourceFrame.toggleBreakpointOnCurrentLine(); } }, _showOutlineDialog: function() { var uiSourceCode = this._editorContainer.currentFile(); if (!uiSourceCode) return; switch (uiSourceCode.contentType()) { case WebInspector.resourceTypes.Document: case WebInspector.resourceTypes.Script: WebInspector.JavaScriptOutlineDialog.show(this.visibleView, uiSourceCode); break; case WebInspector.resourceTypes.Stylesheet: WebInspector.StyleSheetOutlineDialog.show(this.visibleView, uiSourceCode); break; } }, _installDebuggerSidebarController: function() { this._toggleDebuggerSidebarButton = new WebInspector.StatusBarButton(WebInspector.UIString("Hide debugger"), "scripts-debugger-show-hide-button", 3); this._toggleDebuggerSidebarButton.state = "shown"; this._toggleDebuggerSidebarButton.addEventListener("click", clickHandler, this); function clickHandler() { if (this._toggleDebuggerSidebarButton.state === "shown") this._hideDebuggerSidebar(); else this._showDebuggerSidebar(); } this.editorView.element.appendChild(this._toggleDebuggerSidebarButton.element); if (WebInspector.settings.debuggerSidebarHidden.get()) this._hideDebuggerSidebar(); }, _showDebuggerSidebar: function() { if (this._toggleDebuggerSidebarButton.state === "shown") return; this._toggleDebuggerSidebarButton.state = "shown"; this._toggleDebuggerSidebarButton.title = WebInspector.UIString("Hide debugger"); this.splitView.showSidebarElement(); this.debugSidebarResizeWidgetElement.removeStyleClass("hidden"); WebInspector.settings.debuggerSidebarHidden.set(false); }, _hideDebuggerSidebar: function() { if (this._toggleDebuggerSidebarButton.state === "hidden") return; this._toggleDebuggerSidebarButton.state = "hidden"; this._toggleDebuggerSidebarButton.title = WebInspector.UIString("Show debugger"); this.splitView.hideSidebarElement(); this.debugSidebarResizeWidgetElement.addStyleClass("hidden"); WebInspector.settings.debuggerSidebarHidden.set(true); }, _fileRenamed: function(event) { var uiSourceCode = (event.data.uiSourceCode); var name = (event.data.name); if (!uiSourceCode.isSnippet) return; WebInspector.scriptSnippetModel.renameScriptSnippet(uiSourceCode, name); }, _snippetCreationRequested: function(event) { var uiSourceCode = WebInspector.scriptSnippetModel.createScriptSnippet(); this._showSourceLine(uiSourceCode); var shouldHideNavigator = !this._navigatorController.isNavigatorPinned(); if (this._navigatorController.isNavigatorHidden()) this._navigatorController.showNavigatorOverlay(); this._navigator.rename(uiSourceCode, callback.bind(this)); function callback(committed) { if (shouldHideNavigator) this._navigatorController.hideNavigatorOverlay(); if (!committed) { WebInspector.scriptSnippetModel.deleteScriptSnippet(uiSourceCode); return; } this._showSourceLine(uiSourceCode); } }, _itemRenamingRequested: function(event) { var uiSourceCode = (event.data); var shouldHideNavigator = !this._navigatorController.isNavigatorPinned(); if (this._navigatorController.isNavigatorHidden()) this._navigatorController.showNavigatorOverlay(); this._navigator.rename(uiSourceCode, callback.bind(this)); function callback(committed) { if (shouldHideNavigator && committed) { this._navigatorController.hideNavigatorOverlay(); this._showSourceLine(uiSourceCode); } } }, _showLocalHistory: function(uiSourceCode) { WebInspector.RevisionHistoryView.showHistory(uiSourceCode); }, appendApplicableItems: function(event, contextMenu, target) { this._appendUISourceCodeItems(contextMenu, target); this._appendFunctionItems(contextMenu, target); }, _appendUISourceCodeItems: function(contextMenu, target) { if (!(target instanceof WebInspector.UISourceCode)) return; var uiSourceCode = (target); contextMenu.appendItem(WebInspector.UIString("Local modifications..."), this._showLocalHistory.bind(this, uiSourceCode)); var resource = WebInspector.resourceForURL(uiSourceCode.url); if (resource && resource.request) contextMenu.appendApplicableItems(resource.request); }, _appendFunctionItems: function(contextMenu, target) { if (!(target instanceof WebInspector.RemoteObject)) return; var remoteObject = (target); if (remoteObject.type !== "function") return; function didGetDetails(error, response) { if (error) { console.error(error); return; } WebInspector.inspectorView.showPanelForAnchorNavigation(this); var uiLocation = WebInspector.debuggerModel.rawLocationToUILocation(response.location); this._showSourceLine(uiLocation.uiSourceCode, uiLocation.lineNumber); } function revealFunction() { DebuggerAgent.getFunctionDetails(remoteObject.objectId, didGetDetails.bind(this)); } contextMenu.appendItem(WebInspector.UIString("Show function definition"), revealFunction.bind(this)); }, showGoToSourceDialog: function() { WebInspector.OpenResourceDialog.show(this, this._workspace, this.editorView.mainElement); }, __proto__: WebInspector.Panel.prototype }
JavaScript
(function() { /* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function defineCommonExtensionSymbols(apiPrivate) { if (!apiPrivate.audits) apiPrivate.audits = {}; apiPrivate.audits.Severity = { Info: "info", Warning: "warning", Severe: "severe" }; if (!apiPrivate.console) apiPrivate.console = {}; apiPrivate.console.Severity = { Tip: "tip", Debug: "debug", Log: "log", Warning: "warning", Error: "error" }; if (!apiPrivate.panels) apiPrivate.panels = {}; apiPrivate.panels.SearchAction = { CancelSearch: "cancelSearch", PerformSearch: "performSearch", NextSearchResult: "nextSearchResult", PreviousSearchResult: "previousSearchResult" }; apiPrivate.Events = { AuditStarted: "audit-started-", ButtonClicked: "button-clicked-", ConsoleMessageAdded: "console-message-added", ElementsPanelObjectSelected: "panel-objectSelected-elements", NetworkRequestFinished: "network-request-finished", Reset: "reset", OpenResource: "open-resource", PanelSearch: "panel-search-", Reload: "Reload", ResourceAdded: "resource-added", ResourceContentCommitted: "resource-content-committed", TimelineEventRecorded: "timeline-event-recorded", ViewShown: "view-shown-", ViewHidden: "view-hidden-" }; apiPrivate.Commands = { AddAuditCategory: "addAuditCategory", AddAuditResult: "addAuditResult", AddConsoleMessage: "addConsoleMessage", AddRequestHeaders: "addRequestHeaders", CreatePanel: "createPanel", CreateSidebarPane: "createSidebarPane", CreateStatusBarButton: "createStatusBarButton", EvaluateOnInspectedPage: "evaluateOnInspectedPage", GetConsoleMessages: "getConsoleMessages", GetHAR: "getHAR", GetPageResources: "getPageResources", GetRequestContent: "getRequestContent", GetResourceContent: "getResourceContent", Subscribe: "subscribe", SetOpenResourceHandler: "setOpenResourceHandler", SetResourceContent: "setResourceContent", SetSidebarContent: "setSidebarContent", SetSidebarHeight: "setSidebarHeight", SetSidebarPage: "setSidebarPage", ShowPanel: "showPanel", StopAuditCategoryRun: "stopAuditCategoryRun", Unsubscribe: "unsubscribe", UpdateAuditProgress: "updateAuditProgress", UpdateButton: "updateButton", InspectedURLChanged: "inspectedURLChanged" }; } function injectedExtensionAPI(injectedScriptId) { var apiPrivate = {}; defineCommonExtensionSymbols(apiPrivate); var commands = apiPrivate.Commands; var events = apiPrivate.Events; var userAction = false; // Here and below, all constructors are private to API implementation. // For a public type Foo, if internal fields are present, these are on // a private FooImpl type, an instance of FooImpl is used in a closure // by Foo consutrctor to re-bind publicly exported members to an instance // of Foo. /** * @constructor */ function EventSinkImpl(type, customDispatch) { this._type = type; this._listeners = []; this._customDispatch = customDispatch; } EventSinkImpl.prototype = { addListener: function(callback) { if (typeof callback !== "function") throw "addListener: callback is not a function"; if (this._listeners.length === 0) extensionServer.sendRequest({ command: commands.Subscribe, type: this._type }); this._listeners.push(callback); extensionServer.registerHandler("notify-" + this._type, this._dispatch.bind(this)); }, removeListener: function(callback) { var listeners = this._listeners; for (var i = 0; i < listeners.length; ++i) { if (listeners[i] === callback) { listeners.splice(i, 1); break; } } if (this._listeners.length === 0) extensionServer.sendRequest({ command: commands.Unsubscribe, type: this._type }); }, _fire: function() { var listeners = this._listeners.slice(); for (var i = 0; i < listeners.length; ++i) listeners[i].apply(null, arguments); }, _dispatch: function(request) { if (this._customDispatch) this._customDispatch.call(this, request); else this._fire.apply(this, request.arguments); } } /** * @constructor */ function InspectorExtensionAPI() { this.audits = new Audits(); this.inspectedWindow = new InspectedWindow(); this.panels = new Panels(); this.network = new Network(); defineDeprecatedProperty(this, "webInspector", "resources", "network"); this.timeline = new Timeline(); this.console = new ConsoleAPI(); this.onReset = new EventSink(events.Reset); } /** * @constructor */ InspectorExtensionAPI.prototype = { log: function(message) { extensionServer.sendRequest({ command: commands.Log, message: message }); } } /** * @constructor */ function ConsoleAPI() { this.onMessageAdded = new EventSink(events.ConsoleMessageAdded); } ConsoleAPI.prototype = { getMessages: function(callback) { extensionServer.sendRequest({ command: commands.GetConsoleMessages }, callback); }, addMessage: function(severity, text, url, line) { extensionServer.sendRequest({ command: commands.AddConsoleMessage, severity: severity, text: text, url: url, line: line }); }, get Severity() { return apiPrivate.console.Severity; } } /** * @constructor */ function Network() { function dispatchRequestEvent(message) { var request = message.arguments[1]; request.__proto__ = new Request(message.arguments[0]); this._fire(request); } this.onRequestFinished = new EventSink(events.NetworkRequestFinished, dispatchRequestEvent); defineDeprecatedProperty(this, "network", "onFinished", "onRequestFinished"); this.onNavigated = new EventSink(events.InspectedURLChanged); } Network.prototype = { getHAR: function(callback) { function callbackWrapper(result) { var entries = (result && result.entries) || []; for (var i = 0; i < entries.length; ++i) { entries[i].__proto__ = new Request(entries[i]._requestId); delete entries[i]._requestId; } callback(result); } return extensionServer.sendRequest({ command: commands.GetHAR }, callback && callbackWrapper); }, addRequestHeaders: function(headers) { return extensionServer.sendRequest({ command: commands.AddRequestHeaders, headers: headers, extensionId: window.location.hostname }); } } /** * @constructor */ function RequestImpl(id) { this._id = id; } RequestImpl.prototype = { getContent: function(callback) { function callbackWrapper(response) { callback(response.content, response.encoding); } extensionServer.sendRequest({ command: commands.GetRequestContent, id: this._id }, callback && callbackWrapper); } } /** * @constructor */ function Panels() { var panels = { elements: new ElementsPanel() }; function panelGetter(name) { return panels[name]; } for (var panel in panels) this.__defineGetter__(panel, panelGetter.bind(null, panel)); } Panels.prototype = { create: function(title, icon, page, callback) { var id = "extension-panel-" + extensionServer.nextObjectId(); var request = { command: commands.CreatePanel, id: id, title: title, icon: icon, page: page }; extensionServer.sendRequest(request, callback && callback.bind(this, new ExtensionPanel(id))); }, setOpenResourceHandler: function(callback) { var hadHandler = extensionServer.hasHandler(events.OpenResource); if (!callback) extensionServer.unregisterHandler(events.OpenResource); else { function callbackWrapper(message) { // Allow the panel to show itself when handling the event. userAction = true; try { callback.call(null, new Resource(message.resource), message.lineNumber); } finally { userAction = false; } } extensionServer.registerHandler(events.OpenResource, callbackWrapper); } // Only send command if we either removed an existing handler or added handler and had none before. if (hadHandler === !callback) extensionServer.sendRequest({ command: commands.SetOpenResourceHandler, "handlerPresent": !!callback }); }, get SearchAction() { return apiPrivate.panels.SearchAction; } } /** * @constructor */ function ExtensionViewImpl(id) { this._id = id; function dispatchShowEvent(message) { var frameIndex = message.arguments[0]; this._fire(window.parent.frames[frameIndex]); } this.onShown = new EventSink(events.ViewShown + id, dispatchShowEvent); this.onHidden = new EventSink(events.ViewHidden + id); } /** * @constructor */ function PanelWithSidebarImpl(id) { this._id = id; } PanelWithSidebarImpl.prototype = { createSidebarPane: function(title, callback) { var id = "extension-sidebar-" + extensionServer.nextObjectId(); var request = { command: commands.CreateSidebarPane, panel: this._id, id: id, title: title }; function callbackWrapper() { callback(new ExtensionSidebarPane(id)); } extensionServer.sendRequest(request, callback && callbackWrapper); }, __proto__: ExtensionViewImpl.prototype } /** * @constructor * @extends {PanelWithSidebar} */ function ElementsPanel() { var id = "elements"; PanelWithSidebar.call(this, id); this.onSelectionChanged = new EventSink(events.ElementsPanelObjectSelected); } /** * @constructor * @extends {ExtensionViewImpl} */ function ExtensionPanelImpl(id) { ExtensionViewImpl.call(this, id); this.onSearch = new EventSink(events.PanelSearch + id); } ExtensionPanelImpl.prototype = { createStatusBarButton: function(iconPath, tooltipText, disabled) { var id = "button-" + extensionServer.nextObjectId(); var request = { command: commands.CreateStatusBarButton, panel: this._id, id: id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled }; extensionServer.sendRequest(request); return new Button(id); }, show: function() { if (!userAction) return; var request = { command: commands.ShowPanel, id: this._id }; extensionServer.sendRequest(request); }, __proto__: ExtensionViewImpl.prototype } /** * @constructor * @extends {ExtensionViewImpl} */ function ExtensionSidebarPaneImpl(id) { ExtensionViewImpl.call(this, id); } ExtensionSidebarPaneImpl.prototype = { setHeight: function(height) { extensionServer.sendRequest({ command: commands.SetSidebarHeight, id: this._id, height: height }); }, setExpression: function(expression, rootTitle, evaluateOptions) { var callback = extractCallbackArgument(arguments); var request = { command: commands.SetSidebarContent, id: this._id, expression: expression, rootTitle: rootTitle, evaluateOnPage: true, }; if (typeof evaluateOptions === "object") request.evaluateOptions = evaluateOptions; extensionServer.sendRequest(request, callback); }, setObject: function(jsonObject, rootTitle, callback) { extensionServer.sendRequest({ command: commands.SetSidebarContent, id: this._id, expression: jsonObject, rootTitle: rootTitle }, callback); }, setPage: function(page) { extensionServer.sendRequest({ command: commands.SetSidebarPage, id: this._id, page: page }); } } /** * @constructor */ function ButtonImpl(id) { this._id = id; this.onClicked = new EventSink(events.ButtonClicked + id); } ButtonImpl.prototype = { update: function(iconPath, tooltipText, disabled) { var request = { command: commands.UpdateButton, id: this._id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled }; extensionServer.sendRequest(request); } }; /** * @constructor */ function Audits() { } Audits.prototype = { addCategory: function(displayName, resultCount) { var id = "extension-audit-category-" + extensionServer.nextObjectId(); if (typeof resultCount !== "undefined") console.warn("Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead."); extensionServer.sendRequest({ command: commands.AddAuditCategory, id: id, displayName: displayName, resultCount: resultCount }); return new AuditCategory(id); } } /** * @constructor */ function AuditCategoryImpl(id) { function dispatchAuditEvent(request) { var auditResult = new AuditResult(request.arguments[0]); try { this._fire(auditResult); } catch (e) { console.error("Uncaught exception in extension audit event handler: " + e); auditResult.done(); } } this._id = id; this.onAuditStarted = new EventSink(events.AuditStarted + id, dispatchAuditEvent); } /** * @constructor */ function AuditResultImpl(id) { this._id = id; this.createURL = this._nodeFactory.bind(null, "url"); this.createSnippet = this._nodeFactory.bind(null, "snippet"); this.createText = this._nodeFactory.bind(null, "text"); this.createObject = this._nodeFactory.bind(null, "object"); this.createNode = this._nodeFactory.bind(null, "node"); } AuditResultImpl.prototype = { addResult: function(displayName, description, severity, details) { // shorthand for specifying details directly in addResult(). if (details && !(details instanceof AuditResultNode)) details = new AuditResultNode(details instanceof Array ? details : [details]); var request = { command: commands.AddAuditResult, resultId: this._id, displayName: displayName, description: description, severity: severity, details: details }; extensionServer.sendRequest(request); }, createResult: function() { return new AuditResultNode(Array.prototype.slice.call(arguments)); }, updateProgress: function(worked, totalWork) { extensionServer.sendRequest({ command: commands.UpdateAuditProgress, resultId: this._id, progress: worked / totalWork }); }, done: function() { extensionServer.sendRequest({ command: commands.StopAuditCategoryRun, resultId: this._id }); }, get Severity() { return apiPrivate.audits.Severity; }, createResourceLink: function(url, lineNumber) { return { type: "resourceLink", arguments: [url, lineNumber && lineNumber - 1] }; }, _nodeFactory: function(type) { return { type: type, arguments: Array.prototype.slice.call(arguments, 1) }; } } /** * @constructor */ function AuditResultNode(contents) { this.contents = contents; this.children = []; this.expanded = false; } AuditResultNode.prototype = { addChild: function() { var node = new AuditResultNode(Array.prototype.slice.call(arguments)); this.children.push(node); return node; } }; /** * @constructor */ function InspectedWindow() { function dispatchResourceEvent(message) { this._fire(new Resource(message.arguments[0])); } function dispatchResourceContentEvent(message) { this._fire(new Resource(message.arguments[0]), message.arguments[1]); } this.onResourceAdded = new EventSink(events.ResourceAdded, dispatchResourceEvent); this.onResourceContentCommitted = new EventSink(events.ResourceContentCommitted, dispatchResourceContentEvent); } InspectedWindow.prototype = { reload: function(optionsOrUserAgent) { var options = null; if (typeof optionsOrUserAgent === "object") options = optionsOrUserAgent; else if (typeof optionsOrUserAgent === "string") { options = { userAgent: optionsOrUserAgent }; console.warn("Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. " + "Use inspectedWindow.reload({ userAgent: value}) instead."); } return extensionServer.sendRequest({ command: commands.Reload, options: options }); }, eval: function(expression, evaluateOptions) { var callback = extractCallbackArgument(arguments); function callbackWrapper(result) { callback(result.value, result.isException); } var request = { command: commands.EvaluateOnInspectedPage, expression: expression }; if (typeof evaluateOptions === "object") request.evaluateOptions = evaluateOptions; return extensionServer.sendRequest(request, callback && callbackWrapper); }, getResources: function(callback) { function wrapResource(resourceData) { return new Resource(resourceData); } function callbackWrapper(resources) { callback(resources.map(wrapResource)); } return extensionServer.sendRequest({ command: commands.GetPageResources }, callback && callbackWrapper); } } /** * @constructor */ function ResourceImpl(resourceData) { this._url = resourceData.url this._type = resourceData.type; } ResourceImpl.prototype = { get url() { return this._url; }, get type() { return this._type; }, getContent: function(callback) { function callbackWrapper(response) { callback(response.content, response.encoding); } return extensionServer.sendRequest({ command: commands.GetResourceContent, url: this._url }, callback && callbackWrapper); }, setContent: function(content, commit, callback) { return extensionServer.sendRequest({ command: commands.SetResourceContent, url: this._url, content: content, commit: commit }, callback); } } /** * @constructor */ function TimelineImpl() { this.onEventRecorded = new EventSink(events.TimelineEventRecorded); } /** * @constructor */ function ExtensionServerClient() { this._callbacks = {}; this._handlers = {}; this._lastRequestId = 0; this._lastObjectId = 0; this.registerHandler("callback", this._onCallback.bind(this)); var channel = new MessageChannel(); this._port = channel.port1; this._port.addEventListener("message", this._onMessage.bind(this), false); this._port.start(); window.parent.postMessage("registerExtension", [ channel.port2 ], "*"); } ExtensionServerClient.prototype = { /** * @param {function()=} callback */ sendRequest: function(message, callback) { if (typeof callback === "function") message.requestId = this._registerCallback(callback); return this._port.postMessage(message); }, hasHandler: function(command) { return !!this._handlers[command]; }, registerHandler: function(command, handler) { this._handlers[command] = handler; }, unregisterHandler: function(command) { delete this._handlers[command]; }, nextObjectId: function() { return injectedScriptId + "_" + ++this._lastObjectId; }, _registerCallback: function(callback) { var id = ++this._lastRequestId; this._callbacks[id] = callback; return id; }, _onCallback: function(request) { if (request.requestId in this._callbacks) { var callback = this._callbacks[request.requestId]; delete this._callbacks[request.requestId]; callback(request.result); } }, _onMessage: function(event) { var request = event.data; var handler = this._handlers[request.command]; if (handler) handler.call(this, request); } } function populateInterfaceClass(interface, implementation) { for (var member in implementation) { if (member.charAt(0) === "_") continue; var descriptor = null; // Traverse prototype chain until we find the owner. for (var owner = implementation; owner && !descriptor; owner = owner.__proto__) descriptor = Object.getOwnPropertyDescriptor(owner, member); if (!descriptor) continue; if (typeof descriptor.value === "function") interface[member] = descriptor.value.bind(implementation); else if (typeof descriptor.get === "function") interface.__defineGetter__(member, descriptor.get.bind(implementation)); else Object.defineProperty(interface, member, descriptor); } } function declareInterfaceClass(implConstructor) { return function() { var impl = { __proto__: implConstructor.prototype }; implConstructor.apply(impl, arguments); populateInterfaceClass(this, impl); } } function defineDeprecatedProperty(object, className, oldName, newName) { var warningGiven = false; function getter() { if (!warningGiven) { console.warn(className + "." + oldName + " is deprecated. Use " + className + "." + newName + " instead"); warningGiven = true; } return object[newName]; } object.__defineGetter__(oldName, getter); } function extractCallbackArgument(args) { var lastArgument = args[args.length - 1]; return typeof lastArgument === "function" ? lastArgument : undefined; } var AuditCategory = declareInterfaceClass(AuditCategoryImpl); var AuditResult = declareInterfaceClass(AuditResultImpl); var Button = declareInterfaceClass(ButtonImpl); var EventSink = declareInterfaceClass(EventSinkImpl); var ExtensionPanel = declareInterfaceClass(ExtensionPanelImpl); var ExtensionSidebarPane = declareInterfaceClass(ExtensionSidebarPaneImpl); var PanelWithSidebar = declareInterfaceClass(PanelWithSidebarImpl); var Request = declareInterfaceClass(RequestImpl); var Resource = declareInterfaceClass(ResourceImpl); var Timeline = declareInterfaceClass(TimelineImpl); var extensionServer = new ExtensionServerClient(); return new InspectorExtensionAPI(); } // Default implementation; platforms will override. function buildPlatformExtensionAPI(extensionInfo) { function platformExtensionAPI(coreAPI) { window.webInspector = coreAPI; } return platformExtensionAPI.toString(); } function buildExtensionAPIInjectedScript(extensionInfo) { return "(function(injectedScriptHost, inspectedWindow, injectedScriptId){ " + defineCommonExtensionSymbols.toString() + ";" + injectedExtensionAPI.toString() + ";" + buildPlatformExtensionAPI(extensionInfo) + ";" + "platformExtensionAPI(injectedExtensionAPI(injectedScriptId));" + "return {};" + "})"; } /* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function platformExtensionAPI(coreAPI) { function getTabId() { return tabId; } chrome = window.chrome || {}; // Override chrome.devtools as a workaround for a error-throwing getter being exposed // in extension pages loaded into a non-extension process (only happens for remote client // extensions) var devtools_descriptor = Object.getOwnPropertyDescriptor(chrome, "devtools"); if (!devtools_descriptor || devtools_descriptor.get) Object.defineProperty(chrome, "devtools", { value: {}, enumerable: true }); // Only expose tabId on chrome.devtools.inspectedWindow, not webInspector.inspectedWindow. chrome.devtools.inspectedWindow = {}; chrome.devtools.inspectedWindow.__defineGetter__("tabId", getTabId); chrome.devtools.inspectedWindow.__proto__ = coreAPI.inspectedWindow; chrome.devtools.network = coreAPI.network; chrome.devtools.panels = coreAPI.panels; // default to expose experimental APIs for now. if (extensionInfo.exposeExperimentalAPIs !== false) { chrome.experimental = chrome.experimental || {}; chrome.experimental.devtools = chrome.experimental.devtools || {}; var properties = Object.getOwnPropertyNames(coreAPI); for (var i = 0; i < properties.length; ++i) { var descriptor = Object.getOwnPropertyDescriptor(coreAPI, properties[i]); Object.defineProperty(chrome.experimental.devtools, properties[i], descriptor); } chrome.experimental.devtools.inspectedWindow = chrome.devtools.inspectedWindow; } if (extensionInfo.exposeWebInspectorNamespace) window.webInspector = coreAPI; } var tabId; var extensionInfo = {}; platformExtensionAPI(injectedExtensionAPI("remote-" + window.parent.frames.length)); })();
JavaScript
WebInspector.CSSNamedFlowCollectionsView = function() { WebInspector.SidebarView.call(this, WebInspector.SidebarView.SidebarPosition.Left); this.registerRequiredCSS("cssNamedFlows.css"); this._namedFlows = {}; this._contentNodes = {}; this._regionNodes = {}; this.element.addStyleClass("css-named-flow-collections-view"); this.element.addStyleClass("fill"); this._statusElement = document.createElement("span"); this._statusElement.textContent = WebInspector.UIString("CSS Named Flows"); var sidebarHeader = this._leftElement.createChild("div", "tabbed-pane-header selected sidebar-header") var tab = sidebarHeader.createChild("div", "tabbed-pane-header-tab"); tab.createChild("span", "tabbed-pane-header-tab-title").textContent = WebInspector.UIString("CSS Named Flows"); this._sidebarContentElement = this._leftElement.createChild("div", "sidebar-content outline-disclosure"); this._flowListElement = this._sidebarContentElement.createChild("ol"); this._flowTree = new TreeOutline(this._flowListElement); this._emptyElement = document.createElement("div"); this._emptyElement.addStyleClass("info"); this._emptyElement.textContent = WebInspector.UIString("No CSS Named Flows"); this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.closeableTabs = true; this._tabbedPane.show(this._rightElement); } WebInspector.CSSNamedFlowCollectionsView.prototype = { showInDrawer: function() { WebInspector.showViewInDrawer(this._statusElement, this); }, reset: function() { if (!this._document) return; WebInspector.cssModel.getNamedFlowCollectionAsync(this._document.id, this._resetNamedFlows.bind(this)); }, _setDocument: function(document) { this._document = document; this.reset(); }, _documentUpdated: function(event) { var document = (event.data); this._setDocument(document); }, _setSidebarHasContent: function(hasContent) { if (hasContent) { if (!this._emptyElement.parentNode) return; this._sidebarContentElement.removeChild(this._emptyElement); this._sidebarContentElement.appendChild(this._flowListElement); } else { if (!this._flowListElement.parentNode) return; this._sidebarContentElement.removeChild(this._flowListElement); this._sidebarContentElement.appendChild(this._emptyElement); } }, _appendNamedFlow: function(flow) { var flowHash = this._hashNamedFlow(flow.documentNodeId, flow.name); var flowContainer = { flow: flow, flowHash: flowHash }; for (var i = 0; i < flow.content.length; ++i) this._contentNodes[flow.content[i]] = flowHash; for (var i = 0; i < flow.regions.length; ++i) this._regionNodes[flow.regions[i].nodeId] = flowHash; var flowTreeItem = new WebInspector.FlowTreeElement(flowContainer); flowTreeItem.onselect = this._selectNamedFlowTab.bind(this, flowHash); flowContainer.flowTreeItem = flowTreeItem; this._namedFlows[flowHash] = flowContainer; if (!this._flowTree.children.length) this._setSidebarHasContent(true); this._flowTree.appendChild(flowTreeItem); }, _removeNamedFlow: function(flowHash) { var flowContainer = this._namedFlows[flowHash]; if (this._tabbedPane._tabsById[flowHash]) this._tabbedPane.closeTab(flowHash); this._flowTree.removeChild(flowContainer.flowTreeItem); var flow = flowContainer.flow; for (var i = 0; i < flow.content.length; ++i) delete this._contentNodes[flow.content[i]]; for (var i = 0; i < flow.regions.length; ++i) delete this._regionNodes[flow.regions[i].nodeId]; delete this._namedFlows[flowHash]; if (!this._flowTree.children.length) this._setSidebarHasContent(false); }, _updateNamedFlow: function(flow) { var flowHash = this._hashNamedFlow(flow.documentNodeId, flow.name); var flowContainer = this._namedFlows[flowHash]; if (!flowContainer) return; var oldFlow = flowContainer.flow; flowContainer.flow = flow; for (var i = 0; i < oldFlow.content.length; ++i) delete this._contentNodes[oldFlow.content[i]]; for (var i = 0; i < oldFlow.regions.length; ++i) delete this._regionNodes[oldFlow.regions[i].nodeId]; for (var i = 0; i < flow.content.length; ++i) this._contentNodes[flow.content[i]] = flowHash; for (var i = 0; i < flow.regions.length; ++i) this._regionNodes[flow.regions[i].nodeId] = flowHash; flowContainer.flowTreeItem.setOverset(flow.overset); if (flowContainer.flowView) flowContainer.flowView.flow = flow; }, _resetNamedFlows: function(namedFlowCollection) { for (var flowHash in this._namedFlows) this._removeNamedFlow(flowHash); var namedFlows = namedFlowCollection.namedFlowMap; for (var flowName in namedFlows) this._appendNamedFlow(namedFlows[flowName]); if (!this._flowTree.children.length) this._setSidebarHasContent(false); else this._showNamedFlowForNode(WebInspector.panel("elements").treeOutline.selectedDOMNode()); }, _namedFlowCreated: function(event) { if (event.data.documentNodeId !== this._document.id) return; var flow = (event.data); this._appendNamedFlow(flow); }, _namedFlowRemoved: function(event) { if (event.data.documentNodeId !== this._document.id) return; this._removeNamedFlow(this._hashNamedFlow(event.data.documentNodeId, event.data.flowName)); }, _regionLayoutUpdated: function(event) { if (event.data.documentNodeId !== this._document.id) return; var flow = (event.data); this._updateNamedFlow(flow); }, _hashNamedFlow: function(documentNodeId, flowName) { return documentNodeId + "|" + flowName; }, _showNamedFlow: function(flowHash) { this._selectNamedFlowInSidebar(flowHash); this._selectNamedFlowTab(flowHash); }, _selectNamedFlowInSidebar: function(flowHash) { this._namedFlows[flowHash].flowTreeItem.select(true); }, _selectNamedFlowTab: function(flowHash) { var flowContainer = this._namedFlows[flowHash]; if (this._tabbedPane.selectedTabId === flowHash) return; if (!this._tabbedPane.selectTab(flowHash)) { if (!flowContainer.flowView) flowContainer.flowView = new WebInspector.CSSNamedFlowView(flowContainer.flow); this._tabbedPane.appendTab(flowHash, flowContainer.flow.name, flowContainer.flowView); this._tabbedPane.selectTab(flowHash); } }, _selectedNodeChanged: function(event) { var node = (event.data); this._showNamedFlowForNode(node); }, _tabSelected: function(event) { this._selectNamedFlowInSidebar(event.data.tabId); }, _tabClosed: function(event) { this._namedFlows[event.data.tabId].flowTreeItem.deselect(); }, _showNamedFlowForNode: function(node) { if (!node) return; if (this._regionNodes[node.id]) { this._showNamedFlow(this._regionNodes[node.id]); return; } while (node) { if (this._contentNodes[node.id]) { this._showNamedFlow(this._contentNodes[node.id]); return; } node = node.parentNode; } }, wasShown: function() { WebInspector.SidebarView.prototype.wasShown.call(this); WebInspector.domAgent.requestDocument(this._setDocument.bind(this)); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, this._documentUpdated, this); WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.NamedFlowCreated, this._namedFlowCreated, this); WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.NamedFlowRemoved, this._namedFlowRemoved, this); WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.RegionLayoutUpdated, this._regionLayoutUpdated, this); WebInspector.panel("elements").treeOutline.addEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._selectedNodeChanged, this); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabClosed, this._tabClosed, this); }, willHide: function() { WebInspector.domAgent.removeEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, this._documentUpdated, this); WebInspector.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.NamedFlowCreated, this._namedFlowCreated, this); WebInspector.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.NamedFlowRemoved, this._namedFlowRemoved, this); WebInspector.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.RegionLayoutUpdated, this._regionLayoutUpdated, this); WebInspector.panel("elements").treeOutline.removeEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._selectedNodeChanged, this); this._tabbedPane.removeEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this._tabbedPane.removeEventListener(WebInspector.TabbedPane.EventTypes.TabClosed, this._tabClosed, this); }, __proto__: WebInspector.SidebarView.prototype } WebInspector.FlowTreeElement = function(flowContainer) { var container = document.createElement("div"); container.createChild("div", "selection"); container.createChild("span", "title").createChild("span").textContent = flowContainer.flow.name; TreeElement.call(this, container, flowContainer, false); this._overset = false; this.setOverset(flowContainer.flow.overset); } WebInspector.FlowTreeElement.prototype = { setOverset: function(newOverset) { if (this._overset === newOverset) return; if (newOverset) { this.title.addStyleClass("named-flow-overflow"); this.tooltip = WebInspector.UIString("Overflows."); } else { this.title.removeStyleClass("named-flow-overflow"); this.tooltip = ""; } this._overset = newOverset; }, __proto__: TreeElement.prototype } ; WebInspector.CSSNamedFlowView = function(flow) { WebInspector.View.call(this); this.element.addStyleClass("css-named-flow"); this.element.addStyleClass("outline-disclosure"); this._treeOutline = new TreeOutline(this.element.createChild("ol"), true); this._contentTreeItem = new TreeElement(WebInspector.UIString("content"), null, true); this._treeOutline.appendChild(this._contentTreeItem); this._regionsTreeItem = new TreeElement(WebInspector.UIString("region chain"), null, true); this._regionsTreeItem.expand(); this._treeOutline.appendChild(this._regionsTreeItem); this._flow = flow; var content = flow.content; for (var i = 0; i < content.length; ++i) this._insertContentNode(content[i]); var regions = flow.regions; for (var i = 0; i < regions.length; ++i) this._insertRegion(regions[i]); } WebInspector.CSSNamedFlowView.OversetTypeMessageMap = { empty: "empty", fit: "fit", overset: "overset" } WebInspector.CSSNamedFlowView.prototype = { _createFlowTreeOutline: function(rootDOMNode) { if (!rootDOMNode) return null; var treeOutline = new WebInspector.ElementsTreeOutline(false, false, true); treeOutline.element.addStyleClass("named-flow-element"); treeOutline.setVisible(true); treeOutline.rootDOMNode = rootDOMNode; treeOutline.wireToDomAgent(); WebInspector.domAgent.removeEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, treeOutline._elementsTreeUpdater._documentUpdated, treeOutline._elementsTreeUpdater); return treeOutline; }, _insertContentNode: function(contentNodeId, index) { var treeOutline = this._createFlowTreeOutline(WebInspector.domAgent.nodeForId(contentNodeId)); var treeItem = new TreeElement(treeOutline.element, treeOutline); if (index === undefined) { this._contentTreeItem.appendChild(treeItem); return; } this._contentTreeItem.insertChild(treeItem, index); }, _insertRegion: function(region, index) { var treeOutline = this._createFlowTreeOutline(WebInspector.domAgent.nodeForId(region.nodeId)); treeOutline.element.addStyleClass("region-" + region.regionOverset); var treeItem = new TreeElement(treeOutline.element, treeOutline); var oversetText = WebInspector.UIString(WebInspector.CSSNamedFlowView.OversetTypeMessageMap[region.regionOverset]); treeItem.tooltip = WebInspector.UIString("Region is %s.", oversetText); if (index === undefined) { this._regionsTreeItem.appendChild(treeItem); return; } this._regionsTreeItem.insertChild(treeItem, index); }, get flow() { return this._flow; }, set flow(newFlow) { this._update(newFlow); }, _updateRegionOverset: function(regionTreeItem, newRegionOverset, oldRegionOverset) { var element = regionTreeItem.representedObject.element; element.removeStyleClass("region-" + oldRegionOverset); element.addStyleClass("region-" + newRegionOverset); var oversetText = WebInspector.UIString(WebInspector.CSSNamedFlowView.OversetTypeMessageMap[newRegionOverset]); regionTreeItem.tooltip = WebInspector.UIString("Region is %s." , oversetText); }, _mergeContentNodes: function(oldContent, newContent) { var nodeIdSet = {}; for (var i = 0; i < newContent.length; ++i) nodeIdSet[newContent[i]] = true; var oldContentIndex = 0; var newContentIndex = 0; var contentTreeChildIndex = 0; while(oldContentIndex < oldContent.length || newContentIndex < newContent.length) { if (oldContentIndex === oldContent.length) { this._insertContentNode(newContent[newContentIndex]); ++newContentIndex; continue; } if (newContentIndex === newContent.length) { this._contentTreeItem.removeChildAtIndex(contentTreeChildIndex); ++oldContentIndex; continue; } if (oldContent[oldContentIndex] === newContent[newContentIndex]) { ++oldContentIndex; ++newContentIndex; ++contentTreeChildIndex; continue; } if (nodeIdSet[oldContent[oldContentIndex]]) { this._insertContentNode(newContent[newContentIndex], contentTreeChildIndex); ++newContentIndex; ++contentTreeChildIndex; continue; } this._contentTreeItem.removeChildAtIndex(contentTreeChildIndex); ++oldContentIndex; } }, _mergeRegions: function(oldRegions, newRegions) { var nodeIdSet = {}; for (var i = 0; i < newRegions.length; ++i) nodeIdSet[newRegions[i].nodeId] = true; var oldRegionsIndex = 0; var newRegionsIndex = 0; var regionsTreeChildIndex = 0; while(oldRegionsIndex < oldRegions.length || newRegionsIndex < newRegions.length) { if (oldRegionsIndex === oldRegions.length) { this._insertRegion(newRegions[newRegionsIndex]); ++newRegionsIndex; continue; } if (newRegionsIndex === newRegions.length) { this._regionsTreeItem.removeChildAtIndex(regionsTreeChildIndex); ++oldRegionsIndex; continue; } if (oldRegions[oldRegionsIndex].nodeId === newRegions[newRegionsIndex].nodeId) { if (oldRegions[oldRegionsIndex].regionOverset !== newRegions[newRegionsIndex].regionOverset) this._updateRegionOverset(this._regionsTreeItem.children[regionsTreeChildIndex], newRegions[newRegionsIndex].regionOverset, oldRegions[oldRegionsIndex].regionOverset); ++oldRegionsIndex; ++newRegionsIndex; ++regionsTreeChildIndex; continue; } if (nodeIdSet[oldRegions[oldRegionsIndex].nodeId]) { this._insertRegion(newRegions[newRegionsIndex], regionsTreeChildIndex); ++newRegionsIndex; ++regionsTreeChildIndex; continue; } this._regionsTreeItem.removeChildAtIndex(regionsTreeChildIndex); ++oldRegionsIndex; } }, _update: function(newFlow) { this._mergeContentNodes(this._flow.content, newFlow.content); this._mergeRegions(this._flow.regions, newFlow.regions); this._flow = newFlow; }, __proto__: WebInspector.View.prototype } ; WebInspector.EventListenersSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Event Listeners")); this.bodyElement.addStyleClass("events-pane"); this.sections = []; this.settingsSelectElement = document.createElement("select"); this.settingsSelectElement.className = "select-filter"; var option = document.createElement("option"); option.value = "all"; option.label = WebInspector.UIString("All Nodes"); this.settingsSelectElement.appendChild(option); option = document.createElement("option"); option.value = "selected"; option.label = WebInspector.UIString("Selected Node Only"); this.settingsSelectElement.appendChild(option); var filter = WebInspector.settings.eventListenersFilter.get(); if (filter === "all") this.settingsSelectElement[0].selected = true; else if (filter === "selected") this.settingsSelectElement[1].selected = true; this.settingsSelectElement.addEventListener("click", function(event) { event.consume() }, false); this.settingsSelectElement.addEventListener("change", this._changeSetting.bind(this), false); this.titleElement.appendChild(this.settingsSelectElement); this._linkifier = new WebInspector.Linkifier(); } WebInspector.EventListenersSidebarPane._objectGroupName = "event-listeners-sidebar-pane"; WebInspector.EventListenersSidebarPane.prototype = { update: function(node) { RuntimeAgent.releaseObjectGroup(WebInspector.EventListenersSidebarPane._objectGroupName); this._linkifier.reset(); var body = this.bodyElement; body.removeChildren(); this.sections = []; var self = this; function callback(error, eventListeners) { if (error) return; var selectedNodeOnly = "selected" === WebInspector.settings.eventListenersFilter.get(); var sectionNames = []; var sectionMap = {}; for (var i = 0; i < eventListeners.length; ++i) { var eventListener = eventListeners[i]; if (selectedNodeOnly && (node.id !== eventListener.nodeId)) continue; eventListener.node = WebInspector.domAgent.nodeForId(eventListener.nodeId); delete eventListener.nodeId; if (/^function _inspectorCommandLineAPI_logEvent\(/.test(eventListener.handlerBody.toString())) continue; var type = eventListener.type; var section = sectionMap[type]; if (!section) { section = new WebInspector.EventListenersSection(type, node.id, self._linkifier); sectionMap[type] = section; sectionNames.push(type); self.sections.push(section); } section.addListener(eventListener); } if (sectionNames.length === 0) { var div = document.createElement("div"); div.className = "info"; div.textContent = WebInspector.UIString("No Event Listeners"); body.appendChild(div); return; } sectionNames.sort(); for (var i = 0; i < sectionNames.length; ++i) { var section = sectionMap[sectionNames[i]]; body.appendChild(section.element); } } if (node) node.eventListeners(callback); this._selectedNode = node; }, willHide: function() { delete this._selectedNode; }, _changeSetting: function() { var selectedOption = this.settingsSelectElement[this.settingsSelectElement.selectedIndex]; WebInspector.settings.eventListenersFilter.set(selectedOption.value); this.update(this._selectedNode); }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.EventListenersSection = function(title, nodeId, linkifier) { this.eventListeners = []; this._nodeId = nodeId; this._linkifier = linkifier; WebInspector.PropertiesSection.call(this, title); this.propertiesElement.parentNode.removeChild(this.propertiesElement); delete this.propertiesElement; delete this.propertiesTreeOutline; this._eventBars = document.createElement("div"); this._eventBars.className = "event-bars"; this.element.appendChild(this._eventBars); } WebInspector.EventListenersSection.prototype = { addListener: function(eventListener) { var eventListenerBar = new WebInspector.EventListenerBar(eventListener, this._nodeId, this._linkifier); this._eventBars.appendChild(eventListenerBar.element); }, __proto__: WebInspector.PropertiesSection.prototype } WebInspector.EventListenerBar = function(eventListener, nodeId, linkifier) { WebInspector.ObjectPropertiesSection.call(this, WebInspector.RemoteObject.fromPrimitiveValue("")); this.eventListener = eventListener; this._nodeId = nodeId; this._setNodeTitle(); this._setFunctionSubtitle(linkifier); this.editable = false; this.element.className = "event-bar"; this.headerElement.addStyleClass("source-code"); this.propertiesElement.className = "event-properties properties-tree source-code"; } WebInspector.EventListenerBar.prototype = { update: function() { function updateWithNodeObject(nodeObject) { var properties = []; if (this.eventListener.type) properties.push(WebInspector.RemoteObjectProperty.fromPrimitiveValue("type", this.eventListener.type)); if (typeof this.eventListener.useCapture !== "undefined") properties.push(WebInspector.RemoteObjectProperty.fromPrimitiveValue("useCapture", this.eventListener.useCapture)); if (typeof this.eventListener.isAttribute !== "undefined") properties.push(WebInspector.RemoteObjectProperty.fromPrimitiveValue("isAttribute", this.eventListener.isAttribute)); if (nodeObject) properties.push(new WebInspector.RemoteObjectProperty("node", nodeObject)); if (typeof this.eventListener.handlerBody !== "undefined") properties.push(WebInspector.RemoteObjectProperty.fromPrimitiveValue("listenerBody", this.eventListener.handlerBody)); if (this.eventListener.sourceName) properties.push(WebInspector.RemoteObjectProperty.fromPrimitiveValue("sourceName", this.eventListener.sourceName)); if (this.eventListener.location) properties.push(WebInspector.RemoteObjectProperty.fromPrimitiveValue("lineNumber", this.eventListener.location.lineNumber + 1)); this.updateProperties(properties); } WebInspector.RemoteObject.resolveNode(this.eventListener.node, WebInspector.EventListenersSidebarPane._objectGroupName, updateWithNodeObject.bind(this)); }, _setNodeTitle: function() { var node = this.eventListener.node; if (!node) return; if (node.nodeType() === Node.DOCUMENT_NODE) { this.titleElement.textContent = "document"; return; } if (node.id === this._nodeId) { this.titleElement.textContent = node.appropriateSelectorFor(); return; } this.titleElement.removeChildren(); this.titleElement.appendChild(WebInspector.DOMPresentationUtils.linkifyNodeReference(this.eventListener.node)); }, _setFunctionSubtitle: function(linkifier) { if (this.eventListener.location) { this.subtitleElement.removeChildren(); var urlElement; if (this.eventListener.location.scriptId) urlElement = linkifier.linkifyRawLocation(this.eventListener.location); if (!urlElement) { var url = this.eventListener.sourceName; var lineNumber = this.eventListener.location.lineNumber; var columnNumber = 0; urlElement = linkifier.linkifyLocation(url, lineNumber, columnNumber); } this.subtitleElement.appendChild(urlElement); } else { var match = this.eventListener.handlerBody.match(/function ([^\(]+?)\(/); if (match) this.subtitleElement.textContent = match[1]; else this.subtitleElement.textContent = WebInspector.UIString("(anonymous function)"); } }, __proto__: WebInspector.ObjectPropertiesSection.prototype } ; WebInspector.MetricsSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Metrics")); WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetOrMediaQueryResultChanged, this); WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged, this._styleSheetOrMediaQueryResultChanged, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrModified, this._attributesUpdated, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrRemoved, this._attributesUpdated, this); } WebInspector.MetricsSidebarPane.prototype = { update: function(node) { if (node) this.node = node; this._innerUpdate(); }, _innerUpdate: function() { if (this._isEditingMetrics) return; var node = this.node; if (!node || node.nodeType() !== Node.ELEMENT_NODE) { this.bodyElement.removeChildren(); return; } function callback(style) { if (!style || this.node !== node) return; this._updateMetrics(style); } WebInspector.cssModel.getComputedStyleAsync(node.id, callback.bind(this)); function inlineStyleCallback(style) { if (!style || this.node !== node) return; this.inlineStyle = style; } WebInspector.cssModel.getInlineStylesAsync(node.id, inlineStyleCallback.bind(this)); }, _styleSheetOrMediaQueryResultChanged: function() { this._innerUpdate(); }, _attributesUpdated: function(event) { if (this.node !== event.data.node) return; this._innerUpdate(); }, _getPropertyValueAsPx: function(style, propertyName) { return Number(style.getPropertyValue(propertyName).replace(/px$/, "") || 0); }, _getBox: function(computedStyle, componentName) { var suffix = componentName === "border" ? "-width" : ""; var left = this._getPropertyValueAsPx(computedStyle, componentName + "-left" + suffix); var top = this._getPropertyValueAsPx(computedStyle, componentName + "-top" + suffix); var right = this._getPropertyValueAsPx(computedStyle, componentName + "-right" + suffix); var bottom = this._getPropertyValueAsPx(computedStyle, componentName + "-bottom" + suffix); return { left: left, top: top, right: right, bottom: bottom }; }, _highlightDOMNode: function(showHighlight, mode, event) { event.consume(); var nodeId = showHighlight && this.node ? this.node.id : 0; if (nodeId) { if (this._highlightMode === mode) return; this._highlightMode = mode; WebInspector.domAgent.highlightDOMNode(nodeId, mode); } else { delete this._highlightMode; WebInspector.domAgent.hideDOMNodeHighlight(); } for (var i = 0; this._boxElements && i < this._boxElements.length; ++i) { var element = this._boxElements[i]; if (!nodeId || mode === "all" || element._name === mode) element.style.backgroundColor = element._backgroundColor; else element.style.backgroundColor = ""; } }, _updateMetrics: function(style) { var metricsElement = document.createElement("div"); metricsElement.className = "metrics"; var self = this; function createBoxPartElement(style, name, side, suffix) { var propertyName = (name !== "position" ? name + "-" : "") + side + suffix; var value = style.getPropertyValue(propertyName); if (value === "" || (name !== "position" && value === "0px")) value = "\u2012"; else if (name === "position" && value === "auto") value = "\u2012"; value = value.replace(/px$/, ""); var element = document.createElement("div"); element.className = side; element.textContent = value; element.addEventListener("dblclick", this.startEditing.bind(this, element, name, propertyName, style), false); return element; } function getContentAreaWidthPx(style) { var width = style.getPropertyValue("width").replace(/px$/, ""); if (style.getPropertyValue("box-sizing") === "border-box") { var borderBox = self._getBox(style, "border"); var paddingBox = self._getBox(style, "padding"); width = width - borderBox.left - borderBox.right - paddingBox.left - paddingBox.right; } return width; } function getContentAreaHeightPx(style) { var height = style.getPropertyValue("height").replace(/px$/, ""); if (style.getPropertyValue("box-sizing") === "border-box") { var borderBox = self._getBox(style, "border"); var paddingBox = self._getBox(style, "padding"); height = height - borderBox.top - borderBox.bottom - paddingBox.top - paddingBox.bottom; } return height; } var noMarginDisplayType = { "table-cell": true, "table-column": true, "table-column-group": true, "table-footer-group": true, "table-header-group": true, "table-row": true, "table-row-group": true }; var noPaddingDisplayType = { "table-column": true, "table-column-group": true, "table-footer-group": true, "table-header-group": true, "table-row": true, "table-row-group": true }; var noPositionType = { "static": true }; var boxes = ["content", "padding", "border", "margin", "position"]; var boxColors = [ WebInspector.Color.PageHighlight.Content, WebInspector.Color.PageHighlight.Padding, WebInspector.Color.PageHighlight.Border, WebInspector.Color.PageHighlight.Margin, WebInspector.Color.fromRGBA(0, 0, 0, 0) ]; var boxLabels = [WebInspector.UIString("content"), WebInspector.UIString("padding"), WebInspector.UIString("border"), WebInspector.UIString("margin"), WebInspector.UIString("position")]; var previousBox = null; this._boxElements = []; for (var i = 0; i < boxes.length; ++i) { var name = boxes[i]; if (name === "margin" && noMarginDisplayType[style.getPropertyValue("display")]) continue; if (name === "padding" && noPaddingDisplayType[style.getPropertyValue("display")]) continue; if (name === "position" && noPositionType[style.getPropertyValue("position")]) continue; var boxElement = document.createElement("div"); boxElement.className = name; boxElement._backgroundColor = boxColors[i].toString("original"); boxElement._name = name; boxElement.style.backgroundColor = boxElement._backgroundColor; boxElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, true, name === "position" ? "all" : name), false); this._boxElements.push(boxElement); if (name === "content") { var widthElement = document.createElement("span"); widthElement.textContent = getContentAreaWidthPx(style); widthElement.addEventListener("dblclick", this.startEditing.bind(this, widthElement, "width", "width", style), false); var heightElement = document.createElement("span"); heightElement.textContent = getContentAreaHeightPx(style); heightElement.addEventListener("dblclick", this.startEditing.bind(this, heightElement, "height", "height", style), false); boxElement.appendChild(widthElement); boxElement.appendChild(document.createTextNode(" \u00D7 ")); boxElement.appendChild(heightElement); } else { var suffix = (name === "border" ? "-width" : ""); var labelElement = document.createElement("div"); labelElement.className = "label"; labelElement.textContent = boxLabels[i]; boxElement.appendChild(labelElement); boxElement.appendChild(createBoxPartElement.call(this, style, name, "top", suffix)); boxElement.appendChild(document.createElement("br")); boxElement.appendChild(createBoxPartElement.call(this, style, name, "left", suffix)); if (previousBox) boxElement.appendChild(previousBox); boxElement.appendChild(createBoxPartElement.call(this, style, name, "right", suffix)); boxElement.appendChild(document.createElement("br")); boxElement.appendChild(createBoxPartElement.call(this, style, name, "bottom", suffix)); } previousBox = boxElement; } metricsElement.appendChild(previousBox); metricsElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, false, ""), false); this.bodyElement.removeChildren(); this.bodyElement.appendChild(metricsElement); }, startEditing: function(targetElement, box, styleProperty, computedStyle) { if (WebInspector.isBeingEdited(targetElement)) return; var context = { box: box, styleProperty: styleProperty, computedStyle: computedStyle }; var boundKeyDown = this._handleKeyDown.bind(this, context, styleProperty); context.keyDownHandler = boundKeyDown; targetElement.addEventListener("keydown", boundKeyDown, false); this._isEditingMetrics = true; var config = new WebInspector.EditingConfig(this.editingCommitted.bind(this), this.editingCancelled.bind(this), context); WebInspector.startEditing(targetElement, config); window.getSelection().setBaseAndExtent(targetElement, 0, targetElement, 1); }, _handleKeyDown: function(context, styleProperty, event) { var element = event.currentTarget; function finishHandler(originalValue, replacementString) { this._applyUserInput(element, replacementString, originalValue, context, false); } function customNumberHandler(number) { if (styleProperty !== "margin" && number < 0) number = 0; return number; } WebInspector.handleElementValueModifications(event, element, finishHandler.bind(this), undefined, customNumberHandler); }, editingEnded: function(element, context) { delete this.originalPropertyData; delete this.previousPropertyDataCandidate; element.removeEventListener("keydown", context.keyDownHandler, false); delete this._isEditingMetrics; }, editingCancelled: function(element, context) { if ("originalPropertyData" in this && this.inlineStyle) { if (!this.originalPropertyData) { var pastLastSourcePropertyIndex = this.inlineStyle.pastLastSourcePropertyIndex(); if (pastLastSourcePropertyIndex) this.inlineStyle.allProperties[pastLastSourcePropertyIndex - 1].setText("", false); } else this.inlineStyle.allProperties[this.originalPropertyData.index].setText(this.originalPropertyData.propertyText, false); } this.editingEnded(element, context); this.update(); }, _applyUserInput: function(element, userInput, previousContent, context, commitEditor) { if (!this.inlineStyle) { return this.editingCancelled(element, context); } if (commitEditor && userInput === previousContent) return this.editingCancelled(element, context); if (context.box !== "position" && (!userInput || userInput === "\u2012")) userInput = "0px"; else if (context.box === "position" && (!userInput || userInput === "\u2012")) userInput = "auto"; userInput = userInput.toLowerCase(); if (/^\d+$/.test(userInput)) userInput += "px"; var styleProperty = context.styleProperty; var computedStyle = context.computedStyle; if (computedStyle.getPropertyValue("box-sizing") === "border-box" && (styleProperty === "width" || styleProperty === "height")) { if (!userInput.match(/px$/)) { WebInspector.log("For elements with box-sizing: border-box, only absolute content area dimensions can be applied", WebInspector.ConsoleMessage.MessageLevel.Error, true); return; } var borderBox = this._getBox(computedStyle, "border"); var paddingBox = this._getBox(computedStyle, "padding"); var userValuePx = Number(userInput.replace(/px$/, "")); if (isNaN(userValuePx)) return; if (styleProperty === "width") userValuePx += borderBox.left + borderBox.right + paddingBox.left + paddingBox.right; else userValuePx += borderBox.top + borderBox.bottom + paddingBox.top + paddingBox.bottom; userInput = userValuePx + "px"; } this.previousPropertyDataCandidate = null; var self = this; var callback = function(style) { if (!style) return; self.inlineStyle = style; if (!("originalPropertyData" in self)) self.originalPropertyData = self.previousPropertyDataCandidate; if (typeof self._highlightMode !== "undefined") { WebInspector.domAgent.highlightDOMNode(self.node.id, self._highlightMode); } if (commitEditor) { self.dispatchEventToListeners("metrics edited"); self.update(); } }; var allProperties = this.inlineStyle.allProperties; for (var i = 0; i < allProperties.length; ++i) { var property = allProperties[i]; if (property.name !== context.styleProperty || property.inactive) continue; this.previousPropertyDataCandidate = property; property.setValue(userInput, commitEditor, true, callback); return; } this.inlineStyle.appendProperty(context.styleProperty, userInput, callback); }, editingCommitted: function(element, userInput, previousContent, context) { this.editingEnded(element, context); this._applyUserInput(element, userInput, previousContent, context, true); }, __proto__: WebInspector.SidebarPane.prototype } ; WebInspector.PropertiesSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Properties")); } WebInspector.PropertiesSidebarPane._objectGroupName = "properties-sidebar-pane"; WebInspector.PropertiesSidebarPane.prototype = { update: function(node) { var body = this.bodyElement; if (!node) { body.removeChildren(); this.sections = []; return; } WebInspector.RemoteObject.resolveNode(node, WebInspector.PropertiesSidebarPane._objectGroupName, nodeResolved.bind(this)); function nodeResolved(object) { if (!object) return; function protoList() { var proto = this; var result = {}; var counter = 1; while (proto) { result[counter++] = proto; proto = proto.__proto__; } return result; } object.callFunction(protoList, undefined, nodePrototypesReady.bind(this)); object.release(); } function nodePrototypesReady(object) { if (!object) return; object.getOwnProperties(fillSection.bind(this)); } function fillSection(prototypes) { if (!prototypes) return; var body = this.bodyElement; body.removeChildren(); this.sections = []; for (var i = 0; i < prototypes.length; ++i) { if (!parseInt(prototypes[i].name, 10)) continue; var prototype = prototypes[i].value; var title = prototype.description; if (title.match(/Prototype$/)) title = title.replace(/Prototype$/, ""); var section = new WebInspector.ObjectPropertiesSection(prototype, title); this.sections.push(section); body.appendChild(section.element); } } }, __proto__: WebInspector.SidebarPane.prototype } ; WebInspector.StylesSidebarPane = function(computedStylePane, setPseudoClassCallback) { WebInspector.SidebarPane.call(this, WebInspector.UIString("Styles")); this.settingsSelectElement = document.createElement("select"); this.settingsSelectElement.className = "select-settings"; var option = document.createElement("option"); option.value = WebInspector.Color.Format.Original; option.label = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "As authored" : "As Authored"); this.settingsSelectElement.appendChild(option); option = document.createElement("option"); option.value = WebInspector.Color.Format.HEX; option.label = WebInspector.UIString("Hex Colors"); this.settingsSelectElement.appendChild(option); option = document.createElement("option"); option.value = WebInspector.Color.Format.RGB; option.label = WebInspector.UIString("RGB Colors"); this.settingsSelectElement.appendChild(option); option = document.createElement("option"); option.value = WebInspector.Color.Format.HSL; option.label = WebInspector.UIString("HSL Colors"); this.settingsSelectElement.appendChild(option); var muteEventListener = function(event) { event.consume(true); }; this.settingsSelectElement.addEventListener("click", muteEventListener, true); this.settingsSelectElement.addEventListener("change", this._changeSetting.bind(this), false); this._updateColorFormatFilter(); this.titleElement.appendChild(this.settingsSelectElement); this._elementStateButton = document.createElement("button"); this._elementStateButton.className = "pane-title-button element-state"; this._elementStateButton.title = WebInspector.UIString("Toggle Element State"); this._elementStateButton.addEventListener("click", this._toggleElementStatePane.bind(this), false); this.titleElement.appendChild(this._elementStateButton); var addButton = document.createElement("button"); addButton.className = "pane-title-button add"; addButton.id = "add-style-button-test-id"; addButton.title = WebInspector.UIString("New Style Rule"); addButton.addEventListener("click", this._createNewRule.bind(this), false); this.titleElement.appendChild(addButton); this._computedStylePane = computedStylePane; computedStylePane._stylesSidebarPane = this; this._setPseudoClassCallback = setPseudoClassCallback; this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true); WebInspector.settings.colorFormat.addChangeListener(this._colorFormatSettingChanged.bind(this)); this._createElementStatePane(); this.bodyElement.appendChild(this._elementStatePane); this._sectionsContainer = document.createElement("div"); this.bodyElement.appendChild(this._sectionsContainer); this._spectrumHelper = new WebInspector.SpectrumPopupHelper(); this._linkifier = new WebInspector.Linkifier(new WebInspector.Linkifier.DefaultCSSFormatter()); WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetOrMediaQueryResultChanged, this); WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged, this._styleSheetOrMediaQueryResultChanged, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrModified, this._attributeChanged, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrRemoved, this._attributeChanged, this); WebInspector.settings.showUserAgentStyles.addChangeListener(this._showUserAgentStylesSettingChanged.bind(this)); } WebInspector.StylesSidebarPane.PseudoIdNames = [ "", "first-line", "first-letter", "before", "after", "selection", "", "-webkit-scrollbar", "-webkit-file-upload-button", "-webkit-input-placeholder", "-webkit-slider-thumb", "-webkit-search-cancel-button", "-webkit-search-decoration", "-webkit-search-results-decoration", "-webkit-search-results-button", "-webkit-media-controls-panel", "-webkit-media-controls-play-button", "-webkit-media-controls-mute-button", "-webkit-media-controls-timeline", "-webkit-media-controls-timeline-container", "-webkit-media-controls-volume-slider", "-webkit-media-controls-volume-slider-container", "-webkit-media-controls-current-time-display", "-webkit-media-controls-time-remaining-display", "-webkit-media-controls-seek-back-button", "-webkit-media-controls-seek-forward-button", "-webkit-media-controls-fullscreen-button", "-webkit-media-controls-rewind-button", "-webkit-media-controls-return-to-realtime-button", "-webkit-media-controls-toggle-closed-captions-button", "-webkit-media-controls-status-display", "-webkit-scrollbar-thumb", "-webkit-scrollbar-button", "-webkit-scrollbar-track", "-webkit-scrollbar-track-piece", "-webkit-scrollbar-corner", "-webkit-resizer", "-webkit-inner-spin-button", "-webkit-outer-spin-button" ]; WebInspector.StylesSidebarPane.canonicalPropertyName = function(name) { if (!name || name.length < 9 || name.charAt(0) !== "-") return name; var match = name.match(/(?:-webkit-|-khtml-|-apple-)(.+)/); if (!match) return name; return match[1]; } WebInspector.StylesSidebarPane.createExclamationMark = function(propertyName) { var exclamationElement = document.createElement("img"); exclamationElement.className = "exclamation-mark"; exclamationElement.title = WebInspector.CSSMetadata.cssPropertiesMetainfo.keySet()[propertyName.toLowerCase()] ? WebInspector.UIString("Invalid property value.") : WebInspector.UIString("Unknown property name."); return exclamationElement; } WebInspector.StylesSidebarPane.prototype = { _contextMenuEventFired: function(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendApplicableItems(event.target); contextMenu.show(); }, get _forcedPseudoClasses() { return this.node ? (this.node.getUserProperty("pseudoState") || undefined) : undefined; }, _updateForcedPseudoStateInputs: function() { if (!this.node) return; var nodePseudoState = this._forcedPseudoClasses; if (!nodePseudoState) nodePseudoState = []; var inputs = this._elementStatePane.inputs; for (var i = 0; i < inputs.length; ++i) inputs[i].checked = nodePseudoState.indexOf(inputs[i].state) >= 0; }, update: function(node, forceUpdate) { this._spectrumHelper.hide(); var refresh = false; if (forceUpdate) delete this.node; if (!forceUpdate && (node === this.node)) refresh = true; if (node && node.nodeType() === Node.TEXT_NODE && node.parentNode) node = node.parentNode; if (node && node.nodeType() !== Node.ELEMENT_NODE) node = null; if (node) this.node = node; else node = this.node; this._updateForcedPseudoStateInputs(); if (refresh) this._refreshUpdate(); else this._rebuildUpdate(); }, _refreshUpdate: function(editedSection, forceFetchComputedStyle, userCallback) { if (this._refreshUpdateInProgress) { this._lastNodeForInnerRefresh = this.node; return; } var node = this._validateNode(userCallback); if (!node) return; function computedStyleCallback(computedStyle) { delete this._refreshUpdateInProgress; if (this._lastNodeForInnerRefresh) { delete this._lastNodeForInnerRefresh; this._refreshUpdate(editedSection, forceFetchComputedStyle, userCallback); return; } if (this.node === node && computedStyle) this._innerRefreshUpdate(node, computedStyle, editedSection); if (userCallback) userCallback(); } if (this._computedStylePane.expanded || forceFetchComputedStyle) { this._refreshUpdateInProgress = true; WebInspector.cssModel.getComputedStyleAsync(node.id, computedStyleCallback.bind(this)); } else { this._innerRefreshUpdate(node, null, editedSection); if (userCallback) userCallback(); } }, _rebuildUpdate: function() { if (this._rebuildUpdateInProgress) { this._lastNodeForInnerRebuild = this.node; return; } var node = this._validateNode(); if (!node) return; this._rebuildUpdateInProgress = true; var resultStyles = {}; function stylesCallback(matchedResult) { delete this._rebuildUpdateInProgress; var lastNodeForRebuild = this._lastNodeForInnerRebuild; if (lastNodeForRebuild) { delete this._lastNodeForInnerRebuild; if (lastNodeForRebuild !== this.node) { this._rebuildUpdate(); return; } } if (matchedResult && this.node === node) { resultStyles.matchedCSSRules = matchedResult.matchedCSSRules; resultStyles.pseudoElements = matchedResult.pseudoElements; resultStyles.inherited = matchedResult.inherited; this._innerRebuildUpdate(node, resultStyles); } if (lastNodeForRebuild) { this._rebuildUpdate(); return; } } function inlineCallback(inlineStyle, attributesStyle) { resultStyles.inlineStyle = inlineStyle; resultStyles.attributesStyle = attributesStyle; } function computedCallback(computedStyle) { resultStyles.computedStyle = computedStyle; } if (this._computedStylePane.expanded) WebInspector.cssModel.getComputedStyleAsync(node.id, computedCallback.bind(this)); WebInspector.cssModel.getInlineStylesAsync(node.id, inlineCallback.bind(this)); WebInspector.cssModel.getMatchedStylesAsync(node.id, true, true, stylesCallback.bind(this)); }, _validateNode: function(userCallback) { if (!this.node) { this._sectionsContainer.removeChildren(); this._computedStylePane.bodyElement.removeChildren(); this.sections = {}; if (userCallback) userCallback(); return null; } return this.node; }, _styleSheetOrMediaQueryResultChanged: function() { if (this._userOperation || this._isEditingStyle) return; this._rebuildUpdate(); }, _attributeChanged: function(event) { if (this._isEditingStyle || this._userOperation) return; if (!this._canAffectCurrentStyles(event.data.node)) return; this._rebuildUpdate(); }, _canAffectCurrentStyles: function(node) { return this.node && (this.node === node || node.parentNode === this.node.parentNode || node.isAncestor(this.node)); }, _innerRefreshUpdate: function(node, computedStyle, editedSection) { for (var pseudoId in this.sections) { var styleRules = this._refreshStyleRules(this.sections[pseudoId], computedStyle); var usedProperties = {}; this._markUsedProperties(styleRules, usedProperties); this._refreshSectionsForStyleRules(styleRules, usedProperties, editedSection); } if (computedStyle) this.sections[0][0].rebuildComputedTrace(this.sections[0]); this._nodeStylesUpdatedForTest(node, false); }, _innerRebuildUpdate: function(node, styles) { this._sectionsContainer.removeChildren(); this._computedStylePane.bodyElement.removeChildren(); this._linkifier.reset(); var styleRules = this._rebuildStyleRules(node, styles); var usedProperties = {}; this._markUsedProperties(styleRules, usedProperties); this.sections[0] = this._rebuildSectionsForStyleRules(styleRules, usedProperties, 0, null); var anchorElement = this.sections[0].inheritedPropertiesSeparatorElement; if (styles.computedStyle) this.sections[0][0].rebuildComputedTrace(this.sections[0]); for (var i = 0; i < styles.pseudoElements.length; ++i) { var pseudoElementCSSRules = styles.pseudoElements[i]; styleRules = []; var pseudoId = pseudoElementCSSRules.pseudoId; var entry = { isStyleSeparator: true, pseudoId: pseudoId }; styleRules.push(entry); for (var j = pseudoElementCSSRules.rules.length - 1; j >= 0; --j) { var rule = pseudoElementCSSRules.rules[j]; styleRules.push({ style: rule.style, selectorText: rule.selectorText, media: rule.media, sourceURL: rule.sourceURL, rule: rule, editable: !!(rule.style && rule.style.id) }); } usedProperties = {}; this._markUsedProperties(styleRules, usedProperties); this.sections[pseudoId] = this._rebuildSectionsForStyleRules(styleRules, usedProperties, pseudoId, anchorElement); } this._nodeStylesUpdatedForTest(node, true); }, _nodeStylesUpdatedForTest: function(node, rebuild) { }, _refreshStyleRules: function(sections, computedStyle) { var nodeComputedStyle = computedStyle; var styleRules = []; for (var i = 0; sections && i < sections.length; ++i) { var section = sections[i]; if (section.isBlank) continue; if (section.computedStyle) section.styleRule.style = nodeComputedStyle; var styleRule = { section: section, style: section.styleRule.style, computedStyle: section.computedStyle, rule: section.rule, editable: !!(section.styleRule.style && section.styleRule.style.id), isAttribute: section.styleRule.isAttribute, isInherited: section.styleRule.isInherited }; styleRules.push(styleRule); } return styleRules; }, _rebuildStyleRules: function(node, styles) { var nodeComputedStyle = styles.computedStyle; this.sections = {}; var styleRules = []; function addAttributesStyle() { if (!styles.attributesStyle) return; var attrStyle = { style: styles.attributesStyle, editable: false }; attrStyle.selectorText = node.nodeNameInCorrectCase() + "[" + WebInspector.UIString("Attributes Style") + "]"; styleRules.push(attrStyle); } styleRules.push({ computedStyle: true, selectorText: "", style: nodeComputedStyle, editable: false }); if (styles.inlineStyle && node.nodeType() === Node.ELEMENT_NODE) { var inlineStyle = { selectorText: "element.style", style: styles.inlineStyle, isAttribute: true }; styleRules.push(inlineStyle); } if (styles.matchedCSSRules.length) styleRules.push({ isStyleSeparator: true, text: WebInspector.UIString("Matched CSS Rules") }); var addedAttributesStyle; for (var i = styles.matchedCSSRules.length - 1; i >= 0; --i) { var rule = styles.matchedCSSRules[i]; if (!WebInspector.settings.showUserAgentStyles.get() && (rule.isUser || rule.isUserAgent)) continue; if ((rule.isUser || rule.isUserAgent) && !addedAttributesStyle) { addedAttributesStyle = true; addAttributesStyle(); } styleRules.push({ style: rule.style, selectorText: rule.selectorText, media: rule.media, sourceURL: rule.sourceURL, rule: rule, editable: !!(rule.style && rule.style.id) }); } if (!addedAttributesStyle) addAttributesStyle(); var parentNode = node.parentNode; function insertInheritedNodeSeparator(node) { var entry = {}; entry.isStyleSeparator = true; entry.node = node; styleRules.push(entry); } for (var parentOrdinal = 0; parentOrdinal < styles.inherited.length; ++parentOrdinal) { var parentStyles = styles.inherited[parentOrdinal]; var separatorInserted = false; if (parentStyles.inlineStyle) { if (this._containsInherited(parentStyles.inlineStyle)) { var inlineStyle = { selectorText: WebInspector.UIString("Style Attribute"), style: parentStyles.inlineStyle, isAttribute: true, isInherited: true, parentNode: parentNode }; if (!separatorInserted) { insertInheritedNodeSeparator(parentNode); separatorInserted = true; } styleRules.push(inlineStyle); } } for (var i = parentStyles.matchedCSSRules.length - 1; i >= 0; --i) { var rulePayload = parentStyles.matchedCSSRules[i]; if (!this._containsInherited(rulePayload.style)) continue; var rule = rulePayload; if (!WebInspector.settings.showUserAgentStyles.get() && (rule.isUser || rule.isUserAgent)) continue; if (!separatorInserted) { insertInheritedNodeSeparator(parentNode); separatorInserted = true; } styleRules.push({ style: rule.style, selectorText: rule.selectorText, media: rule.media, sourceURL: rule.sourceURL, rule: rule, isInherited: true, parentNode: parentNode, editable: !!(rule.style && rule.style.id) }); } parentNode = parentNode.parentNode; } return styleRules; }, _markUsedProperties: function(styleRules, usedProperties) { var foundImportantProperties = {}; var propertyToEffectiveRule = {}; for (var i = 0; i < styleRules.length; ++i) { var styleRule = styleRules[i]; if (styleRule.computedStyle || styleRule.isStyleSeparator) continue; if (styleRule.section && styleRule.section.noAffect) continue; styleRule.usedProperties = {}; var style = styleRule.style; var allProperties = style.allProperties; for (var j = 0; j < allProperties.length; ++j) { var property = allProperties[j]; if (!property.isLive || !property.parsedOk) continue; var canonicalName = WebInspector.StylesSidebarPane.canonicalPropertyName(property.name); if (styleRule.isInherited && !WebInspector.CSSMetadata.InheritedProperties[canonicalName]) continue; if (foundImportantProperties.hasOwnProperty(canonicalName)) continue; var isImportant = property.priority.length; if (!isImportant && usedProperties.hasOwnProperty(canonicalName)) continue; if (isImportant) { foundImportantProperties[canonicalName] = true; if (propertyToEffectiveRule.hasOwnProperty(canonicalName)) delete propertyToEffectiveRule[canonicalName].usedProperties[canonicalName]; } styleRule.usedProperties[canonicalName] = true; usedProperties[canonicalName] = true; propertyToEffectiveRule[canonicalName] = styleRule; } } }, _refreshSectionsForStyleRules: function(styleRules, usedProperties, editedSection) { for (var i = 0; i < styleRules.length; ++i) { var styleRule = styleRules[i]; var section = styleRule.section; if (styleRule.computedStyle) { section._usedProperties = usedProperties; section.update(); } else { section._usedProperties = styleRule.usedProperties; section.update(section === editedSection); } } }, _rebuildSectionsForStyleRules: function(styleRules, usedProperties, pseudoId, anchorElement) { var sections = []; var lastWasSeparator = true; for (var i = 0; i < styleRules.length; ++i) { var styleRule = styleRules[i]; if (styleRule.isStyleSeparator) { var separatorElement = document.createElement("div"); separatorElement.className = "sidebar-separator"; if (styleRule.node) { var link = WebInspector.DOMPresentationUtils.linkifyNodeReference(styleRule.node); separatorElement.appendChild(document.createTextNode(WebInspector.UIString("Inherited from") + " ")); separatorElement.appendChild(link); if (!sections.inheritedPropertiesSeparatorElement) sections.inheritedPropertiesSeparatorElement = separatorElement; } else if ("pseudoId" in styleRule) { var pseudoName = WebInspector.StylesSidebarPane.PseudoIdNames[styleRule.pseudoId]; if (pseudoName) separatorElement.textContent = WebInspector.UIString("Pseudo ::%s element", pseudoName); else separatorElement.textContent = WebInspector.UIString("Pseudo element"); } else separatorElement.textContent = styleRule.text; this._sectionsContainer.insertBefore(separatorElement, anchorElement); lastWasSeparator = true; continue; } var computedStyle = styleRule.computedStyle; var editable = styleRule.editable; if (typeof editable === "undefined") editable = true; if (computedStyle) var section = new WebInspector.ComputedStylePropertiesSection(this, styleRule, usedProperties); else { var section = new WebInspector.StylePropertiesSection(this, styleRule, editable, styleRule.isInherited, lastWasSeparator); section._markSelectorMatches(); } section.expanded = true; if (computedStyle) { this._computedStylePane.bodyElement.appendChild(section.element); lastWasSeparator = true; } else { this._sectionsContainer.insertBefore(section.element, anchorElement); lastWasSeparator = false; } sections.push(section); } return sections; }, _containsInherited: function(style) { var properties = style.allProperties; for (var i = 0; i < properties.length; ++i) { var property = properties[i]; if (property.isLive && property.name in WebInspector.CSSMetadata.InheritedProperties) return true; } return false; }, _colorFormatSettingChanged: function(event) { this._updateColorFormatFilter(); for (var pseudoId in this.sections) { var sections = this.sections[pseudoId]; for (var i = 0; i < sections.length; ++i) sections[i].update(true); } }, _updateColorFormatFilter: function() { var selectedIndex = 0; var value = WebInspector.settings.colorFormat.get(); var options = this.settingsSelectElement.options; for (var i = 0; i < options.length; ++i) { if (options[i].value === value) { selectedIndex = i; break; } } this.settingsSelectElement.selectedIndex = selectedIndex; }, _changeSetting: function(event) { var options = this.settingsSelectElement.options; var selectedOption = options[this.settingsSelectElement.selectedIndex]; WebInspector.settings.colorFormat.set(selectedOption.value); }, _createNewRule: function(event) { event.consume(); this.expanded = true; this.addBlankSection().startEditingSelector(); }, addBlankSection: function() { var blankSection = new WebInspector.BlankStylePropertiesSection(this, this.node ? this.node.appropriateSelectorFor(true) : ""); var elementStyleSection = this.sections[0][1]; this._sectionsContainer.insertBefore(blankSection.element, elementStyleSection.element.nextSibling); this.sections[0].splice(2, 0, blankSection); return blankSection; }, removeSection: function(section) { for (var pseudoId in this.sections) { var sections = this.sections[pseudoId]; var index = sections.indexOf(section); if (index === -1) continue; sections.splice(index, 1); if (section.element.parentNode) section.element.parentNode.removeChild(section.element); } }, _toggleElementStatePane: function(event) { event.consume(); if (!this._elementStateButton.hasStyleClass("toggled")) { this.expand(); this._elementStateButton.addStyleClass("toggled"); this._elementStatePane.addStyleClass("expanded"); } else { this._elementStateButton.removeStyleClass("toggled"); this._elementStatePane.removeStyleClass("expanded"); } }, _createElementStatePane: function() { this._elementStatePane = document.createElement("div"); this._elementStatePane.className = "styles-element-state-pane source-code"; var table = document.createElement("table"); var inputs = []; this._elementStatePane.inputs = inputs; function clickListener(event) { var node = this._validateNode(); if (!node) return; this._setPseudoClassCallback(node.id, event.target.state, event.target.checked); } function createCheckbox(state) { var td = document.createElement("td"); var label = document.createElement("label"); var input = document.createElement("input"); input.type = "checkbox"; input.state = state; input.addEventListener("click", clickListener.bind(this), false); inputs.push(input); label.appendChild(input); label.appendChild(document.createTextNode(":" + state)); td.appendChild(label); return td; } var tr = document.createElement("tr"); tr.appendChild(createCheckbox.call(this, "active")); tr.appendChild(createCheckbox.call(this, "hover")); table.appendChild(tr); tr = document.createElement("tr"); tr.appendChild(createCheckbox.call(this, "focus")); tr.appendChild(createCheckbox.call(this, "visited")); table.appendChild(tr); this._elementStatePane.appendChild(table); }, _showUserAgentStylesSettingChanged: function() { this._rebuildUpdate(); }, willHide: function() { this._spectrumHelper.hide(); }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.ComputedStyleSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Computed Style")); var showInheritedCheckbox = new WebInspector.Checkbox(WebInspector.UIString("Show inherited"), "sidebar-pane-subtitle"); this.titleElement.appendChild(showInheritedCheckbox.element); if (WebInspector.settings.showInheritedComputedStyleProperties.get()) { this.bodyElement.addStyleClass("show-inherited"); showInheritedCheckbox.checked = true; } function showInheritedToggleFunction(event) { WebInspector.settings.showInheritedComputedStyleProperties.set(showInheritedCheckbox.checked); if (WebInspector.settings.showInheritedComputedStyleProperties.get()) this.bodyElement.addStyleClass("show-inherited"); else this.bodyElement.removeStyleClass("show-inherited"); } showInheritedCheckbox.addEventListener(showInheritedToggleFunction.bind(this)); } WebInspector.ComputedStyleSidebarPane.prototype = { expand: function() { function callback() { WebInspector.SidebarPane.prototype.expand.call(this); } this._stylesSidebarPane._refreshUpdate(null, true, callback.bind(this)); }, __proto__: WebInspector.SidebarPane.prototype } WebInspector.StylePropertiesSection = function(parentPane, styleRule, editable, isInherited, isFirstSection) { WebInspector.PropertiesSection.call(this, ""); this.element.className = "styles-section matched-styles monospace" + (isFirstSection ? " first-styles-section" : ""); if (styleRule.media) { for (var i = styleRule.media.length - 1; i >= 0; --i) { var media = styleRule.media[i]; var mediaDataElement = this.titleElement.createChild("div", "media"); var mediaText; switch (media.source) { case WebInspector.CSSMedia.Source.LINKED_SHEET: case WebInspector.CSSMedia.Source.INLINE_SHEET: mediaText = "media=\"" + media.text + "\""; break; case WebInspector.CSSMedia.Source.MEDIA_RULE: mediaText = "@media " + media.text; break; case WebInspector.CSSMedia.Source.IMPORT_RULE: mediaText = "@import " + media.text; break; } if (media.sourceURL) { var refElement = mediaDataElement.createChild("div", "subtitle"); var lineNumber = media.sourceLine < 0 ? undefined : media.sourceLine; var anchor = WebInspector.linkifyResourceAsNode(media.sourceURL, lineNumber, "subtitle", media.sourceURL + (isNaN(lineNumber) ? "" : (":" + (lineNumber + 1)))); anchor.preferredPanel = "scripts"; anchor.style.float = "right"; refElement.appendChild(anchor); } var mediaTextElement = mediaDataElement.createChild("span"); mediaTextElement.textContent = mediaText; mediaTextElement.title = media.text; } } var selectorContainer = document.createElement("div"); this._selectorElement = document.createElement("span"); this._selectorElement.textContent = styleRule.selectorText; selectorContainer.appendChild(this._selectorElement); var openBrace = document.createElement("span"); openBrace.textContent = " {"; selectorContainer.appendChild(openBrace); selectorContainer.addEventListener("mousedown", this._handleEmptySpaceMouseDown.bind(this), false); selectorContainer.addEventListener("click", this._handleSelectorContainerClick.bind(this), false); var closeBrace = document.createElement("div"); closeBrace.textContent = "}"; this.element.appendChild(closeBrace); this._selectorElement.addEventListener("click", this._handleSelectorClick.bind(this), false); this.element.addEventListener("mousedown", this._handleEmptySpaceMouseDown.bind(this), false); this.element.addEventListener("click", this._handleEmptySpaceClick.bind(this), false); this._parentPane = parentPane; this.styleRule = styleRule; this.rule = this.styleRule.rule; this.editable = editable; this.isInherited = isInherited; if (this.rule) { if (this.rule.isUserAgent || this.rule.isUser) this.editable = false; this.titleElement.addStyleClass("styles-selector"); } this._usedProperties = styleRule.usedProperties; this._selectorRefElement = document.createElement("div"); this._selectorRefElement.className = "subtitle"; this._selectorRefElement.appendChild(this._createRuleOriginNode()); selectorContainer.insertBefore(this._selectorRefElement, selectorContainer.firstChild); this.titleElement.appendChild(selectorContainer); this._selectorContainer = selectorContainer; if (isInherited) this.element.addStyleClass("show-inherited"); if (!this.editable) this.element.addStyleClass("read-only"); } WebInspector.StylePropertiesSection.prototype = { get pane() { return this._parentPane; }, collapse: function(dontRememberState) { }, isPropertyInherited: function(propertyName) { if (this.isInherited) { return !(propertyName in WebInspector.CSSMetadata.InheritedProperties); } return false; }, isPropertyOverloaded: function(propertyName, isShorthand) { if (!this._usedProperties || this.noAffect) return false; if (this.isInherited && !(propertyName in WebInspector.CSSMetadata.InheritedProperties)) { return false; } var canonicalName = WebInspector.StylesSidebarPane.canonicalPropertyName(propertyName); var used = (canonicalName in this._usedProperties); if (used || !isShorthand) return !used; var longhandProperties = this.styleRule.style.longhandProperties(propertyName); for (var j = 0; j < longhandProperties.length; ++j) { var individualProperty = longhandProperties[j]; if (WebInspector.StylesSidebarPane.canonicalPropertyName(individualProperty.name) in this._usedProperties) return false; } return true; }, nextEditableSibling: function() { var curSection = this; do { curSection = curSection.nextSibling; } while (curSection && !curSection.editable); if (!curSection) { curSection = this.firstSibling; while (curSection && !curSection.editable) curSection = curSection.nextSibling; } return (curSection && curSection.editable) ? curSection : null; }, previousEditableSibling: function() { var curSection = this; do { curSection = curSection.previousSibling; } while (curSection && !curSection.editable); if (!curSection) { curSection = this.lastSibling; while (curSection && !curSection.editable) curSection = curSection.previousSibling; } return (curSection && curSection.editable) ? curSection : null; }, update: function(full) { if (this.styleRule.selectorText) this._selectorElement.textContent = this.styleRule.selectorText; this._markSelectorMatches(); if (full) { this.propertiesTreeOutline.removeChildren(); this.populated = false; } else { var child = this.propertiesTreeOutline.children[0]; while (child) { child.overloaded = this.isPropertyOverloaded(child.name, child.isShorthand); child = child.traverseNextTreeElement(false, null, true); } } this.afterUpdate(); }, afterUpdate: function() { if (this._afterUpdate) { this._afterUpdate(this); delete this._afterUpdate; } }, onpopulate: function() { var style = this.styleRule.style; var allProperties = style.allProperties; this.uniqueProperties = []; var styleHasEditableSource = this.editable && !!style.range; if (styleHasEditableSource) { for (var i = 0; i < allProperties.length; ++i) { var property = allProperties[i]; this.uniqueProperties.push(property); if (property.styleBased) continue; var isShorthand = !!WebInspector.CSSMetadata.cssPropertiesMetainfo.longhands(property.name); var inherited = this.isPropertyInherited(property.name); var overloaded = property.inactive || this.isPropertyOverloaded(property.name); var item = new WebInspector.StylePropertyTreeElement(this, this._parentPane, this.styleRule, style, property, isShorthand, inherited, overloaded); this.propertiesTreeOutline.appendChild(item); } return; } var generatedShorthands = {}; for (var i = 0; i < allProperties.length; ++i) { var property = allProperties[i]; this.uniqueProperties.push(property); var isShorthand = !!WebInspector.CSSMetadata.cssPropertiesMetainfo.longhands(property.name); var shorthands = isShorthand ? null : WebInspector.CSSMetadata.cssPropertiesMetainfo.shorthands(property.name); var shorthandPropertyAvailable = false; for (var j = 0; shorthands && !shorthandPropertyAvailable && j < shorthands.length; ++j) { var shorthand = shorthands[j]; if (shorthand in generatedShorthands) { shorthandPropertyAvailable = true; continue; } if (style.getLiveProperty(shorthand)) { shorthandPropertyAvailable = true; continue; } if (!style.shorthandValue(shorthand)) { shorthandPropertyAvailable = false; continue; } var shorthandProperty = new WebInspector.CSSProperty(style, style.allProperties.length, shorthand, style.shorthandValue(shorthand), "", "style", true, true, undefined); var overloaded = property.inactive || this.isPropertyOverloaded(property.name, true); var item = new WebInspector.StylePropertyTreeElement(this, this._parentPane, this.styleRule, style, shorthandProperty, true, false, overloaded); this.propertiesTreeOutline.appendChild(item); generatedShorthands[shorthand] = shorthandProperty; shorthandPropertyAvailable = true; } if (shorthandPropertyAvailable) continue; var inherited = this.isPropertyInherited(property.name); var overloaded = property.inactive || this.isPropertyOverloaded(property.name, isShorthand); var item = new WebInspector.StylePropertyTreeElement(this, this._parentPane, this.styleRule, style, property, isShorthand, inherited, overloaded); this.propertiesTreeOutline.appendChild(item); } }, findTreeElementWithName: function(name) { var treeElement = this.propertiesTreeOutline.children[0]; while (treeElement) { if (treeElement.name === name) return treeElement; treeElement = treeElement.traverseNextTreeElement(true, null, true); } return null; }, _markSelectorMatches: function() { var rule = this.styleRule.rule; if (!rule) return; var matchingSelectors = rule.matchingSelectors; if (this.noAffect || matchingSelectors) this._selectorElement.className = "selector"; if (!matchingSelectors) return; var selectors = rule.selectors; var fragment = document.createDocumentFragment(); var currentMatch = 0; for (var i = 0, lastSelectorIndex = selectors.length - 1; i <= lastSelectorIndex ; ++i) { var selectorNode; var textNode = document.createTextNode(selectors[i]); if (matchingSelectors[currentMatch] === i) { ++currentMatch; selectorNode = document.createElement("span"); selectorNode.className = "selector-matches"; selectorNode.appendChild(textNode); } else selectorNode = textNode; fragment.appendChild(selectorNode); if (i !== lastSelectorIndex) fragment.appendChild(document.createTextNode(", ")); } this._selectorElement.removeChildren(); this._selectorElement.appendChild(fragment); }, _checkWillCancelEditing: function() { var willCauseCancelEditing = this._willCauseCancelEditing; delete this._willCauseCancelEditing; return willCauseCancelEditing; }, _handleSelectorContainerClick: function(event) { if (this._checkWillCancelEditing() || !this.editable) return; if (event.target === this._selectorContainer) this.addNewBlankProperty(0).startEditing(); }, addNewBlankProperty: function(index) { var style = this.styleRule.style; var property = style.newBlankProperty(index); var item = new WebInspector.StylePropertyTreeElement(this, this._parentPane, this.styleRule, style, property, false, false, false); index = property.index; this.propertiesTreeOutline.insertChild(item, index); item.listItemElement.textContent = ""; item._newProperty = true; item.updateTitle(); return item; }, _createRuleOriginNode: function() { function linkifyUncopyable(url, line) { var link = WebInspector.linkifyResourceAsNode(url, line, "", url + ":" + (line + 1)); link.preferredPanel = "scripts"; link.classList.add("webkit-html-resource-link"); link.setAttribute("data-uncopyable", link.textContent); link.textContent = ""; return link; } if (this.styleRule.sourceURL) return this._parentPane._linkifier.linkifyCSSRuleLocation(this.rule) || linkifyUncopyable(this.styleRule.sourceURL, this.rule.sourceLine); if (!this.rule) return document.createTextNode(""); var origin = ""; if (this.rule.isUserAgent) return document.createTextNode(WebInspector.UIString("user agent stylesheet")); if (this.rule.isUser) return document.createTextNode(WebInspector.UIString("user stylesheet")); if (this.rule.isViaInspector) { var element = document.createElement("span"); function callback(resource) { if (resource) element.appendChild(linkifyUncopyable(resource.url, this.rule.sourceLine)); else element.textContent = WebInspector.UIString("via inspector"); } WebInspector.cssModel.getViaInspectorResourceForRule(this.rule, callback.bind(this)); return element; } }, _handleEmptySpaceMouseDown: function(event) { this._willCauseCancelEditing = this._parentPane._isEditingStyle; }, _handleEmptySpaceClick: function(event) { if (!this.editable) return; if (!window.getSelection().isCollapsed) return; if (this._checkWillCancelEditing()) return; if (event.target.hasStyleClass("header") || this.element.hasStyleClass("read-only") || event.target.enclosingNodeOrSelfWithClass("media")) { event.consume(); return; } this.expand(); this.addNewBlankProperty().startEditing(); }, _handleSelectorClick: function(event) { this._startEditingOnMouseEvent(); event.consume(true); }, _startEditingOnMouseEvent: function() { if (!this.editable) return; if (!this.rule && this.propertiesTreeOutline.children.length === 0) { this.expand(); this.addNewBlankProperty().startEditing(); return; } if (!this.rule) return; this.startEditingSelector(); }, startEditingSelector: function() { var element = this._selectorElement; if (WebInspector.isBeingEdited(element)) return; element.scrollIntoViewIfNeeded(false); element.textContent = element.textContent; var config = new WebInspector.EditingConfig(this.editingSelectorCommitted.bind(this), this.editingSelectorCancelled.bind(this)); WebInspector.startEditing(this._selectorElement, config); window.getSelection().setBaseAndExtent(element, 0, element, 1); }, _moveEditorFromSelector: function(moveDirection) { this._markSelectorMatches(); if (!moveDirection) return; if (moveDirection === "forward") { this.expand(); var firstChild = this.propertiesTreeOutline.children[0]; while (firstChild && firstChild.inherited) firstChild = firstChild.nextSibling; if (!firstChild) this.addNewBlankProperty().startEditing(); else firstChild.startEditing(firstChild.nameElement); } else { var previousSection = this.previousEditableSibling(); if (!previousSection) return; previousSection.expand(); previousSection.addNewBlankProperty().startEditing(); } }, editingSelectorCommitted: function(element, newContent, oldContent, context, moveDirection) { if (newContent) newContent = newContent.trim(); if (newContent === oldContent) { this._selectorElement.textContent = newContent; return this._moveEditorFromSelector(moveDirection); } var selectedNode = this._parentPane.node; function successCallback(newRule, doesAffectSelectedNode) { if (!doesAffectSelectedNode) { this.noAffect = true; this.element.addStyleClass("no-affect"); } else { delete this.noAffect; this.element.removeStyleClass("no-affect"); } this.rule = newRule; this.styleRule = { section: this, style: newRule.style, selectorText: newRule.selectorText, media: newRule.media, sourceURL: newRule.sourceURL, rule: newRule }; this._parentPane.update(selectedNode); finishOperationAndMoveEditor.call(this, moveDirection); } function finishOperationAndMoveEditor(direction) { delete this._parentPane._userOperation; this._moveEditorFromSelector(direction); } this._parentPane._userOperation = true; WebInspector.cssModel.setRuleSelector(this.rule.id, selectedNode ? selectedNode.id : 0, newContent, successCallback.bind(this), finishOperationAndMoveEditor.bind(this, moveDirection)); }, editingSelectorCancelled: function() { this._markSelectorMatches(); }, __proto__: WebInspector.PropertiesSection.prototype } WebInspector.ComputedStylePropertiesSection = function(parentPane, styleRule, usedProperties) { WebInspector.PropertiesSection.call(this, ""); this.headerElement.addStyleClass("hidden"); this.element.className = "styles-section monospace first-styles-section read-only computed-style"; this._parentPane = parentPane; this.styleRule = styleRule; this._usedProperties = usedProperties; this._alwaysShowComputedProperties = { "display": true, "height": true, "width": true }; this.computedStyle = true; this._propertyTreeElements = {}; this._expandedPropertyNames = {}; } WebInspector.ComputedStylePropertiesSection.prototype = { get pane() { return this._parentPane; }, collapse: function(dontRememberState) { }, _isPropertyInherited: function(propertyName) { var canonicalName = WebInspector.StylesSidebarPane.canonicalPropertyName(propertyName); return !(canonicalName in this._usedProperties) && !(canonicalName in this._alwaysShowComputedProperties); }, update: function() { this._expandedPropertyNames = {}; for (var name in this._propertyTreeElements) { if (this._propertyTreeElements[name].expanded) this._expandedPropertyNames[name] = true; } this._propertyTreeElements = {}; this.propertiesTreeOutline.removeChildren(); this.populated = false; }, onpopulate: function() { function sorter(a, b) { return a.name.localeCompare(b.name); } var style = this.styleRule.style; if (!style) return; var uniqueProperties = []; var allProperties = style.allProperties; for (var i = 0; i < allProperties.length; ++i) uniqueProperties.push(allProperties[i]); uniqueProperties.sort(sorter); this._propertyTreeElements = {}; for (var i = 0; i < uniqueProperties.length; ++i) { var property = uniqueProperties[i]; var inherited = this._isPropertyInherited(property.name); var item = new WebInspector.StylePropertyTreeElement(this, this._parentPane, this.styleRule, style, property, false, inherited, false); this.propertiesTreeOutline.appendChild(item); this._propertyTreeElements[property.name] = item; } }, rebuildComputedTrace: function(sections) { for (var i = 0; i < sections.length; ++i) { var section = sections[i]; if (section.computedStyle || section.isBlank) continue; for (var j = 0; j < section.uniqueProperties.length; ++j) { var property = section.uniqueProperties[j]; if (property.disabled) continue; if (section.isInherited && !(property.name in WebInspector.CSSMetadata.InheritedProperties)) continue; var treeElement = this._propertyTreeElements[property.name]; if (treeElement) { var fragment = document.createDocumentFragment(); var selector = fragment.createChild("span"); selector.style.color = "gray"; selector.textContent = section.styleRule.selectorText; fragment.appendChild(document.createTextNode(" - " + property.value + " ")); var subtitle = fragment.createChild("span"); subtitle.style.float = "right"; subtitle.appendChild(section._createRuleOriginNode()); var childElement = new TreeElement(fragment, null, false); treeElement.appendChild(childElement); if (property.inactive || section.isPropertyOverloaded(property.name)) childElement.listItemElement.addStyleClass("overloaded"); if (!property.parsedOk) { childElement.listItemElement.addStyleClass("not-parsed-ok"); childElement.listItemElement.insertBefore(WebInspector.StylesSidebarPane.createExclamationMark(property.name), childElement.listItemElement.firstChild); } } } } for (var name in this._expandedPropertyNames) { if (name in this._propertyTreeElements) this._propertyTreeElements[name].expand(); } }, __proto__: WebInspector.PropertiesSection.prototype } WebInspector.BlankStylePropertiesSection = function(parentPane, defaultSelectorText) { WebInspector.StylePropertiesSection.call(this, parentPane, {selectorText: defaultSelectorText, rule: {isViaInspector: true}}, true, false, false); this.element.addStyleClass("blank-section"); } WebInspector.BlankStylePropertiesSection.prototype = { get isBlank() { return !this._normal; }, expand: function() { if (!this.isBlank) WebInspector.StylePropertiesSection.prototype.expand.call(this); }, editingSelectorCommitted: function(element, newContent, oldContent, context, moveDirection) { if (!this.isBlank) { WebInspector.StylePropertiesSection.prototype.editingSelectorCommitted.call(this, element, newContent, oldContent, context, moveDirection); return; } function successCallback(newRule, doesSelectorAffectSelectedNode) { var styleRule = { section: this, style: newRule.style, selectorText: newRule.selectorText, sourceURL: newRule.sourceURL, rule: newRule }; this.makeNormal(styleRule); if (!doesSelectorAffectSelectedNode) { this.noAffect = true; this.element.addStyleClass("no-affect"); } this._selectorRefElement.removeChildren(); this._selectorRefElement.appendChild(this._createRuleOriginNode()); this.expand(); if (this.element.parentElement) this._moveEditorFromSelector(moveDirection); this._markSelectorMatches(); delete this._parentPane._userOperation; } if (newContent) newContent = newContent.trim(); this._parentPane._userOperation = true; WebInspector.cssModel.addRule(this.pane.node.id, newContent, successCallback.bind(this), this.editingSelectorCancelled.bind(this)); }, editingSelectorCancelled: function() { delete this._parentPane._userOperation; if (!this.isBlank) { WebInspector.StylePropertiesSection.prototype.editingSelectorCancelled.call(this); return; } this.pane.removeSection(this); }, makeNormal: function(styleRule) { this.element.removeStyleClass("blank-section"); this.styleRule = styleRule; this.rule = styleRule.rule; this._normal = true; }, __proto__: WebInspector.StylePropertiesSection.prototype } WebInspector.StylePropertyTreeElement = function(section, parentPane, styleRule, style, property, isShorthand, inherited, overloaded) { this.section = section; this._parentPane = parentPane; this._styleRule = styleRule; this.style = style; this.property = property; this.isShorthand = isShorthand; this._inherited = inherited; this._overloaded = overloaded; TreeElement.call(this, "", null, isShorthand); this.selectable = false; } WebInspector.StylePropertyTreeElement.prototype = { get inherited() { return this._inherited; }, set inherited(x) { if (x === this._inherited) return; this._inherited = x; this.updateState(); }, get overloaded() { return this._overloaded; }, set overloaded(x) { if (x === this._overloaded) return; this._overloaded = x; this.updateState(); }, get disabled() { return this.property.disabled; }, get name() { if (!this.disabled || !this.property.text) return this.property.name; var text = this.property.text; var index = text.indexOf(":"); if (index < 1) return this.property.name; return text.substring(0, index).trim(); }, get priority() { if (this.disabled) return ""; return this.property.priority; }, get value() { if (!this.disabled || !this.property.text) return this.property.value; var match = this.property.text.match(/(.*);\s*/); if (!match || !match[1]) return this.property.value; var text = match[1]; var index = text.indexOf(":"); if (index < 1) return this.property.value; return text.substring(index + 1).trim(); }, get parsedOk() { return this.property.parsedOk; }, onattach: function() { this.updateTitle(); this.listItemElement.addEventListener("mousedown", this._mouseDown.bind(this)); this.listItemElement.addEventListener("mouseup", this._resetMouseDownElement.bind(this)); this.listItemElement.addEventListener("click", this._mouseClick.bind(this)); }, _mouseDown: function(event) { if (this._parentPane) { this._parentPane._mouseDownTreeElement = this; this._parentPane._mouseDownTreeElementIsName = this._isNameElement(event.target); this._parentPane._mouseDownTreeElementIsValue = this._isValueElement(event.target); } }, _resetMouseDownElement: function() { if (this._parentPane) { delete this._parentPane._mouseDownTreeElement; delete this._parentPane._mouseDownTreeElementIsName; delete this._parentPane._mouseDownTreeElementIsValue; } }, updateTitle: function() { var value = this.value; this.updateState(); var enabledCheckboxElement; if (this.parsedOk) { enabledCheckboxElement = document.createElement("input"); enabledCheckboxElement.className = "enabled-button"; enabledCheckboxElement.type = "checkbox"; enabledCheckboxElement.checked = !this.disabled; enabledCheckboxElement.addEventListener("click", this.toggleEnabled.bind(this), false); } var nameElement = document.createElement("span"); nameElement.className = "webkit-css-property"; nameElement.textContent = this.name; nameElement.title = this.property.propertyText; this.nameElement = nameElement; this._expandElement = document.createElement("span"); this._expandElement.className = "expand-element"; var valueElement = document.createElement("span"); valueElement.className = "value"; this.valueElement = valueElement; var cf = WebInspector.Color.Format; if (value) { var self = this; function processValue(regex, processor, nextProcessor, valueText) { var container = document.createDocumentFragment(); var items = valueText.replace(regex, "\0$1\0").split("\0"); for (var i = 0; i < items.length; ++i) { if ((i % 2) === 0) { if (nextProcessor) container.appendChild(nextProcessor(items[i])); else container.appendChild(document.createTextNode(items[i])); } else { var processedNode = processor(items[i]); if (processedNode) container.appendChild(processedNode); } } return container; } function linkifyURL(url) { var hrefUrl = url; var match = hrefUrl.match(/['"]?([^'"]+)/); if (match) hrefUrl = match[1]; var container = document.createDocumentFragment(); container.appendChild(document.createTextNode("url(")); if (self._styleRule.sourceURL) hrefUrl = WebInspector.ParsedURL.completeURL(self._styleRule.sourceURL, hrefUrl); else if (self._parentPane.node) hrefUrl = self._parentPane.node.resolveURL(hrefUrl); var hasResource = !!WebInspector.resourceForURL(hrefUrl); container.appendChild(WebInspector.linkifyURLAsNode(hrefUrl, url, undefined, !hasResource)); container.appendChild(document.createTextNode(")")); return container; } function processColor(text) { try { var color = new WebInspector.Color(text); } catch (e) { return document.createTextNode(text); } var format = getFormat(); var hasSpectrum = self._parentPane; var spectrumHelper = hasSpectrum ? self._parentPane._spectrumHelper : null; var spectrum = spectrumHelper ? spectrumHelper.spectrum() : null; var colorSwatch = new WebInspector.ColorSwatch(); colorSwatch.setColorString(text); colorSwatch.element.addEventListener("click", swatchClick, false); var scrollerElement = hasSpectrum ? self._parentPane._computedStylePane.element.parentElement : null; function spectrumChanged(e) { color = e.data; var colorString = color.toString(); colorValueElement.textContent = colorString; colorSwatch.setColorString(colorString); self.applyStyleText(nameElement.textContent + ": " + valueElement.textContent, false, false, false); } function spectrumHidden(event) { scrollerElement.removeEventListener("scroll", repositionSpectrum, false); var commitEdit = event.data; var propertyText = !commitEdit && self.originalPropertyText ? self.originalPropertyText : (nameElement.textContent + ": " + valueElement.textContent); self.applyStyleText(propertyText, true, true, false); spectrum.removeEventListener(WebInspector.Spectrum.Events.ColorChanged, spectrumChanged); spectrumHelper.removeEventListener(WebInspector.SpectrumPopupHelper.Events.Hidden, spectrumHidden); delete self._parentPane._isEditingStyle; delete self.originalPropertyText; } function repositionSpectrum() { spectrumHelper.reposition(colorSwatch.element); } function swatchClick(e) { if (!spectrumHelper || e.shiftKey) changeColorDisplay(e); else { var visible = spectrumHelper.toggle(colorSwatch.element, color, format); if (visible) { spectrum.displayText = color.toString(format); self.originalPropertyText = self.property.propertyText; self._parentPane._isEditingStyle = true; spectrum.addEventListener(WebInspector.Spectrum.Events.ColorChanged, spectrumChanged); spectrumHelper.addEventListener(WebInspector.SpectrumPopupHelper.Events.Hidden, spectrumHidden); scrollerElement.addEventListener("scroll", repositionSpectrum, false); } } e.consume(true); } function getFormat() { var format; var formatSetting = WebInspector.settings.colorFormat.get(); if (formatSetting === cf.Original) format = cf.Original; else if (color.nickname) format = cf.Nickname; else if (formatSetting === cf.RGB) format = (color.simple ? cf.RGB : cf.RGBA); else if (formatSetting === cf.HSL) format = (color.simple ? cf.HSL : cf.HSLA); else if (color.simple) format = (color.hasShortHex() ? cf.ShortHEX : cf.HEX); else format = cf.RGBA; return format; } var colorValueElement = document.createElement("span"); colorValueElement.textContent = color.toString(format); function nextFormat(curFormat) { switch (curFormat) { case cf.Original: return color.simple ? cf.RGB : cf.RGBA; case cf.RGB: case cf.RGBA: return color.simple ? cf.HSL : cf.HSLA; case cf.HSL: case cf.HSLA: if (color.nickname) return cf.Nickname; if (color.simple) return color.hasShortHex() ? cf.ShortHEX : cf.HEX; else return cf.Original; case cf.ShortHEX: return cf.HEX; case cf.HEX: return cf.Original; case cf.Nickname: if (color.simple) return color.hasShortHex() ? cf.ShortHEX : cf.HEX; else return cf.Original; default: return null; } } function changeColorDisplay(event) { do { format = nextFormat(format); var currentValue = color.toString(format || ""); } while (format && currentValue === color.value && format !== cf.Original); if (format) colorValueElement.textContent = currentValue; } var container = document.createElement("nobr"); container.appendChild(colorSwatch.element); container.appendChild(colorValueElement); return container; } var colorRegex = /((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}|\b\w+\b(?!-))/g; var colorProcessor = processValue.bind(window, colorRegex, processColor, null); valueElement.appendChild(processValue(/url\(\s*([^)\s]+)\s*\)/g, linkifyURL.bind(this), WebInspector.CSSMetadata.isColorAwareProperty(self.name) ? colorProcessor : null, value)); } this.listItemElement.removeChildren(); nameElement.normalize(); valueElement.normalize(); if (!this.treeOutline) return; if (enabledCheckboxElement && this.treeOutline.section && this.parent.root && !this.section.computedStyle) this.listItemElement.appendChild(enabledCheckboxElement); this.listItemElement.appendChild(nameElement); this.listItemElement.appendChild(document.createTextNode(": ")); this.listItemElement.appendChild(this._expandElement); this.listItemElement.appendChild(valueElement); this.listItemElement.appendChild(document.createTextNode(";")); if (!this.parsedOk) { this.hasChildren = false; this.listItemElement.addStyleClass("not-parsed-ok"); this.listItemElement.insertBefore(WebInspector.StylesSidebarPane.createExclamationMark(this.property.name), this.listItemElement.firstChild); } if (this.property.inactive) this.listItemElement.addStyleClass("inactive"); }, _updatePane: function(userCallback) { if (this.treeOutline && this.treeOutline.section && this.treeOutline.section.pane) this.treeOutline.section.pane._refreshUpdate(this.treeOutline.section, false, userCallback); else { if (userCallback) userCallback(); } }, toggleEnabled: function(event) { var disabled = !event.target.checked; function callback(newStyle) { if (!newStyle) return; this.style = newStyle; this._styleRule.style = newStyle; if (this.treeOutline.section && this.treeOutline.section.pane) this.treeOutline.section.pane.dispatchEventToListeners("style property toggled"); this._updatePane(); delete this._parentPane._userOperation; } this._parentPane._userOperation = true; this.property.setDisabled(disabled, callback.bind(this)); event.consume(); }, updateState: function() { if (!this.listItemElement) return; if (this.style.isPropertyImplicit(this.name) || this.value === "initial") this.listItemElement.addStyleClass("implicit"); else this.listItemElement.removeStyleClass("implicit"); if (this.inherited) this.listItemElement.addStyleClass("inherited"); else this.listItemElement.removeStyleClass("inherited"); if (this.overloaded) this.listItemElement.addStyleClass("overloaded"); else this.listItemElement.removeStyleClass("overloaded"); if (this.disabled) this.listItemElement.addStyleClass("disabled"); else this.listItemElement.removeStyleClass("disabled"); }, onpopulate: function() { if (this.children.length || !this.isShorthand) return; var longhandProperties = this.style.longhandProperties(this.name); for (var i = 0; i < longhandProperties.length; ++i) { var name = longhandProperties[i].name; if (this.treeOutline.section) { var inherited = this.treeOutline.section.isPropertyInherited(name); var overloaded = this.treeOutline.section.isPropertyOverloaded(name); } var liveProperty = this.style.getLiveProperty(name); if (!liveProperty) continue; var item = new WebInspector.StylePropertyTreeElement(this.section, this._parentPane, this._styleRule, this.style, liveProperty, false, inherited, overloaded); this.appendChild(item); } }, restoreNameElement: function() { if (this.nameElement === this.listItemElement.querySelector(".webkit-css-property")) return; this.nameElement = document.createElement("span"); this.nameElement.className = "webkit-css-property"; this.nameElement.textContent = ""; this.listItemElement.insertBefore(this.nameElement, this.listItemElement.firstChild); }, _mouseClick: function(event) { if (!window.getSelection().isCollapsed) return; event.consume(true); if (event.target === this.listItemElement) { if (!this.section.editable) return; if (this.section._checkWillCancelEditing()) return; this.section.addNewBlankProperty(this.property.index + 1).startEditing(); return; } this.startEditing(event.target); }, _isNameElement: function(element) { return element.enclosingNodeOrSelfWithClass("webkit-css-property") === this.nameElement; }, _isValueElement: function(element) { return !!element.enclosingNodeOrSelfWithClass("value"); }, startEditing: function(selectElement) { if (this.parent.isShorthand) return; if (selectElement === this._expandElement) return; if (this.treeOutline.section && !this.treeOutline.section.editable) return; if (!selectElement) selectElement = this.nameElement; else selectElement = selectElement.enclosingNodeOrSelfWithClass("webkit-css-property") || selectElement.enclosingNodeOrSelfWithClass("value"); var isEditingName = selectElement === this.nameElement; if (!isEditingName && selectElement !== this.valueElement) { isEditingName = false; selectElement = this.valueElement; } if (WebInspector.isBeingEdited(selectElement)) return; var context = { expanded: this.expanded, hasChildren: this.hasChildren, isEditingName: isEditingName, previousContent: selectElement.textContent }; this.hasChildren = false; if (selectElement.parentElement) selectElement.parentElement.addStyleClass("child-editing"); selectElement.textContent = selectElement.textContent; function pasteHandler(context, event) { var data = event.clipboardData.getData("Text"); if (!data) return; var colonIdx = data.indexOf(":"); if (colonIdx < 0) return; var name = data.substring(0, colonIdx).trim(); var value = data.substring(colonIdx + 1).trim(); event.preventDefault(); if (!("originalName" in context)) { context.originalName = this.nameElement.textContent; context.originalValue = this.valueElement.textContent; } this.nameElement.textContent = name; this.valueElement.textContent = value; this.nameElement.normalize(); this.valueElement.normalize(); this.editingCommitted(null, event.target.textContent, context.previousContent, context, "forward"); } function blurListener(context, event) { var treeElement = this._parentPane._mouseDownTreeElement; var moveDirection = ""; if (treeElement === this) { if (isEditingName && this._parentPane._mouseDownTreeElementIsValue) moveDirection = "forward"; if (!isEditingName && this._parentPane._mouseDownTreeElementIsName) moveDirection = "backward"; } this.editingCommitted(null, event.target.textContent, context.previousContent, context, moveDirection); } delete this.originalPropertyText; this._parentPane._isEditingStyle = true; if (selectElement.parentElement) selectElement.parentElement.scrollIntoViewIfNeeded(false); var applyItemCallback = !isEditingName ? this._applyFreeFlowStyleTextEdit.bind(this, true) : undefined; this._prompt = new WebInspector.StylesSidebarPane.CSSPropertyPrompt(isEditingName ? WebInspector.CSSMetadata.cssPropertiesMetainfo : WebInspector.CSSMetadata.keywordsForProperty(this.nameElement.textContent), this, isEditingName); if (applyItemCallback) { this._prompt.addEventListener(WebInspector.TextPrompt.Events.ItemApplied, applyItemCallback, this); this._prompt.addEventListener(WebInspector.TextPrompt.Events.ItemAccepted, applyItemCallback, this); } var proxyElement = this._prompt.attachAndStartEditing(selectElement, blurListener.bind(this, context)); proxyElement.addEventListener("keydown", this.editingNameValueKeyDown.bind(this, context), false); if (isEditingName) proxyElement.addEventListener("paste", pasteHandler.bind(this, context)); window.getSelection().setBaseAndExtent(selectElement, 0, selectElement, 1); }, editingNameValueKeyDown: function(context, event) { if (event.handled) return; var isEditingName = context.isEditingName; var result; function shouldCommitValueSemicolon(text, cursorPosition) { var openQuote = ""; for (var i = 0; i < cursorPosition; ++i) { var ch = text[i]; if (ch === "\\" && openQuote !== "") ++i; else if (!openQuote && (ch === "\"" || ch === "'")) openQuote = ch; else if (openQuote === ch) openQuote = ""; } return !openQuote; } var isFieldInputTerminated = (event.keyCode === WebInspector.KeyboardShortcut.Keys.Semicolon.code) && (isEditingName ? event.shiftKey : (!event.shiftKey && shouldCommitValueSemicolon(event.target.textContent, event.target.selectionLeftOffset()))); if (isEnterKey(event) || isFieldInputTerminated) { event.preventDefault(); result = "forward"; } else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B") result = "cancel"; else if (!isEditingName && this._newProperty && event.keyCode === WebInspector.KeyboardShortcut.Keys.Backspace.code) { var selection = window.getSelection(); if (selection.isCollapsed && !selection.focusOffset) { event.preventDefault(); result = "backward"; } } else if (event.keyIdentifier === "U+0009") { result = event.shiftKey ? "backward" : "forward"; event.preventDefault(); } if (result) { switch (result) { case "cancel": this.editingCancelled(null, context); break; case "forward": case "backward": this.editingCommitted(null, event.target.textContent, context.previousContent, context, result); break; } event.consume(); return; } if (!isEditingName) this._applyFreeFlowStyleTextEdit(false); }, _applyFreeFlowStyleTextEdit: function(now) { if (this._applyFreeFlowStyleTextEditTimer) clearTimeout(this._applyFreeFlowStyleTextEditTimer); function apply() { var valueText = this.valueElement.textContent; if (valueText.indexOf(";") === -1) this.applyStyleText(this.nameElement.textContent + ": " + valueText, false, false, false); } if (now) apply.call(this); else this._applyFreeFlowStyleTextEditTimer = setTimeout(apply.bind(this), 100); }, kickFreeFlowStyleEditForTest: function() { this._applyFreeFlowStyleTextEdit(true); }, editingEnded: function(context) { this._resetMouseDownElement(); if (this._applyFreeFlowStyleTextEditTimer) clearTimeout(this._applyFreeFlowStyleTextEditTimer); this.hasChildren = context.hasChildren; if (context.expanded) this.expand(); var editedElement = context.isEditingName ? this.nameElement : this.valueElement; if (editedElement.parentElement) editedElement.parentElement.removeStyleClass("child-editing"); delete this._parentPane._isEditingStyle; }, editingCancelled: function(element, context) { this._removePrompt(); this._revertStyleUponEditingCanceled(this.originalPropertyText); this.editingEnded(context); }, _revertStyleUponEditingCanceled: function(originalPropertyText) { if (typeof originalPropertyText === "string") { delete this.originalPropertyText; this.applyStyleText(originalPropertyText, true, false, true); } else { if (this._newProperty) this.treeOutline.removeChild(this); else this.updateTitle(); } }, _findSibling: function(moveDirection) { var target = this; do { target = (moveDirection === "forward" ? target.nextSibling : target.previousSibling); } while(target && target.inherited); return target; }, editingCommitted: function(element, userInput, previousContent, context, moveDirection) { this._removePrompt(); this.editingEnded(context); var isEditingName = context.isEditingName; var createNewProperty, moveToPropertyName, moveToSelector; var moveTo = this; var moveToOther = (isEditingName ^ (moveDirection === "forward")); var abandonNewProperty = this._newProperty && !userInput && (moveToOther || isEditingName); if (moveDirection === "forward" && !isEditingName || moveDirection === "backward" && isEditingName) { moveTo = moveTo._findSibling(moveDirection); if (moveTo) moveToPropertyName = moveTo.name; else if (moveDirection === "forward" && (!this._newProperty || userInput)) createNewProperty = true; else if (moveDirection === "backward") moveToSelector = true; } var moveToIndex = moveTo && this.treeOutline ? this.treeOutline.children.indexOf(moveTo) : -1; var blankInput = /^\s*$/.test(userInput); var isDataPasted = "originalName" in context; var isDirtyViaPaste = isDataPasted && (this.nameElement.textContent !== context.originalName || this.valueElement.textContent !== context.originalValue); var shouldCommitNewProperty = this._newProperty && (moveToOther || (!moveDirection && !isEditingName) || (isEditingName && blankInput)); if (((userInput !== previousContent || isDirtyViaPaste) && !this._newProperty) || shouldCommitNewProperty) { this.treeOutline.section._afterUpdate = moveToNextCallback.bind(this, this._newProperty, !blankInput, this.treeOutline.section); var propertyText; if (blankInput || (this._newProperty && /^\s*$/.test(this.valueElement.textContent))) propertyText = ""; else { if (isEditingName) propertyText = userInput + ": " + this.valueElement.textContent; else propertyText = this.nameElement.textContent + ": " + userInput; } this.applyStyleText(propertyText, true, true, false); } else { if (!isDataPasted && !this._newProperty) this.updateTitle(); moveToNextCallback.call(this, this._newProperty, false, this.treeOutline.section); } function moveToNextCallback(alreadyNew, valueChanged, section) { if (!moveDirection) return; if (moveTo && moveTo.parent) { moveTo.startEditing(!isEditingName ? moveTo.nameElement : moveTo.valueElement); return; } if (moveTo && !moveTo.parent) { var propertyElements = section.propertiesTreeOutline.children; if (moveDirection === "forward" && blankInput && !isEditingName) --moveToIndex; if (moveToIndex >= propertyElements.length && !this._newProperty) createNewProperty = true; else { var treeElement = moveToIndex >= 0 ? propertyElements[moveToIndex] : null; if (treeElement) { var elementToEdit = !isEditingName ? treeElement.nameElement : treeElement.valueElement; if (alreadyNew && blankInput) elementToEdit = moveDirection === "forward" ? treeElement.nameElement : treeElement.valueElement; treeElement.startEditing(elementToEdit); return; } else if (!alreadyNew) moveToSelector = true; } } if (createNewProperty) { if (alreadyNew && !valueChanged && (isEditingName ^ (moveDirection === "backward"))) return; section.addNewBlankProperty().startEditing(); return; } if (abandonNewProperty) { moveTo = this._findSibling(moveDirection); var sectionToEdit = (moveTo || moveDirection === "backward") ? section : section.nextEditableSibling(); if (sectionToEdit) { if (sectionToEdit.rule) sectionToEdit.startEditingSelector(); else sectionToEdit._moveEditorFromSelector(moveDirection); } return; } if (moveToSelector) { if (section.rule) section.startEditingSelector(); else section._moveEditorFromSelector(moveDirection); } } }, _removePrompt: function() { if (this._prompt) { this._prompt.detach(); delete this._prompt; } }, _hasBeenModifiedIncrementally: function() { return typeof this.originalPropertyText === "string" || (!!this.property.propertyText && this._newProperty); }, applyStyleText: function(styleText, updateInterface, majorChange, isRevert) { function userOperationFinishedCallback(parentPane, updateInterface) { if (updateInterface) delete parentPane._userOperation; } if (!isRevert && !updateInterface && !this._hasBeenModifiedIncrementally()) { this.originalPropertyText = this.property.propertyText; } if (!this.treeOutline) return; var section = this.treeOutline.section; styleText = styleText.replace(/\s/g, " ").trim(); var styleTextLength = styleText.length; if (!styleTextLength && updateInterface && !isRevert && this._newProperty && !this._hasBeenModifiedIncrementally()) { this.parent.removeChild(this); section.afterUpdate(); return; } var currentNode = this._parentPane.node; if (updateInterface) this._parentPane._userOperation = true; function callback(userCallback, originalPropertyText, newStyle) { if (!newStyle) { if (updateInterface) { this._revertStyleUponEditingCanceled(originalPropertyText); } userCallback(); return; } if (this._newProperty) this._newPropertyInStyle = true; this.style = newStyle; this.property = newStyle.propertyAt(this.property.index); this._styleRule.style = this.style; if (section && section.pane) section.pane.dispatchEventToListeners("style edited"); if (updateInterface && currentNode === section.pane.node) { this._updatePane(userCallback); return; } userCallback(); } if (styleText.length && !/;\s*$/.test(styleText)) styleText += ";"; var overwriteProperty = !!(!this._newProperty || this._newPropertyInStyle); this.property.setText(styleText, majorChange, overwriteProperty, callback.bind(this, userOperationFinishedCallback.bind(null, this._parentPane, updateInterface), this.originalPropertyText)); }, ondblclick: function() { return true; }, isEventWithinDisclosureTriangle: function(event) { if (!this.section.computedStyle) return event.target === this._expandElement; return TreeElement.prototype.isEventWithinDisclosureTriangle.call(this, event); }, __proto__: TreeElement.prototype } WebInspector.StylesSidebarPane.CSSPropertyPrompt = function(cssCompletions, sidebarPane, isEditingName, acceptCallback) { WebInspector.TextPrompt.call(this, this._buildPropertyCompletions.bind(this), WebInspector.StyleValueDelimiters); this.setSuggestBoxEnabled("generic-suggest"); this._cssCompletions = cssCompletions; this._sidebarPane = sidebarPane; this._isEditingName = isEditingName; } WebInspector.StylesSidebarPane.CSSPropertyPrompt.prototype = { onKeyDown: function(event) { switch (event.keyIdentifier) { case "Up": case "Down": case "PageUp": case "PageDown": if (this._handleNameOrValueUpDown(event)) { event.preventDefault(); return; } break; } WebInspector.TextPrompt.prototype.onKeyDown.call(this, event); }, onMouseWheel: function(event) { if (this._handleNameOrValueUpDown(event)) { event.consume(true); return; } WebInspector.TextPrompt.prototype.onMouseWheel.call(this, event); }, tabKeyPressed: function() { this.acceptAutoComplete(); return false; }, _handleNameOrValueUpDown: function(event) { function finishHandler(originalValue, replacementString) { this._sidebarPane.applyStyleText(this._sidebarPane.nameElement.textContent + ": " + this._sidebarPane.valueElement.textContent, false, false, false); } if (!this._isEditingName && WebInspector.handleElementValueModifications(event, this._sidebarPane.valueElement, finishHandler.bind(this), this._isValueSuggestion.bind(this))) return true; return false; }, _isValueSuggestion: function(word) { if (!word) return false; word = word.toLowerCase(); return this._cssCompletions.keySet().hasOwnProperty(word); }, _buildPropertyCompletions: function(proxyElement, wordRange, force, completionsReadyCallback) { var prefix = wordRange.toString().toLowerCase(); if (!prefix && !force) return; var results = this._cssCompletions.startsWith(prefix); var selectedIndex = this._cssCompletions.mostUsedOf(results); completionsReadyCallback(results, selectedIndex); }, __proto__: WebInspector.TextPrompt.prototype } ; WebInspector.ElementsPanel = function() { WebInspector.Panel.call(this, "elements"); this.registerRequiredCSS("breadcrumbList.css"); this.registerRequiredCSS("elementsPanel.css"); this.registerRequiredCSS("textPrompt.css"); this.setHideOnDetach(); const initialSidebarWidth = 325; const minimumContentWidthPercent = 34; this.createSidebarView(this.element, WebInspector.SidebarView.SidebarPosition.Right, initialSidebarWidth); this.splitView.setMinimumSidebarWidth(Preferences.minElementsSidebarWidth); this.splitView.setMinimumMainWidthPercent(minimumContentWidthPercent); this.contentElement = this.splitView.mainElement; this.contentElement.id = "elements-content"; this.contentElement.addStyleClass("outline-disclosure"); this.contentElement.addStyleClass("source-code"); if (!WebInspector.settings.domWordWrap.get()) this.contentElement.classList.add("nowrap"); WebInspector.settings.domWordWrap.addChangeListener(this._domWordWrapSettingChanged.bind(this)); this.contentElement.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true); this.treeOutline = new WebInspector.ElementsTreeOutline(true, true, false, this._populateContextMenu.bind(this), this._setPseudoClassForNodeId.bind(this)); this.treeOutline.wireToDomAgent(); this.treeOutline.addEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._selectedNodeChanged, this); this.crumbsElement = document.createElement("div"); this.crumbsElement.className = "crumbs"; this.crumbsElement.addEventListener("mousemove", this._mouseMovedInCrumbs.bind(this), false); this.crumbsElement.addEventListener("mouseout", this._mouseMovedOutOfCrumbs.bind(this), false); this.sidebarPanes = {}; this.sidebarPanes.computedStyle = new WebInspector.ComputedStyleSidebarPane(); this.sidebarPanes.styles = new WebInspector.StylesSidebarPane(this.sidebarPanes.computedStyle, this._setPseudoClassForNodeId.bind(this)); this.sidebarPanes.metrics = new WebInspector.MetricsSidebarPane(); this.sidebarPanes.properties = new WebInspector.PropertiesSidebarPane(); this.sidebarPanes.domBreakpoints = WebInspector.domBreakpointsSidebarPane; this.sidebarPanes.eventListeners = new WebInspector.EventListenersSidebarPane(); this.sidebarPanes.styles.onexpand = this.updateStyles.bind(this); this.sidebarPanes.metrics.onexpand = this.updateMetrics.bind(this); this.sidebarPanes.properties.onexpand = this.updateProperties.bind(this); this.sidebarPanes.eventListeners.onexpand = this.updateEventListeners.bind(this); this.sidebarPanes.styles.expanded = true; this.sidebarPanes.styles.addEventListener("style edited", this._stylesPaneEdited, this); this.sidebarPanes.styles.addEventListener("style property toggled", this._stylesPaneEdited, this); this.sidebarPanes.metrics.addEventListener("metrics edited", this._metricsPaneEdited, this); for (var pane in this.sidebarPanes) { this.sidebarElement.appendChild(this.sidebarPanes[pane].element); if (this.sidebarPanes[pane].onattach) this.sidebarPanes[pane].onattach(); } this._popoverHelper = new WebInspector.PopoverHelper(this.element, this._getPopoverAnchor.bind(this), this._showPopover.bind(this)); this._popoverHelper.setTimeout(0); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrModified, this._updateBreadcrumbIfNeeded, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrRemoved, this._updateBreadcrumbIfNeeded, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.NodeRemoved, this._nodeRemoved, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, this._documentUpdatedEvent, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.InspectElementRequested, this._inspectElementRequested, this); if (WebInspector.domAgent.existingDocument()) this._documentUpdated(WebInspector.domAgent.existingDocument()); } WebInspector.ElementsPanel.prototype = { get statusBarItems() { return [this.crumbsElement]; }, defaultFocusedElement: function() { return this.treeOutline.element; }, statusBarResized: function() { this.updateBreadcrumbSizes(); }, wasShown: function() { if (this.treeOutline.element.parentElement !== this.contentElement) this.contentElement.appendChild(this.treeOutline.element); WebInspector.Panel.prototype.wasShown.call(this); this.updateBreadcrumb(); this.treeOutline.updateSelection(); this.treeOutline.setVisible(true); if (!this.treeOutline.rootDOMNode) WebInspector.domAgent.requestDocument(); this.sidebarElement.insertBefore(this.sidebarPanes.domBreakpoints.element, this.sidebarPanes.eventListeners.element); }, willHide: function() { WebInspector.domAgent.hideDOMNodeHighlight(); this.treeOutline.setVisible(false); this._popoverHelper.hidePopover(); this.contentElement.removeChild(this.treeOutline.element); for (var pane in this.sidebarPanes) { if (this.sidebarPanes[pane].willHide) this.sidebarPanes[pane].willHide(); } WebInspector.Panel.prototype.willHide.call(this); }, onResize: function() { this.treeOutline.updateSelection(); this.updateBreadcrumbSizes(); }, _setPseudoClassForNodeId: function(nodeId, pseudoClass, enable) { var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) return; var pseudoClasses = node.getUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName); if (enable) { pseudoClasses = pseudoClasses || []; if (pseudoClasses.indexOf(pseudoClass) >= 0) return; pseudoClasses.push(pseudoClass); node.setUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName, pseudoClasses); } else { if (!pseudoClasses || pseudoClasses.indexOf(pseudoClass) < 0) return; pseudoClasses.remove(pseudoClass); if (!pseudoClasses.length) node.removeUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName); } this.treeOutline.updateOpenCloseTags(node); WebInspector.cssModel.forcePseudoState(node.id, node.getUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName)); this._metricsPaneEdited(); this._stylesPaneEdited(); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.ForcedElementState, selector: node.appropriateSelectorFor(false), enabled: enable, state: pseudoClass }); }, _selectedNodeChanged: function() { var selectedNode = this.selectedDOMNode(); if (!selectedNode && this._lastValidSelectedNode) this._selectedPathOnReset = this._lastValidSelectedNode.path(); this.updateBreadcrumb(false); this._updateSidebars(); if (selectedNode) { ConsoleAgent.addInspectedNode(selectedNode.id); this._lastValidSelectedNode = selectedNode; } WebInspector.notifications.dispatchEventToListeners(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged); }, _updateSidebars: function() { for (var pane in this.sidebarPanes) this.sidebarPanes[pane].needsUpdate = true; this.updateStyles(true); this.updateMetrics(); this.updateProperties(); this.updateEventListeners(); }, _reset: function() { delete this.currentQuery; }, _documentUpdatedEvent: function(event) { this._documentUpdated(event.data); }, _documentUpdated: function(inspectedRootDocument) { this._reset(); this.searchCanceled(); this.treeOutline.rootDOMNode = inspectedRootDocument; if (!inspectedRootDocument) { if (this.isShowing()) WebInspector.domAgent.requestDocument(); return; } this.sidebarPanes.domBreakpoints.restoreBreakpoints(); function selectNode(candidateFocusNode) { if (!candidateFocusNode) candidateFocusNode = inspectedRootDocument.body || inspectedRootDocument.documentElement; if (!candidateFocusNode) return; this.selectDOMNode(candidateFocusNode); if (this.treeOutline.selectedTreeElement) this.treeOutline.selectedTreeElement.expand(); } function selectLastSelectedNode(nodeId) { if (this.selectedDOMNode()) { return; } var node = nodeId ? WebInspector.domAgent.nodeForId(nodeId) : null; selectNode.call(this, node); } if (this._selectedPathOnReset) WebInspector.domAgent.pushNodeByPathToFrontend(this._selectedPathOnReset, selectLastSelectedNode.bind(this)); else selectNode.call(this); delete this._selectedPathOnReset; }, searchCanceled: function() { delete this._searchQuery; this._hideSearchHighlights(); WebInspector.searchController.updateSearchMatchesCount(0, this); delete this._currentSearchResultIndex; delete this._searchResults; WebInspector.domAgent.cancelSearch(); }, performSearch: function(query) { this.searchCanceled(); const whitespaceTrimmedQuery = query.trim(); if (!whitespaceTrimmedQuery.length) return; this._searchQuery = query; function resultCountCallback(resultCount) { WebInspector.searchController.updateSearchMatchesCount(resultCount, this); if (!resultCount) return; this._searchResults = new Array(resultCount); this._currentSearchResultIndex = -1; this.jumpToNextSearchResult(); } WebInspector.domAgent.performSearch(whitespaceTrimmedQuery, resultCountCallback.bind(this)); }, _contextMenuEventFired: function(event) { function toggleWordWrap() { WebInspector.settings.domWordWrap.set(!WebInspector.settings.domWordWrap.get()); } var contextMenu = new WebInspector.ContextMenu(event); var populated = this.treeOutline.populateContextMenu(contextMenu, event); if (WebInspector.experimentsSettings.cssRegions.isEnabled()) { contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString("CSS Named Flows..."), this._showNamedFlowCollections.bind(this)); } contextMenu.appendSeparator(); contextMenu.appendCheckboxItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Word wrap" : "Word Wrap"), toggleWordWrap.bind(this), WebInspector.settings.domWordWrap.get()); contextMenu.show(); }, _showNamedFlowCollections: function() { if (!WebInspector.cssNamedFlowCollectionsView) WebInspector.cssNamedFlowCollectionsView = new WebInspector.CSSNamedFlowCollectionsView(); WebInspector.cssNamedFlowCollectionsView.showInDrawer(); }, _domWordWrapSettingChanged: function(event) { if (event.data) this.contentElement.removeStyleClass("nowrap"); else this.contentElement.addStyleClass("nowrap"); var selectedNode = this.selectedDOMNode(); if (!selectedNode) return; var treeElement = this.treeOutline.findTreeElement(selectedNode); if (treeElement) treeElement.updateSelection(); }, switchToAndFocus: function(node) { WebInspector.searchController.cancelSearch(); WebInspector.inspectorView.setCurrentPanel(this); this.selectDOMNode(node, true); }, _populateContextMenu: function(contextMenu, node) { contextMenu.appendSeparator(); var pane = this.sidebarPanes.domBreakpoints; pane.populateNodeContextMenu(node, contextMenu); }, _getPopoverAnchor: function(element) { var anchor = element.enclosingNodeOrSelfWithClass("webkit-html-resource-link"); if (anchor) { if (!anchor.href) return null; var resource = WebInspector.resourceTreeModel.resourceForURL(anchor.href); if (!resource || resource.type !== WebInspector.resourceTypes.Image) return null; anchor.removeAttribute("title"); } return anchor; }, _loadDimensionsForNode: function(treeElement, callback) { if (treeElement.treeOutline !== this.treeOutline) { callback(); return; } var node = (treeElement.representedObject); if (!node.nodeName() || node.nodeName().toLowerCase() !== "img") { callback(); return; } WebInspector.RemoteObject.resolveNode(node, "", resolvedNode); function resolvedNode(object) { if (!object) { callback(); return; } object.callFunctionJSON(dimensions, undefined, callback); object.release(); function dimensions() { return { offsetWidth: this.offsetWidth, offsetHeight: this.offsetHeight, naturalWidth: this.naturalWidth, naturalHeight: this.naturalHeight }; } } }, _showPopover: function(anchor, popover) { var listItem = anchor.enclosingNodeOrSelfWithNodeName("li"); if (listItem && listItem.treeElement) this._loadDimensionsForNode(listItem.treeElement, WebInspector.DOMPresentationUtils.buildImagePreviewContents.bind(WebInspector.DOMPresentationUtils, anchor.href, true, showPopover)); else WebInspector.DOMPresentationUtils.buildImagePreviewContents(anchor.href, true, showPopover); function showPopover(contents) { if (!contents) return; popover.setCanShrink(false); popover.show(contents, anchor); } }, jumpToNextSearchResult: function() { if (!this._searchResults) return; this._hideSearchHighlights(); if (++this._currentSearchResultIndex >= this._searchResults.length) this._currentSearchResultIndex = 0; this._highlightCurrentSearchResult(); }, jumpToPreviousSearchResult: function() { if (!this._searchResults) return; this._hideSearchHighlights(); if (--this._currentSearchResultIndex < 0) this._currentSearchResultIndex = (this._searchResults.length - 1); this._highlightCurrentSearchResult(); return true; }, _highlightCurrentSearchResult: function() { var index = this._currentSearchResultIndex; var searchResults = this._searchResults; var searchResult = searchResults[index]; if (searchResult === null) { WebInspector.searchController.updateCurrentMatchIndex(index, this); return; } if (typeof searchResult === "undefined") { function callback(node) { searchResults[index] = node || null; this._highlightCurrentSearchResult(); } WebInspector.domAgent.searchResult(index, callback.bind(this)); return; } WebInspector.searchController.updateCurrentMatchIndex(index, this); var treeElement = this.treeOutline.findTreeElement(searchResult); if (treeElement) { treeElement.highlightSearchResults(this._searchQuery); treeElement.reveal(); } }, _hideSearchHighlights: function() { if (!this._searchResults) return; var searchResult = this._searchResults[this._currentSearchResultIndex]; if (!searchResult) return; var treeElement = this.treeOutline.findTreeElement(searchResult); if (treeElement) treeElement.hideSearchHighlights(); }, selectedDOMNode: function() { return this.treeOutline.selectedDOMNode(); }, selectDOMNode: function(node, focus) { this.treeOutline.selectDOMNode(node, focus); }, _nodeRemoved: function(event) { if (!this.isShowing()) return; var crumbs = this.crumbsElement; for (var crumb = crumbs.firstChild; crumb; crumb = crumb.nextSibling) { if (crumb.representedObject === event.data.node) { this.updateBreadcrumb(true); return; } } }, _stylesPaneEdited: function() { this.sidebarPanes.metrics.needsUpdate = true; this.updateMetrics(); }, _metricsPaneEdited: function() { this.sidebarPanes.styles.needsUpdate = true; this.updateStyles(true); }, _mouseMovedInCrumbs: function(event) { var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); var crumbElement = nodeUnderMouse.enclosingNodeOrSelfWithClass("crumb"); WebInspector.domAgent.highlightDOMNode(crumbElement ? crumbElement.representedObject.id : 0); if ("_mouseOutOfCrumbsTimeout" in this) { clearTimeout(this._mouseOutOfCrumbsTimeout); delete this._mouseOutOfCrumbsTimeout; } }, _mouseMovedOutOfCrumbs: function(event) { var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.crumbsElement)) return; WebInspector.domAgent.hideDOMNodeHighlight(); this._mouseOutOfCrumbsTimeout = setTimeout(this.updateBreadcrumbSizes.bind(this), 1000); }, _updateBreadcrumbIfNeeded: function(event) { var name = event.data.name; if (name !== "class" && name !== "id") return; var node = (event.data.node); var crumbs = this.crumbsElement; var crumb = crumbs.firstChild; while (crumb) { if (crumb.representedObject === node) { this.updateBreadcrumb(true); break; } crumb = crumb.nextSibling; } }, updateBreadcrumb: function(forceUpdate) { if (!this.isShowing()) return; var crumbs = this.crumbsElement; var handled = false; var crumb = crumbs.firstChild; while (crumb) { if (crumb.representedObject === this.selectedDOMNode()) { crumb.addStyleClass("selected"); handled = true; } else { crumb.removeStyleClass("selected"); } crumb = crumb.nextSibling; } if (handled && !forceUpdate) { this.updateBreadcrumbSizes(); return; } crumbs.removeChildren(); var panel = this; function selectCrumbFunction(event) { var crumb = event.currentTarget; if (crumb.hasStyleClass("collapsed")) { if (crumb === panel.crumbsElement.firstChild) { var currentCrumb = crumb; while (currentCrumb) { var hidden = currentCrumb.hasStyleClass("hidden"); var collapsed = currentCrumb.hasStyleClass("collapsed"); if (!hidden && !collapsed) break; crumb = currentCrumb; currentCrumb = currentCrumb.nextSibling; } } panel.updateBreadcrumbSizes(crumb); } else panel.selectDOMNode(crumb.representedObject, true); event.preventDefault(); } for (var current = this.selectedDOMNode(); current; current = current.parentNode) { if (current.nodeType() === Node.DOCUMENT_NODE) continue; crumb = document.createElement("span"); crumb.className = "crumb"; crumb.representedObject = current; crumb.addEventListener("mousedown", selectCrumbFunction, false); var crumbTitle; switch (current.nodeType()) { case Node.ELEMENT_NODE: WebInspector.DOMPresentationUtils.decorateNodeLabel(current, crumb); break; case Node.TEXT_NODE: crumbTitle = WebInspector.UIString("(text)"); break case Node.COMMENT_NODE: crumbTitle = "<!-->"; break; case Node.DOCUMENT_TYPE_NODE: crumbTitle = "<!DOCTYPE>"; break; default: crumbTitle = current.nodeNameInCorrectCase(); } if (!crumb.childNodes.length) { var nameElement = document.createElement("span"); nameElement.textContent = crumbTitle; crumb.appendChild(nameElement); crumb.title = crumbTitle; } if (current === this.selectedDOMNode()) crumb.addStyleClass("selected"); if (!crumbs.childNodes.length) crumb.addStyleClass("end"); crumbs.appendChild(crumb); } if (crumbs.hasChildNodes()) crumbs.lastChild.addStyleClass("start"); this.updateBreadcrumbSizes(); }, updateBreadcrumbSizes: function(focusedCrumb) { if (!this.isShowing()) return; if (document.body.offsetWidth <= 0) { return; } var crumbs = this.crumbsElement; if (!crumbs.childNodes.length || crumbs.offsetWidth <= 0) return; var selectedIndex = 0; var focusedIndex = 0; var selectedCrumb; var i = 0; var crumb = crumbs.firstChild; while (crumb) { if (!selectedCrumb && crumb.hasStyleClass("selected")) { selectedCrumb = crumb; selectedIndex = i; } if (crumb === focusedCrumb) focusedIndex = i; if (crumb !== crumbs.lastChild) crumb.removeStyleClass("start"); if (crumb !== crumbs.firstChild) crumb.removeStyleClass("end"); crumb.removeStyleClass("compact"); crumb.removeStyleClass("collapsed"); crumb.removeStyleClass("hidden"); crumb = crumb.nextSibling; ++i; } crumbs.firstChild.addStyleClass("end"); crumbs.lastChild.addStyleClass("start"); function crumbsAreSmallerThanContainer() { var rightPadding = 20; var errorWarningElement = document.getElementById("error-warning-count"); if (!WebInspector.drawer.visible && errorWarningElement) rightPadding += errorWarningElement.offsetWidth; return ((crumbs.totalOffsetLeft() + crumbs.offsetWidth + rightPadding) < window.innerWidth); } if (crumbsAreSmallerThanContainer()) return; var BothSides = 0; var AncestorSide = -1; var ChildSide = 1; function makeCrumbsSmaller(shrinkingFunction, direction, significantCrumb) { if (!significantCrumb) significantCrumb = (focusedCrumb || selectedCrumb); if (significantCrumb === selectedCrumb) var significantIndex = selectedIndex; else if (significantCrumb === focusedCrumb) var significantIndex = focusedIndex; else { var significantIndex = 0; for (var i = 0; i < crumbs.childNodes.length; ++i) { if (crumbs.childNodes[i] === significantCrumb) { significantIndex = i; break; } } } function shrinkCrumbAtIndex(index) { var shrinkCrumb = crumbs.childNodes[index]; if (shrinkCrumb && shrinkCrumb !== significantCrumb) shrinkingFunction(shrinkCrumb); if (crumbsAreSmallerThanContainer()) return true; return false; } if (direction) { var index = (direction > 0 ? 0 : crumbs.childNodes.length - 1); while (index !== significantIndex) { if (shrinkCrumbAtIndex(index)) return true; index += (direction > 0 ? 1 : -1); } } else { var startIndex = 0; var endIndex = crumbs.childNodes.length - 1; while (startIndex != significantIndex || endIndex != significantIndex) { var startDistance = significantIndex - startIndex; var endDistance = endIndex - significantIndex; if (startDistance >= endDistance) var index = startIndex++; else var index = endIndex--; if (shrinkCrumbAtIndex(index)) return true; } } return false; } function coalesceCollapsedCrumbs() { var crumb = crumbs.firstChild; var collapsedRun = false; var newStartNeeded = false; var newEndNeeded = false; while (crumb) { var hidden = crumb.hasStyleClass("hidden"); if (!hidden) { var collapsed = crumb.hasStyleClass("collapsed"); if (collapsedRun && collapsed) { crumb.addStyleClass("hidden"); crumb.removeStyleClass("compact"); crumb.removeStyleClass("collapsed"); if (crumb.hasStyleClass("start")) { crumb.removeStyleClass("start"); newStartNeeded = true; } if (crumb.hasStyleClass("end")) { crumb.removeStyleClass("end"); newEndNeeded = true; } continue; } collapsedRun = collapsed; if (newEndNeeded) { newEndNeeded = false; crumb.addStyleClass("end"); } } else collapsedRun = true; crumb = crumb.nextSibling; } if (newStartNeeded) { crumb = crumbs.lastChild; while (crumb) { if (!crumb.hasStyleClass("hidden")) { crumb.addStyleClass("start"); break; } crumb = crumb.previousSibling; } } } function compact(crumb) { if (crumb.hasStyleClass("hidden")) return; crumb.addStyleClass("compact"); } function collapse(crumb, dontCoalesce) { if (crumb.hasStyleClass("hidden")) return; crumb.addStyleClass("collapsed"); crumb.removeStyleClass("compact"); if (!dontCoalesce) coalesceCollapsedCrumbs(); } if (!focusedCrumb) { if (makeCrumbsSmaller(compact, ChildSide)) return; if (makeCrumbsSmaller(collapse, ChildSide)) return; } if (makeCrumbsSmaller(compact, (focusedCrumb ? BothSides : AncestorSide))) return; if (makeCrumbsSmaller(collapse, (focusedCrumb ? BothSides : AncestorSide))) return; if (!selectedCrumb) return; compact(selectedCrumb); if (crumbsAreSmallerThanContainer()) return; collapse(selectedCrumb, true); }, updateStyles: function(forceUpdate) { var stylesSidebarPane = this.sidebarPanes.styles; var computedStylePane = this.sidebarPanes.computedStyle; if ((!stylesSidebarPane.expanded && !computedStylePane.expanded) || !stylesSidebarPane.needsUpdate) return; stylesSidebarPane.update(this.selectedDOMNode(), forceUpdate); stylesSidebarPane.needsUpdate = false; }, updateMetrics: function() { var metricsSidebarPane = this.sidebarPanes.metrics; if (!metricsSidebarPane.expanded || !metricsSidebarPane.needsUpdate) return; metricsSidebarPane.update(this.selectedDOMNode()); metricsSidebarPane.needsUpdate = false; }, updateProperties: function() { var propertiesSidebarPane = this.sidebarPanes.properties; if (!propertiesSidebarPane.expanded || !propertiesSidebarPane.needsUpdate) return; propertiesSidebarPane.update(this.selectedDOMNode()); propertiesSidebarPane.needsUpdate = false; }, updateEventListeners: function() { var eventListenersSidebarPane = this.sidebarPanes.eventListeners; if (!eventListenersSidebarPane.expanded || !eventListenersSidebarPane.needsUpdate) return; eventListenersSidebarPane.update(this.selectedDOMNode()); eventListenersSidebarPane.needsUpdate = false; }, handleShortcut: function(event) { if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) && !event.shiftKey && event.keyIdentifier === "U+005A") { WebInspector.domAgent.undo(this._updateSidebars.bind(this)); event.handled = true; return; } var isRedoKey = WebInspector.isMac() ? event.metaKey && event.shiftKey && event.keyIdentifier === "U+005A" : event.ctrlKey && event.keyIdentifier === "U+0059"; if (isRedoKey) { DOMAgent.redo(this._updateSidebars.bind(this)); event.handled = true; return; } this.treeOutline.handleShortcut(event); }, handleCopyEvent: function(event) { if (!window.getSelection().isCollapsed) return; event.clipboardData.clearData(); event.preventDefault(); this.selectedDOMNode().copyNode(); }, sidebarResized: function(event) { this.treeOutline.updateSelection(); }, _inspectElementRequested: function(event) { var node = event.data; this.revealAndSelectNode(node.id); }, revealAndSelectNode: function(nodeId) { WebInspector.inspectorView.setCurrentPanel(this); var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) return; WebInspector.domAgent.highlightDOMNodeForTwoSeconds(nodeId); this.selectDOMNode(node, true); }, appendApplicableItems: function(event, contextMenu, target) { if (!(target instanceof WebInspector.RemoteObject)) return; var remoteObject = (target); if (remoteObject.subtype !== "node") return; function selectNode(nodeId) { if (nodeId) WebInspector.domAgent.inspectElement(nodeId); } function revealElement() { remoteObject.pushNodeToFrontend(selectNode); } contextMenu.appendItem(WebInspector.UIString("Reveal in Elements Panel"), revealElement.bind(this)); }, __proto__: WebInspector.Panel.prototype }
JavaScript
WebInspector.MemoryStatistics = function(timelinePanel, model, sidebarWidth) { this._timelinePanel = timelinePanel; this._counters = []; model.addEventListener(WebInspector.TimelineModel.Events.RecordAdded, this._onRecordAdded, this); model.addEventListener(WebInspector.TimelineModel.Events.RecordsCleared, this._onRecordsCleared, this); this._containerAnchor = timelinePanel.element.lastChild; this._memorySidebarView = new WebInspector.SidebarView(WebInspector.SidebarView.SidebarPosition.Left, undefined, sidebarWidth); this._memorySidebarView.sidebarElement.addStyleClass("sidebar"); this._memorySidebarView.element.id = "memory-graphs-container"; this._memorySidebarView.addEventListener(WebInspector.SidebarView.EventTypes.Resized, this._sidebarResized.bind(this)); this._canvasContainer = this._memorySidebarView.mainElement; this._canvasContainer.id = "memory-graphs-canvas-container"; this._currentValuesBar = this._canvasContainer.createChild("div"); this._currentValuesBar.id = "counter-values-bar"; this._canvas = this._canvasContainer.createChild("canvas"); this._canvas.id = "memory-counters-graph"; this._lastMarkerXPosition = 0; this._canvas.addEventListener("mouseover", this._onMouseOver.bind(this), true); this._canvas.addEventListener("mousemove", this._onMouseMove.bind(this), true); this._canvas.addEventListener("mouseout", this._onMouseOut.bind(this), true); this._canvas.addEventListener("click", this._onClick.bind(this), true); this._timelineGrid = new WebInspector.TimelineGrid(); this._canvasContainer.appendChild(this._timelineGrid.dividersElement); this._memorySidebarView.sidebarElement.createChild("div", "sidebar-tree sidebar-tree-section").textContent = WebInspector.UIString("COUNTERS"); function getDocumentCount(entry) { return entry.documentCount; } function getNodeCount(entry) { return entry.nodeCount; } function getListenerCount(entry) { return entry.listenerCount; } this._counterUI = [ new WebInspector.CounterUI(this, "Document Count", "Documents: %d", [100,0,0], getDocumentCount), new WebInspector.CounterUI(this, "DOM Node Count", "Nodes: %d", [0,100,0], getNodeCount), new WebInspector.CounterUI(this, "Event Listener Count", "Listeners: %d", [0,0,100], getListenerCount) ]; TimelineAgent.setIncludeMemoryDetails(true); } WebInspector.SwatchCheckbox = function(title, color) { this.element = document.createElement("div"); this._swatch = this.element.createChild("div", "swatch"); this.element.createChild("span", "title").textContent = title; this._color = color; this.checked = true; this.element.addEventListener("click", this._toggleCheckbox.bind(this), true); } WebInspector.SwatchCheckbox.Events = { Changed: "Changed" } WebInspector.SwatchCheckbox.prototype = { get checked() { return this._checked; }, set checked(v) { this._checked = v; if (this._checked) this._swatch.style.backgroundColor = this._color; else this._swatch.style.backgroundColor = ""; }, _toggleCheckbox: function(event) { this.checked = !this.checked; this.dispatchEventToListeners(WebInspector.SwatchCheckbox.Events.Changed); }, __proto__: WebInspector.Object.prototype } WebInspector.CounterUI = function(memoryCountersPane, title, currentValueLabel, rgb, valueGetter) { this._memoryCountersPane = memoryCountersPane; this.valueGetter = valueGetter; var container = memoryCountersPane._memorySidebarView.sidebarElement.createChild("div", "memory-counter-sidebar-info"); var swatchColor = "rgb(" + rgb.join(",") + ")"; this._swatch = new WebInspector.SwatchCheckbox(WebInspector.UIString(title), swatchColor); this._swatch.addEventListener(WebInspector.SwatchCheckbox.Events.Changed, this._toggleCounterGraph.bind(this)); container.appendChild(this._swatch.element); this._range = this._swatch.element.createChild("span"); this._value = memoryCountersPane._currentValuesBar.createChild("span", "memory-counter-value"); this._value.style.color = swatchColor; this._currentValueLabel = currentValueLabel; this.graphColor = "rgba(" + rgb.join(",") + ",0.8)"; this.graphYValues = []; } WebInspector.CounterUI.prototype = { _toggleCounterGraph: function(event) { if (this._swatch.checked) this._value.removeStyleClass("hidden"); else this._value.addStyleClass("hidden"); this._memoryCountersPane.refresh(); }, setRange: function(minValue, maxValue) { this._range.textContent = WebInspector.UIString("[ %d - %d ]", minValue, maxValue); }, updateCurrentValue: function(countersEntry) { this._value.textContent = WebInspector.UIString(this._currentValueLabel, this.valueGetter(countersEntry)); }, clearCurrentValueAndMarker: function(ctx) { this._value.textContent = ""; this.restoreImageUnderMarker(ctx); }, get visible() { return this._swatch.checked; }, saveImageUnderMarker: function(ctx, x, y, radius) { const w = radius + 1; var imageData = ctx.getImageData(x - w, y - w, 2 * w, 2 * w); this._imageUnderMarker = { x: x - w, y: y - w, imageData: imageData }; }, restoreImageUnderMarker: function(ctx) { if (!this.visible) return; if (this._imageUnderMarker) ctx.putImageData(this._imageUnderMarker.imageData, this._imageUnderMarker.x, this._imageUnderMarker.y); this.discardImageUnderMarker(); }, discardImageUnderMarker: function() { delete this._imageUnderMarker; } } WebInspector.MemoryStatistics.prototype = { _onRecordsCleared: function() { this._counters = []; }, setMainTimelineGrid: function(timelineGrid) { this._mainTimelineGrid = timelineGrid; }, setTopPosition: function(top) { this._memorySidebarView.element.style.top = top + "px"; this._updateSize(); }, setSidebarWidth: function(width) { if (this._ignoreSidebarResize) return; this._ignoreSidebarResize = true; this._memorySidebarView.setSidebarWidth(width); this._ignoreSidebarResize = false; }, _sidebarResized: function(event) { if (this._ignoreSidebarResize) return; this._ignoreSidebarResize = true; this._timelinePanel.splitView.setSidebarWidth(event.data); this._ignoreSidebarResize = false; }, _updateSize: function() { var width = this._mainTimelineGrid.dividersElement.offsetWidth + 1; this._canvasContainer.style.width = width + "px"; var height = this._canvasContainer.offsetHeight - this._currentValuesBar.offsetHeight; this._canvas.width = width; this._canvas.height = height; }, _onRecordAdded: function(event) { var statistics = this._counters; function addStatistics(record) { var counters = record["counters"]; if (!counters) return; statistics.push({ time: record.endTime || record.startTime, documentCount: counters["documents"], nodeCount: counters["nodes"], listenerCount: counters["jsEventListeners"] }); } WebInspector.TimelinePresentationModel.forAllRecords([event.data], null, addStatistics); }, _draw: function() { this._calculateVisibleIndexes(); this._calculateXValues(); this._clear(); this._setVerticalClip(10, this._canvas.height - 20); for (var i = 0; i < this._counterUI.length; i++) this._drawGraph(this._counterUI[i]); }, _calculateVisibleIndexes: function() { var calculator = this._timelinePanel.calculator; var start = calculator.minimumBoundary() * 1000; var end = calculator.maximumBoundary() * 1000; var firstIndex = 0; var lastIndex = this._counters.length - 1; for (var i = 0; i < this._counters.length; i++) { var time = this._counters[i].time; if (time <= start) { firstIndex = i; } else { if (end < time) break; lastIndex = i; } } this._minimumIndex = firstIndex; this._maximumIndex = lastIndex; this._minTime = start; this._maxTime = end; }, _onClick: function(event) { var x = event.x - event.target.offsetParent.offsetLeft; var i = this._recordIndexAt(x); var counter = this._counters[i]; if (counter) this._timelinePanel.revealRecordAt(counter.time / 1000); }, _onMouseOut: function(event) { delete this._markerXPosition; var ctx = this._canvas.getContext("2d"); for (var i = 0; i < this._counterUI.length; i++) this._counterUI[i].clearCurrentValueAndMarker(ctx); }, _onMouseOver: function(event) { this._onMouseMove(event); }, _onMouseMove: function(event) { var x = event.x - event.target.offsetParent.offsetLeft this._markerXPosition = x; this._refreshCurrentValues(); }, _refreshCurrentValues: function() { if (!this._counters.length) return; if (this._markerXPosition === undefined) return; var i = this._recordIndexAt(this._markerXPosition); for (var j = 0; j < this._counterUI.length; j++) this._counterUI[j].updateCurrentValue(this._counters[i]); this._highlightCurrentPositionOnGraphs(this._markerXPosition, i); }, _recordIndexAt: function(x) { var i; for (i = this._minimumIndex + 1; i <= this._maximumIndex; i++) { var statX = this._counters[i].x; if (x < statX) break; } i--; return i; }, _highlightCurrentPositionOnGraphs: function(x, index) { var ctx = this._canvas.getContext("2d"); for (var i = 0; i < this._counterUI.length; i++) { var counterUI = this._counterUI[i]; if (!counterUI.visible) continue; counterUI.restoreImageUnderMarker(ctx); } const radius = 2; for (var i = 0; i < this._counterUI.length; i++) { var counterUI = this._counterUI[i]; if (!counterUI.visible) continue; var y = counterUI.graphYValues[index]; counterUI.saveImageUnderMarker(ctx, x, y, radius); } for (var i = 0; i < this._counterUI.length; i++) { var counterUI = this._counterUI[i]; if (!counterUI.visible) continue; var y = counterUI.graphYValues[index]; ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI*2, true); ctx.lineWidth = 1; ctx.fillStyle = counterUI.graphColor; ctx.strokeStyle = counterUI.graphColor; ctx.fill(); ctx.stroke(); ctx.closePath(); } }, visible: function() { return this._memorySidebarView.isShowing(); }, show: function() { var anchor = (this._containerAnchor.nextSibling); this._memorySidebarView.show(this._timelinePanel.element, anchor); this._updateSize(); this._refreshDividers(); setTimeout(this._draw.bind(this), 0); }, refresh: function() { this._updateSize(); this._refreshDividers(); this._draw(); this._refreshCurrentValues(); }, hide: function() { this._memorySidebarView.detach(); }, _refreshDividers: function() { this._timelineGrid.updateDividers(this._timelinePanel.calculator); }, _setVerticalClip: function(originY, height) { this._originY = originY; this._clippedHeight = height; }, _calculateXValues: function() { if (!this._counters.length) return; var width = this._canvas.width; var xFactor = width / (this._maxTime - this._minTime); this._counters[this._minimumIndex].x = 0; for (var i = this._minimumIndex + 1; i < this._maximumIndex; i++) this._counters[i].x = xFactor * (this._counters[i].time - this._minTime); this._counters[this._maximumIndex].x = width; }, _drawGraph: function(counterUI) { var canvas = this._canvas; var ctx = canvas.getContext("2d"); var width = canvas.width; var height = this._clippedHeight; var originY = this._originY; var valueGetter = counterUI.valueGetter; if (!this._counters.length) return; var maxValue; var minValue; for (var i = this._minimumIndex; i <= this._maximumIndex; i++) { var value = valueGetter(this._counters[i]); if (minValue === undefined || value < minValue) minValue = value; if (maxValue === undefined || value > maxValue) maxValue = value; } counterUI.setRange(minValue, maxValue); if (!counterUI.visible) return; var yValues = counterUI.graphYValues; yValues.length = this._counters.length; var maxYRange = maxValue - minValue; var yFactor = maxYRange ? height / (maxYRange) : 1; ctx.beginPath(); var currentY = originY + (height - (valueGetter(this._counters[this._minimumIndex])- minValue) * yFactor); ctx.moveTo(0, currentY); for (var i = this._minimumIndex; i <= this._maximumIndex; i++) { var x = this._counters[i].x; ctx.lineTo(x, currentY); currentY = originY + (height - (valueGetter(this._counters[i])- minValue) * yFactor); ctx.lineTo(x, currentY); yValues[i] = currentY; } ctx.lineTo(width, currentY); ctx.lineWidth = 1; ctx.strokeStyle = counterUI.graphColor; ctx.stroke(); ctx.closePath(); }, _clear: function() { var ctx = this._canvas.getContext("2d"); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); for (var i = 0; i < this._counterUI.length; i++) this._counterUI[i].discardImageUnderMarker(); } } ; WebInspector.TimelineModel = function() { this._records = []; this._stringPool = new StringPool(); this._minimumRecordTime = -1; this._maximumRecordTime = -1; this._collectionEnabled = false; WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, this._onRecordAdded, this); } WebInspector.TimelineModel.TransferChunkLengthBytes = 5000000; WebInspector.TimelineModel.RecordType = { Root: "Root", Program: "Program", EventDispatch: "EventDispatch", BeginFrame: "BeginFrame", ScheduleStyleRecalculation: "ScheduleStyleRecalculation", RecalculateStyles: "RecalculateStyles", InvalidateLayout: "InvalidateLayout", Layout: "Layout", Paint: "Paint", ScrollLayer: "ScrollLayer", DecodeImage: "DecodeImage", ResizeImage: "ResizeImage", CompositeLayers: "CompositeLayers", ParseHTML: "ParseHTML", TimerInstall: "TimerInstall", TimerRemove: "TimerRemove", TimerFire: "TimerFire", XHRReadyStateChange: "XHRReadyStateChange", XHRLoad: "XHRLoad", EvaluateScript: "EvaluateScript", MarkLoad: "MarkLoad", MarkDOMContent: "MarkDOMContent", TimeStamp: "TimeStamp", Time: "Time", TimeEnd: "TimeEnd", ScheduleResourceRequest: "ScheduleResourceRequest", ResourceSendRequest: "ResourceSendRequest", ResourceReceiveResponse: "ResourceReceiveResponse", ResourceReceivedData: "ResourceReceivedData", ResourceFinish: "ResourceFinish", FunctionCall: "FunctionCall", GCEvent: "GCEvent", RequestAnimationFrame: "RequestAnimationFrame", CancelAnimationFrame: "CancelAnimationFrame", FireAnimationFrame: "FireAnimationFrame" } WebInspector.TimelineModel.Events = { RecordAdded: "RecordAdded", RecordsCleared: "RecordsCleared" } WebInspector.TimelineModel.startTimeInSeconds = function(record) { return record.startTime / 1000; } WebInspector.TimelineModel.endTimeInSeconds = function(record) { return (typeof record.endTime === "undefined" ? record.startTime : record.endTime) / 1000; } WebInspector.TimelineModel.durationInSeconds = function(record) { return WebInspector.TimelineModel.endTimeInSeconds(record) - WebInspector.TimelineModel.startTimeInSeconds(record); } WebInspector.TimelineModel.aggregateTimeForRecord = function(total, rawRecord) { var childrenTime = 0; var children = rawRecord["children"] || []; for (var i = 0; i < children.length; ++i) { WebInspector.TimelineModel.aggregateTimeForRecord(total, children[i]); childrenTime += WebInspector.TimelineModel.durationInSeconds(children[i]); } var categoryName = WebInspector.TimelinePresentationModel.recordStyle(rawRecord).category.name; var ownTime = WebInspector.TimelineModel.durationInSeconds(rawRecord) - childrenTime; total[categoryName] = (total[categoryName] || 0) + ownTime; } WebInspector.TimelineModel.aggregateTimeByCategory = function(total, addend) { for (var category in addend) total[category] = (total[category] || 0) + addend[category]; } WebInspector.TimelineModel.prototype = { startRecord: function() { if (this._collectionEnabled) return; this.reset(); WebInspector.timelineManager.start(30); this._collectionEnabled = true; }, stopRecord: function() { if (!this._collectionEnabled) return; WebInspector.timelineManager.stop(); this._collectionEnabled = false; }, get records() { return this._records; }, _onRecordAdded: function(event) { if (this._collectionEnabled) this._addRecord(event.data); }, _addRecord: function(record) { this._stringPool.internObjectStrings(record); this._records.push(record); this._updateBoundaries(record); this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordAdded, record); }, loadFromFile: function(file, progress) { var delegate = new WebInspector.TimelineModelLoadFromFileDelegate(this, progress); var fileReader = this._createFileReader(file, delegate); var loader = new WebInspector.TimelineModelLoader(this, fileReader, progress); fileReader.start(loader); }, loadFromURL: function(url, progress) { var delegate = new WebInspector.TimelineModelLoadFromFileDelegate(this, progress); var urlReader = new WebInspector.ChunkedXHRReader(url, delegate); var loader = new WebInspector.TimelineModelLoader(this, urlReader, progress); urlReader.start(loader); }, _createFileReader: function(file, delegate) { return new WebInspector.ChunkedFileReader(file, WebInspector.TimelineModel.TransferChunkLengthBytes, delegate); }, _createFileWriter: function(fileName, callback) { var stream = new WebInspector.FileOutputStream(); stream.open(fileName, callback); }, saveToFile: function() { var now = new Date(); var fileName = "TimelineRawData-" + now.toISO8601Compact() + ".json"; function callback(stream) { var saver = new WebInspector.TimelineSaver(stream); saver.save(this._records, window.navigator.appVersion); } this._createFileWriter(fileName, callback.bind(this)); }, reset: function() { this._records = []; this._stringPool.reset(); this._minimumRecordTime = -1; this._maximumRecordTime = -1; this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordsCleared); }, minimumRecordTime: function() { return this._minimumRecordTime; }, maximumRecordTime: function() { return this._maximumRecordTime; }, _updateBoundaries: function(record) { var startTime = WebInspector.TimelineModel.startTimeInSeconds(record); var endTime = WebInspector.TimelineModel.endTimeInSeconds(record); if (this._minimumRecordTime === -1 || startTime < this._minimumRecordTime) this._minimumRecordTime = startTime; if (this._maximumRecordTime === -1 || endTime > this._maximumRecordTime) this._maximumRecordTime = endTime; }, recordOffsetInSeconds: function(rawRecord) { return WebInspector.TimelineModel.startTimeInSeconds(rawRecord) - this._minimumRecordTime; }, __proto__: WebInspector.Object.prototype } WebInspector.TimelineModelLoader = function(model, reader, progress) { this._model = model; this._reader = reader; this._progress = progress; this._buffer = ""; this._firstChunk = true; } WebInspector.TimelineModelLoader.prototype = { write: function(chunk) { var data = this._buffer + chunk; var lastIndex = 0; var index; do { index = lastIndex; lastIndex = WebInspector.findBalancedCurlyBrackets(data, index); } while (lastIndex !== -1) var json = data.slice(0, index) + "]"; this._buffer = data.slice(index); if (!index) return; if (!this._firstChunk) json = "[0" + json; var items; try { items = (JSON.parse(json)); } catch (e) { WebInspector.showErrorMessage("Malformed timeline data."); this._model.reset(); this._reader.cancel(); this._progress.done(); return; } if (this._firstChunk) { this._version = items[0]; this._firstChunk = false; this._model.reset(); } for (var i = 1, size = items.length; i < size; ++i) this._model._addRecord(items[i]); }, close: function() { } } WebInspector.TimelineModelLoadFromFileDelegate = function(model, progress) { this._model = model; this._progress = progress; } WebInspector.TimelineModelLoadFromFileDelegate.prototype = { onTransferStarted: function() { this._progress.setTitle(WebInspector.UIString("Loading\u2026")); }, onChunkTransferred: function(reader) { if (this._progress.isCanceled()) { reader.cancel(); this._progress.done(); this._model.reset(); return; } var totalSize = reader.fileSize(); if (totalSize) { this._progress.setTotalWork(totalSize); this._progress.setWorked(reader.loadedSize()); } }, onTransferFinished: function() { this._progress.done(); }, onError: function(reader, event) { this._progress.done(); this._model.reset(); switch (event.target.error.code) { case FileError.NOT_FOUND_ERR: WebInspector.showErrorMessage(WebInspector.UIString("File \"%s\" not found.", reader.fileName())); break; case FileError.NOT_READABLE_ERR: WebInspector.showErrorMessage(WebInspector.UIString("File \"%s\" is not readable", reader.fileName())); break; case FileError.ABORT_ERR: break; default: WebInspector.showErrorMessage(WebInspector.UIString("An error occurred while reading the file \"%s\"", reader.fileName())); } } } WebInspector.TimelineSaver = function(stream) { this._stream = stream; } WebInspector.TimelineSaver.prototype = { save: function(records, version) { this._records = records; this._recordIndex = 0; this._prologue = "[" + JSON.stringify(version); this._writeNextChunk(this._stream); }, _writeNextChunk: function(stream) { const separator = ",\n"; var data = []; var length = 0; if (this._prologue) { data.push(this._prologue); length += this._prologue.length; delete this._prologue; } else { if (this._recordIndex === this._records.length) { stream.close(); return; } data.push(""); } while (this._recordIndex < this._records.length) { var item = JSON.stringify(this._records[this._recordIndex]); var itemLength = item.length + separator.length; if (length + itemLength > WebInspector.TimelineModel.TransferChunkLengthBytes) break; length += itemLength; data.push(item); ++this._recordIndex; } if (this._recordIndex === this._records.length) data.push(data.pop() + "]"); stream.write(data.join(separator), this._writeNextChunk.bind(this)); } } ; WebInspector.TimelineOverviewPane = function(model) { WebInspector.View.call(this); this.element.id = "timeline-overview-panel"; this._windowStartTime = 0; this._windowEndTime = Infinity; this._eventDividers = []; this._model = model; this._topPaneSidebarElement = document.createElement("div"); this._topPaneSidebarElement.id = "timeline-overview-sidebar"; var overviewTreeElement = document.createElement("ol"); overviewTreeElement.className = "sidebar-tree"; this._topPaneSidebarElement.appendChild(overviewTreeElement); this.element.appendChild(this._topPaneSidebarElement); var topPaneSidebarTree = new TreeOutline(overviewTreeElement); this._currentMode = WebInspector.TimelineOverviewPane.Mode.Events; this._overviewItems = {}; this._overviewItems[WebInspector.TimelineOverviewPane.Mode.Events] = new WebInspector.SidebarTreeElement("timeline-overview-sidebar-events", WebInspector.UIString("Events")); if (Capabilities.timelineSupportsFrameInstrumentation) { this._overviewItems[WebInspector.TimelineOverviewPane.Mode.Frames] = new WebInspector.SidebarTreeElement("timeline-overview-sidebar-frames", WebInspector.UIString("Frames")); } this._overviewItems[WebInspector.TimelineOverviewPane.Mode.Memory] = new WebInspector.SidebarTreeElement("timeline-overview-sidebar-memory", WebInspector.UIString("Memory")); for (var mode in this._overviewItems) { var item = this._overviewItems[mode]; item.onselect = this.setMode.bind(this, mode); topPaneSidebarTree.appendChild(item); } this._overviewItems[this._currentMode].revealAndSelect(false); this._overviewContainer = this.element.createChild("div", "fill"); this._overviewContainer.id = "timeline-overview-container"; this._overviewGrid = new WebInspector.TimelineGrid(); this._overviewGrid.element.id = "timeline-overview-grid"; this._overviewGrid.itemsGraphsElement.id = "timeline-overview-timelines"; this._overviewContainer.appendChild(this._overviewGrid.element); this._heapGraph = new WebInspector.HeapGraph(this._model); this._heapGraph.element.id = "timeline-overview-memory"; this._overviewGrid.element.insertBefore(this._heapGraph.element, this._overviewGrid.itemsGraphsElement); this._overviewWindow = new WebInspector.TimelineOverviewWindow(this._overviewContainer, this._overviewGrid.dividersLabelBarElement); this._overviewWindow.addEventListener(WebInspector.TimelineOverviewWindow.Events.WindowChanged, this._onWindowChanged, this); var separatorElement = document.createElement("div"); separatorElement.id = "timeline-overview-separator"; this.element.appendChild(separatorElement); this._categoryStrips = new WebInspector.TimelineCategoryStrips(this._model); this._overviewGrid.itemsGraphsElement.appendChild(this._categoryStrips.element); var categories = WebInspector.TimelinePresentationModel.categories(); for (var category in categories) categories[category].addEventListener(WebInspector.TimelineCategory.Events.VisibilityChanged, this._onCategoryVisibilityChanged, this); this._overviewGrid.setScrollAndDividerTop(0, 0); this._overviewCalculator = new WebInspector.TimelineOverviewCalculator(); model.addEventListener(WebInspector.TimelineModel.Events.RecordAdded, this._onRecordAdded, this); model.addEventListener(WebInspector.TimelineModel.Events.RecordsCleared, this._reset, this); } WebInspector.TimelineOverviewPane.MinSelectableSize = 12; WebInspector.TimelineOverviewPane.WindowScrollSpeedFactor = .3; WebInspector.TimelineOverviewPane.ResizerOffset = 3.5; WebInspector.TimelineOverviewPane.Mode = { Events: "Events", Frames: "Frames", Memory: "Memory" }; WebInspector.TimelineOverviewPane.Events = { ModeChanged: "ModeChanged", WindowChanged: "WindowChanged" }; WebInspector.TimelineOverviewPane.prototype = { wasShown: function() { this._update(); }, onResize: function() { this._update(); }, setMode: function(newMode) { if (this._currentMode === newMode) return; this._currentMode = newMode; this._setFrameMode(this._currentMode === WebInspector.TimelineOverviewPane.Mode.Frames); switch (this._currentMode) { case WebInspector.TimelineOverviewPane.Mode.Events: case WebInspector.TimelineOverviewPane.Mode.Frames: this._heapGraph.hide(); this._overviewGrid.itemsGraphsElement.removeStyleClass("hidden"); break; case WebInspector.TimelineOverviewPane.Mode.Memory: this._overviewGrid.itemsGraphsElement.addStyleClass("hidden"); this._heapGraph.show(); } this._overviewItems[this._currentMode].revealAndSelect(false); this.dispatchEventToListeners(WebInspector.TimelineOverviewPane.Events.ModeChanged, this._currentMode); this._update(); }, _setFrameMode: function(enabled) { if (!enabled === !this._frameOverview) return; if (enabled) { this._frameOverview = new WebInspector.TimelineFrameOverview(this._model); this._frameOverview.show(this._overviewContainer); } else { this._frameOverview.detach(); this._frameOverview = null; this._overviewGrid.itemsGraphsElement.removeStyleClass("hidden"); this._categoryStrips.update(); } }, _onCategoryVisibilityChanged: function(event) { if (this._currentMode === WebInspector.TimelineOverviewPane.Mode.Events) this._categoryStrips.update(); }, _update: function() { delete this._refreshTimeout; this._updateWindow(); this._overviewCalculator.setWindow(this._model.minimumRecordTime(), this._model.maximumRecordTime()); this._overviewCalculator.setDisplayWindow(0, this._overviewContainer.clientWidth); if (this._heapGraph.visible) this._heapGraph.update(); else if (this._frameOverview) this._frameOverview.update(); else this._categoryStrips.update(); this._overviewGrid.updateDividers(this._overviewCalculator); this._updateEventDividers(); }, _updateEventDividers: function() { var records = this._eventDividers; this._overviewGrid.removeEventDividers(); var dividers = []; for (var i = 0; i < records.length; ++i) { var record = records[i]; var positions = this._overviewCalculator.computeBarGraphPercentages(record); var dividerPosition = Math.round(positions.start * 10); if (dividers[dividerPosition]) continue; var divider = WebInspector.TimelinePresentationModel.createEventDivider(record.type); divider.style.left = positions.start + "%"; dividers[dividerPosition] = divider; } this._overviewGrid.addEventDividers(dividers); }, sidebarResized: function(width) { this._overviewContainer.style.left = width + "px"; this._topPaneSidebarElement.style.width = width + "px"; this._update(); }, addFrame: function(frame) { this._frameOverview.addFrame(frame); this._scheduleRefresh(); }, zoomToFrame: function(frame) { var window = this._frameOverview.framePosition(frame); if (!window) return; this._overviewWindow._setWindowPosition(window.start, window.end); }, _onRecordAdded: function(event) { var record = event.data; var eventDividers = this._eventDividers; function addEventDividers(record) { if (WebInspector.TimelinePresentationModel.isEventDivider(record)) eventDividers.push(record); } WebInspector.TimelinePresentationModel.forAllRecords([record], addEventDividers); this._scheduleRefresh(); }, _reset: function() { this._windowStartTime = 0; this._windowEndTime = Infinity; this._overviewWindow.reset(); this._overviewCalculator.reset(); this._eventDividers = []; this._overviewGrid.updateDividers(this._overviewCalculator); if (this._frameOverview) this._frameOverview.reset(); this._update(); }, windowStartTime: function() { return this._windowStartTime || this._model.minimumRecordTime(); }, windowEndTime: function() { return this._windowEndTime < Infinity ? this._windowEndTime : this._model.maximumRecordTime(); }, windowLeft: function() { return this._overviewWindow.windowLeft; }, windowRight: function() { return this._overviewWindow.windowRight; }, _onWindowChanged: function() { if (this._ignoreWindowChangedEvent) return; if (this._frameOverview) { var times = this._frameOverview.getWindowTimes(this.windowLeft(), this.windowRight()); this._windowStartTime = times.startTime; this._windowEndTime = times.endTime; } else { var absoluteMin = this._model.minimumRecordTime(); var absoluteMax = this._model.maximumRecordTime(); this._windowStartTime = absoluteMin + (absoluteMax - absoluteMin) * this.windowLeft(); this._windowEndTime = absoluteMin + (absoluteMax - absoluteMin) * this.windowRight(); } this.dispatchEventToListeners(WebInspector.TimelineOverviewPane.Events.WindowChanged); }, setWindowTimes: function(left, right) { this._windowStartTime = left; this._windowEndTime = right; this._updateWindow(); }, _updateWindow: function() { var offset = this._model.minimumRecordTime(); var timeSpan = this._model.maximumRecordTime() - offset; var left = this._windowStartTime ? (this._windowStartTime - offset) / timeSpan : 0; var right = this._windowEndTime < Infinity ? (this._windowEndTime - offset) / timeSpan : 1; this._ignoreWindowChangedEvent = true; this._overviewWindow._setWindow(left, right); this._ignoreWindowChangedEvent = false; }, setMinimumRecordDuration: function(value) { this._categoryStrips.setMinimumRecordDuration(value); }, _scheduleRefresh: function() { if (this._refreshTimeout) return; if (!this.isShowing()) return; this._refreshTimeout = setTimeout(this._update.bind(this), 300); }, __proto__: WebInspector.View.prototype } WebInspector.TimelineOverviewWindow = function(parentElement, dividersLabelBarElement) { this._parentElement = parentElement; this._dividersLabelBarElement = dividersLabelBarElement; WebInspector.installDragHandle(this._parentElement, this._startWindowSelectorDragging.bind(this), this._windowSelectorDragging.bind(this), this._endWindowSelectorDragging.bind(this), "ew-resize"); WebInspector.installDragHandle(this._dividersLabelBarElement, this._startWindowDragging.bind(this), this._windowDragging.bind(this), this._endWindowDragging.bind(this), "ew-resize"); this.windowLeft = 0.0; this.windowRight = 1.0; this._parentElement.addEventListener("mousewheel", this._onMouseWheel.bind(this), true); this._parentElement.addEventListener("dblclick", this._resizeWindowMaximum.bind(this), true); this._overviewWindowElement = document.createElement("div"); this._overviewWindowElement.className = "timeline-overview-window"; parentElement.appendChild(this._overviewWindowElement); this._overviewWindowBordersElement = document.createElement("div"); this._overviewWindowBordersElement.className = "timeline-overview-window-rulers"; parentElement.appendChild(this._overviewWindowBordersElement); var overviewDividersBackground = document.createElement("div"); overviewDividersBackground.className = "timeline-overview-dividers-background"; parentElement.appendChild(overviewDividersBackground); this._leftResizeElement = document.createElement("div"); this._leftResizeElement.className = "timeline-window-resizer"; this._leftResizeElement.style.left = 0; parentElement.appendChild(this._leftResizeElement); WebInspector.installDragHandle(this._leftResizeElement, null, this._leftResizeElementDragging.bind(this), null, "ew-resize"); this._rightResizeElement = document.createElement("div"); this._rightResizeElement.className = "timeline-window-resizer timeline-window-resizer-right"; this._rightResizeElement.style.right = 0; parentElement.appendChild(this._rightResizeElement); WebInspector.installDragHandle(this._rightResizeElement, null, this._rightResizeElementDragging.bind(this), null, "ew-resize"); } WebInspector.TimelineOverviewWindow.Events = { WindowChanged: "WindowChanged" } WebInspector.TimelineOverviewWindow.prototype = { reset: function() { this.windowLeft = 0.0; this.windowRight = 1.0; this._overviewWindowElement.style.left = "0%"; this._overviewWindowElement.style.width = "100%"; this._overviewWindowBordersElement.style.left = "0%"; this._overviewWindowBordersElement.style.right = "0%"; this._leftResizeElement.style.left = "0%"; this._rightResizeElement.style.left = "100%"; }, _leftResizeElementDragging: function(event) { this._resizeWindowLeft(event.pageX - this._parentElement.offsetLeft); event.preventDefault(); }, _rightResizeElementDragging: function(event) { this._resizeWindowRight(event.pageX - this._parentElement.offsetLeft); event.preventDefault(); }, _startWindowSelectorDragging: function(event) { var position = event.pageX - this._parentElement.offsetLeft; this._overviewWindowSelector = new WebInspector.TimelineOverviewPane.WindowSelector(this._parentElement, position); return true; }, _windowSelectorDragging: function(event) { this._overviewWindowSelector._updatePosition(event.pageX - this._parentElement.offsetLeft); event.preventDefault(); }, _endWindowSelectorDragging: function(event) { var window = this._overviewWindowSelector._close(event.pageX - this._parentElement.offsetLeft); delete this._overviewWindowSelector; if (window.end === window.start) { var middle = window.end; window.start = Math.max(0, middle - WebInspector.TimelineOverviewPane.MinSelectableSize / 2); window.end = Math.min(this._parentElement.clientWidth, middle + WebInspector.TimelineOverviewPane.MinSelectableSize / 2); } else if (window.end - window.start < WebInspector.TimelineOverviewPane.MinSelectableSize) { if (this._parentElement.clientWidth - window.end > WebInspector.TimelineOverviewPane.MinSelectableSize) window.end = window.start + WebInspector.TimelineOverviewPane.MinSelectableSize; else window.start = window.end - WebInspector.TimelineOverviewPane.MinSelectableSize; } this._setWindowPosition(window.start, window.end); }, _startWindowDragging: function(event) { var windowLeft = this._leftResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.ResizerOffset; this._dragOffset = windowLeft - event.pageX; return true; }, _windowDragging: function(event) { var windowLeft = this._leftResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.ResizerOffset; var start = this._dragOffset + event.pageX; this._moveWindow(start); event.preventDefault(); }, _endWindowDragging: function(event) { delete this._dragOffset; }, _moveWindow: function(start) { var windowLeft = this._leftResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.ResizerOffset; var windowRight = this._rightResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.ResizerOffset; var windowSize = windowRight - windowLeft; var end = start + windowSize; if (start < 0) { start = 0; end = windowSize; } if (end > this._parentElement.clientWidth) { end = this._parentElement.clientWidth; start = end - windowSize; } this._setWindowPosition(start, end); }, _resizeWindowLeft: function(start) { if (start < 10) start = 0; else if (start > this._rightResizeElement.offsetLeft - 4) start = this._rightResizeElement.offsetLeft - 4; this._setWindowPosition(start, null); }, _resizeWindowRight: function(end) { if (end > this._parentElement.clientWidth - 10) end = this._parentElement.clientWidth; else if (end < this._leftResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.MinSelectableSize) end = this._leftResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.MinSelectableSize; this._setWindowPosition(null, end); }, _resizeWindowMaximum: function() { this._setWindowPosition(0, this._parentElement.clientWidth); }, _setWindow: function(left, right) { var clientWidth = this._parentElement.clientWidth; this._setWindowPosition(left * clientWidth, right * clientWidth); }, _setWindowPosition: function(start, end) { var clientWidth = this._parentElement.clientWidth; const rulerAdjustment = 1 / clientWidth; if (typeof start === "number") { this.windowLeft = start / clientWidth; this._leftResizeElement.style.left = this.windowLeft * 100 + "%"; this._overviewWindowElement.style.left = this.windowLeft * 100 + "%"; this._overviewWindowBordersElement.style.left = (this.windowLeft - rulerAdjustment) * 100 + "%"; } if (typeof end === "number") { this.windowRight = end / clientWidth; this._rightResizeElement.style.left = this.windowRight * 100 + "%"; } this._overviewWindowElement.style.width = (this.windowRight - this.windowLeft) * 100 + "%"; this._overviewWindowBordersElement.style.right = (1 - this.windowRight + 2 * rulerAdjustment) * 100 + "%"; this.dispatchEventToListeners(WebInspector.TimelineOverviewWindow.Events.WindowChanged); }, _onMouseWheel: function(event) { const zoomFactor = 1.1; const mouseWheelZoomSpeed = 1 / 120; if (typeof event.wheelDeltaY === "number" && event.wheelDeltaY) { var referencePoint = event.pageX - this._parentElement.offsetLeft; this._zoom(Math.pow(zoomFactor, -event.wheelDeltaY * mouseWheelZoomSpeed), referencePoint); } if (typeof event.wheelDeltaX === "number" && event.wheelDeltaX) { var windowLeft = this._leftResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.ResizerOffset; var start = windowLeft - Math.round(event.wheelDeltaX * WebInspector.TimelineOverviewPane.WindowScrollSpeedFactor); this._moveWindow(start); event.preventDefault(); } }, _zoom: function(factor, referencePoint) { var left = this._leftResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.ResizerOffset; var right = this._rightResizeElement.offsetLeft + WebInspector.TimelineOverviewPane.ResizerOffset; var delta = factor * (right - left); if (factor < 1 && delta < WebInspector.TimelineOverviewPane.MinSelectableSize) return; var max = this._parentElement.clientWidth; left = Math.max(0, Math.min(max - delta, referencePoint + (left - referencePoint) * factor)); right = Math.min(max, left + delta); this._setWindowPosition(left, right); }, __proto__: WebInspector.Object.prototype } WebInspector.TimelineOverviewCalculator = function() { } WebInspector.TimelineOverviewCalculator.prototype = { computePosition: function(time) { return (time - this._minimumBoundary) / this.boundarySpan() * this._workingArea + this.paddingLeft; }, computeBarGraphPercentages: function(record) { var start = (WebInspector.TimelineModel.startTimeInSeconds(record) - this._minimumBoundary) / this.boundarySpan() * 100; var end = (WebInspector.TimelineModel.endTimeInSeconds(record) - this._minimumBoundary) / this.boundarySpan() * 100; return {start: start, end: end}; }, setWindow: function(minimum, maximum) { this._minimumBoundary = minimum >= 0 ? minimum : undefined; this._maximumBoundary = maximum >= 0 ? maximum : undefined; }, setDisplayWindow: function(paddingLeft, clientWidth) { this._workingArea = clientWidth - paddingLeft; this.paddingLeft = paddingLeft; }, reset: function() { this.setWindow(); }, formatTime: function(value) { return Number.secondsToString(value); }, maximumBoundary: function() { return this._maximumBoundary; }, minimumBoundary: function() { return this._minimumBoundary; }, boundarySpan: function() { return this._maximumBoundary - this._minimumBoundary; } } WebInspector.TimelineOverviewPane.WindowSelector = function(parent, position) { this._startPosition = position; this._width = parent.offsetWidth; this._windowSelector = document.createElement("div"); this._windowSelector.className = "timeline-window-selector"; this._windowSelector.style.left = this._startPosition + "px"; this._windowSelector.style.right = this._width - this._startPosition + + "px"; parent.appendChild(this._windowSelector); } WebInspector.TimelineOverviewPane.WindowSelector.prototype = { _createSelectorElement: function(parent, left, width, height) { var selectorElement = document.createElement("div"); selectorElement.className = "timeline-window-selector"; selectorElement.style.left = left + "px"; selectorElement.style.width = width + "px"; selectorElement.style.top = "0px"; selectorElement.style.height = height + "px"; parent.appendChild(selectorElement); return selectorElement; }, _close: function(position) { position = Math.max(0, Math.min(position, this._width)); this._windowSelector.parentNode.removeChild(this._windowSelector); return this._startPosition < position ? {start: this._startPosition, end: position} : {start: position, end: this._startPosition}; }, _updatePosition: function(position) { position = Math.max(0, Math.min(position, this._width)); if (position < this._startPosition) { this._windowSelector.style.left = position + "px"; this._windowSelector.style.right = this._width - this._startPosition + "px"; } else { this._windowSelector.style.left = this._startPosition + "px"; this._windowSelector.style.right = this._width - position + "px"; } } } WebInspector.HeapGraph = function(model) { this._canvas = document.createElement("canvas"); this._model = model; this._maxHeapSizeLabel = document.createElement("div"); this._maxHeapSizeLabel.addStyleClass("max"); this._maxHeapSizeLabel.addStyleClass("memory-graph-label"); this._minHeapSizeLabel = document.createElement("div"); this._minHeapSizeLabel.addStyleClass("min"); this._minHeapSizeLabel.addStyleClass("memory-graph-label"); this._element = document.createElement("div"); this._element.addStyleClass("hidden"); this._element.appendChild(this._canvas); this._element.appendChild(this._maxHeapSizeLabel); this._element.appendChild(this._minHeapSizeLabel); } WebInspector.HeapGraph.prototype = { get element() { return this._element; }, get visible() { return !this.element.hasStyleClass("hidden"); }, show: function() { this.element.removeStyleClass("hidden"); }, hide: function() { this.element.addStyleClass("hidden"); }, update: function() { var records = this._model.records; if (!records.length) return; const yPadding = 5; this._canvas.width = this.element.clientWidth; this._canvas.height = this.element.clientHeight - yPadding; const lowerOffset = 3; var maxUsedHeapSize = 0; var minUsedHeapSize = 100000000000; var minTime = this._model.minimumRecordTime(); var maxTime = this._model.maximumRecordTime();; WebInspector.TimelinePresentationModel.forAllRecords(records, function(r) { maxUsedHeapSize = Math.max(maxUsedHeapSize, r.usedHeapSize || maxUsedHeapSize); minUsedHeapSize = Math.min(minUsedHeapSize, r.usedHeapSize || minUsedHeapSize); }); minUsedHeapSize = Math.min(minUsedHeapSize, maxUsedHeapSize); var width = this._canvas.width; var height = this._canvas.height - lowerOffset; var xFactor = width / (maxTime - minTime); var yFactor = height / (maxUsedHeapSize - minUsedHeapSize); var histogram = new Array(width); WebInspector.TimelinePresentationModel.forAllRecords(records, function(r) { if (!r.usedHeapSize) return; var x = Math.round((WebInspector.TimelineModel.endTimeInSeconds(r) - minTime) * xFactor); var y = Math.round((r.usedHeapSize - minUsedHeapSize) * yFactor); histogram[x] = Math.max(histogram[x] || 0, y); }); var ctx = this._canvas.getContext("2d"); this._clear(ctx); height = height + 1; ctx.beginPath(); var initialY = 0; for (var k = 0; k < histogram.length; k++) { if (histogram[k]) { initialY = histogram[k]; break; } } ctx.moveTo(0, height - initialY); for (var x = 0; x < histogram.length; x++) { if (!histogram[x]) continue; ctx.lineTo(x, height - histogram[x]); } ctx.lineWidth = 0.5; ctx.strokeStyle = "rgba(20,0,0,0.8)"; ctx.stroke(); ctx.fillStyle = "rgba(214,225,254, 0.8);"; ctx.lineTo(width, 60); ctx.lineTo(0, 60); ctx.lineTo(0, height - initialY); ctx.fill(); ctx.closePath(); this._maxHeapSizeLabel.textContent = Number.bytesToString(maxUsedHeapSize); this._minHeapSizeLabel.textContent = Number.bytesToString(minUsedHeapSize); }, _clear: function(ctx) { ctx.fillStyle = "rgba(255,255,255,0.8)"; ctx.fillRect(0, 0, this._canvas.width, this._canvas.height); }, } WebInspector.TimelineCategoryStrips = function(model) { this._model = model; this.element = document.createElement("canvas"); this._context = this.element.getContext("2d"); this._minimumRecordDuration = 0; this._fillStyles = {}; var categories = WebInspector.TimelinePresentationModel.categories(); for (var category in categories) this._fillStyles[category] = WebInspector.TimelinePresentationModel.createFillStyleForCategory(this._context, 0, WebInspector.TimelineCategoryStrips._innerStripHeight, categories[category]); this._disabledCategoryFillStyle = WebInspector.TimelinePresentationModel.createFillStyle(this._context, 0, WebInspector.TimelineCategoryStrips._innerStripHeight, "rgb(218, 218, 218)", "rgb(170, 170, 170)", "rgb(143, 143, 143)"); this._disabledCategoryBorderStyle = "rgb(143, 143, 143)"; } WebInspector.TimelineCategoryStrips._canvasHeight = 60; WebInspector.TimelineCategoryStrips._numberOfStrips = 3; WebInspector.TimelineCategoryStrips._stripHeight = Math.round(WebInspector.TimelineCategoryStrips._canvasHeight / WebInspector.TimelineCategoryStrips._numberOfStrips); WebInspector.TimelineCategoryStrips._stripPadding = 4; WebInspector.TimelineCategoryStrips._innerStripHeight = WebInspector.TimelineCategoryStrips._stripHeight - 2 * WebInspector.TimelineCategoryStrips._stripPadding; WebInspector.TimelineCategoryStrips.prototype = { update: function() { this.element.width = this.element.parentElement.clientWidth; this.element.height = WebInspector.TimelineCategoryStrips._canvasHeight; var timeOffset = this._model.minimumRecordTime(); var timeSpan = this._model.maximumRecordTime() - timeOffset; var scale = this.element.width / timeSpan; var lastBarByGroup = []; this._context.fillStyle = "rgba(0, 0, 0, 0.05)"; for (var i = 1; i < WebInspector.TimelineCategoryStrips._numberOfStrips; i += 2) this._context.fillRect(0.5, i * WebInspector.TimelineCategoryStrips._stripHeight + 0.5, this.element.width, WebInspector.TimelineCategoryStrips._stripHeight); function appendRecord(record) { if (!!this._minimumRecordDuration && (WebInspector.TimelineModel.durationInSeconds(record) < this._minimumRecordDuration)) return; if (record.type === WebInspector.TimelineModel.RecordType.BeginFrame) return; var recordStart = Math.floor((WebInspector.TimelineModel.startTimeInSeconds(record) - timeOffset) * scale); var recordEnd = Math.ceil((WebInspector.TimelineModel.endTimeInSeconds(record) - timeOffset) * scale); var category = WebInspector.TimelinePresentationModel.categoryForRecord(record); if (category.overviewStripGroupIndex < 0) return; var bar = lastBarByGroup[category.overviewStripGroupIndex]; const barsMergeThreshold = 2; if (bar && bar.category === category && bar.end + barsMergeThreshold >= recordStart) { if (recordEnd > bar.end) bar.end = recordEnd; return; } if (bar) this._renderBar(bar.start, bar.end, bar.category); lastBarByGroup[category.overviewStripGroupIndex] = { start: recordStart, end: recordEnd, category: category }; } WebInspector.TimelinePresentationModel.forAllRecords(this._model.records, appendRecord.bind(this)); for (var i = 0; i < lastBarByGroup.length; ++i) { if (lastBarByGroup[i]) this._renderBar(lastBarByGroup[i].start, lastBarByGroup[i].end, lastBarByGroup[i].category); } }, setMinimumRecordDuration: function(value) { this._minimumRecordDuration = value; this.update(); }, _renderBar: function(begin, end, category) { var x = begin + 0.5; var y = category.overviewStripGroupIndex * WebInspector.TimelineCategoryStrips._stripHeight + WebInspector.TimelineCategoryStrips._stripPadding + 0.5; var width = Math.max(end - begin, 1); this._context.save(); this._context.translate(x, y); this._context.fillStyle = category.hidden ? this._disabledCategoryFillStyle : this._fillStyles[category.name]; this._context.fillRect(0, 0, width, WebInspector.TimelineCategoryStrips._innerStripHeight); this._context.strokeStyle = category.hidden ? this._disabledCategoryBorderStyle : category.borderColor; this._context.strokeRect(0, 0, width, WebInspector.TimelineCategoryStrips._innerStripHeight); this._context.restore(); } } WebInspector.TimelineFrameOverview = function(model) { WebInspector.View.call(this); this.element = document.createElement("canvas"); this.element.className = "timeline-frame-overview-bars fill"; this._model = model; this.reset(); this._outerPadding = 4; this._maxInnerBarWidth = 10; this._actualPadding = 5; this._actualOuterBarWidth = this._maxInnerBarWidth + this._actualPadding; this._context = this.element.getContext("2d"); this._fillStyles = {}; var categories = WebInspector.TimelinePresentationModel.categories(); for (var category in categories) this._fillStyles[category] = WebInspector.TimelinePresentationModel.createFillStyleForCategory(this._context, this._maxInnerBarWidth, 0, categories[category]); } WebInspector.TimelineFrameOverview.prototype = { reset: function() { this._recordsPerBar = 1; this._barTimes = []; this._frames = []; }, update: function() { const minBarWidth = 4; this._framesPerBar = Math.max(1, this._frames.length * minBarWidth / this.element.clientWidth); this._barTimes = []; var visibleFrames = this._aggregateFrames(this._framesPerBar); const paddingTop = 4; const targetFPS = 30; var fullBarLength = 1.0 / targetFPS; if (fullBarLength < this._medianFrameLength) fullBarLength = Math.min(this._medianFrameLength * 2, this._maxFrameLength); var scale = (this.element.clientHeight - paddingTop) / fullBarLength; this._renderBars(visibleFrames, scale); }, addFrame: function(frame) { this._frames.push(frame); }, framePosition: function(frame) { var frameNumber = this._frames.indexOf(frame); if (frameNumber < 0) return; var barNumber = Math.floor(frameNumber / this._framesPerBar); var firstBar = this._framesPerBar > 1 ? barNumber : Math.max(barNumber - 1, 0); var lastBar = this._framesPerBar > 1 ? barNumber : Math.min(barNumber + 1, this._barTimes.length - 1); return { start: Math.ceil(this._barNumberToScreenPosition(firstBar) - this._actualPadding / 2), end: Math.floor(this._barNumberToScreenPosition(lastBar + 1) - this._actualPadding / 2) } }, _aggregateFrames: function(framesPerBar) { var visibleFrames = []; var durations = []; this._maxFrameLength = 0; for (var barNumber = 0, currentFrame = 0; currentFrame < this._frames.length; ++barNumber) { var barStartTime = this._frames[currentFrame].startTime; var longestFrame = null; for (var lastFrame = Math.min(Math.floor((barNumber + 1) * framesPerBar), this._frames.length); currentFrame < lastFrame; ++currentFrame) { if (!longestFrame || longestFrame.duration < this._frames[currentFrame].duration) longestFrame = this._frames[currentFrame]; } var barEndTime = this._frames[currentFrame - 1].endTime; if (longestFrame) { this._maxFrameLength = Math.max(this._maxFrameLength, longestFrame.duration); visibleFrames.push(longestFrame); this._barTimes.push({ startTime: barStartTime, endTime: barEndTime }); durations.push(longestFrame.duration); } } this._medianFrameLength = durations.qselect(Math.floor(durations.length / 2)); return visibleFrames; }, _renderBars: function(frames, scale) { this.element.width = this.element.clientWidth; this.element.height = this.element.clientHeight; const maxPadding = 5; this._actualOuterBarWidth = Math.min((this.element.width - 2 * this._outerPadding) / frames.length, this._maxInnerBarWidth + maxPadding); this._actualPadding = Math.min(Math.floor(this._actualOuterBarWidth / 3), maxPadding); var barWidth = this._actualOuterBarWidth - this._actualPadding; for (var i = 0; i < frames.length; ++i) this._renderBar(this._barNumberToScreenPosition(i), barWidth, frames[i], scale); this._drawFPSMarks(scale); }, _barNumberToScreenPosition: function(n) { return this._outerPadding + this._actualOuterBarWidth * n; }, _drawFPSMarks: function(scale) { const fpsMarks = [30, 60]; this._context.save(); this._context.beginPath(); this._context.font = "9px monospace"; this._context.textAlign = "right"; this._context.textBaseline = "top"; const labelPadding = 2; var lineHeight = 12; var labelTopMargin = 0; for (var i = 0; i < fpsMarks.length; ++i) { var fps = fpsMarks[i]; var y = this.element.height - Math.floor(1.0 / fps * scale) - 0.5; var label = fps + " FPS "; var labelWidth = this._context.measureText(label).width; var labelX = this.element.width; var labelY; if (labelTopMargin < y - lineHeight) labelY = y - lineHeight; else if (y + lineHeight < this.element.height) labelY = y; else break; this._context.moveTo(0, y); this._context.lineTo(this.element.width, y); this._context.fillStyle = "rgba(255, 255, 255, 0.75)"; this._context.fillRect(labelX - labelWidth - labelPadding, labelY, labelWidth + 2 * labelPadding, lineHeight); this._context.fillStyle = "rgb(0, 0, 0)"; this._context.fillText(label, labelX, labelY); labelTopMargin = labelY + lineHeight; } this._context.strokeStyle = "rgb(51, 51, 51)"; this._context.stroke(); this._context.restore(); }, _renderBar: function(left, width, frame, scale) { var categories = Object.keys(WebInspector.TimelinePresentationModel.categories()); if (!categories.length) return; var x = Math.floor(left) + 0.5; width = Math.floor(width); for (var i = 0, bottomOffset = this.element.height; i < categories.length; ++i) { var category = categories[i]; var duration = frame.timeByCategory[category]; if (!duration) continue; var height = duration * scale; var y = Math.floor(bottomOffset - height) + 0.5; this._context.save(); this._context.translate(x, 0); this._context.scale(width / this._maxInnerBarWidth, 1); this._context.fillStyle = this._fillStyles[category]; this._context.fillRect(0, y, this._maxInnerBarWidth, Math.floor(height)); this._context.restore(); this._context.strokeStyle = WebInspector.TimelinePresentationModel.categories()[category].borderColor; this._context.strokeRect(x, y, width, Math.floor(height)); bottomOffset -= height - 1; } var nonCPUTime = frame.duration - frame.cpuTime; var y0 = Math.floor(bottomOffset - nonCPUTime * scale) + 0.5; var y1 = Math.floor(bottomOffset) + 0.5; this._context.strokeStyle = "rgb(90, 90, 90)"; this._context.beginPath(); this._context.moveTo(x, y1); this._context.lineTo(x, y0); this._context.lineTo(x + width, y0); this._context.lineTo(x + width, y1); this._context.stroke(); }, getWindowTimes: function(windowLeft, windowRight) { var windowSpan = this.element.clientWidth; var leftOffset = windowLeft * windowSpan - this._outerPadding + this._actualPadding; var rightOffset = windowRight * windowSpan - this._outerPadding; var bars = this.element.children; var firstBar = Math.floor(Math.max(leftOffset, 0) / this._actualOuterBarWidth); var lastBar = Math.min(Math.floor(rightOffset / this._actualOuterBarWidth), this._barTimes.length - 1); const snapToRightTolerancePixels = 3; return { startTime: firstBar >= this._barTimes.length ? Infinity : this._barTimes[firstBar].startTime, endTime: rightOffset + snapToRightTolerancePixels > windowSpan ? Infinity : this._barTimes[lastBar].endTime } }, __proto__: WebInspector.View.prototype } WebInspector.TimelineWindowFilter = function(pane) { this._pane = pane; } WebInspector.TimelineWindowFilter.prototype = { accept: function(record) { return record.lastChildEndTime >= this._pane._windowStartTime && record.startTime <= this._pane._windowEndTime; } } ; WebInspector.TimelinePresentationModel = function() { this._linkifier = new WebInspector.Linkifier(); this._glueRecords = false; this._filters = []; this.reset(); } WebInspector.TimelinePresentationModel.categories = function() { if (WebInspector.TimelinePresentationModel._categories) return WebInspector.TimelinePresentationModel._categories; WebInspector.TimelinePresentationModel._categories = { program: new WebInspector.TimelineCategory("program", WebInspector.UIString("Program"), -1, "#BBBBBB", "#DDDDDD", "#FFFFFF"), loading: new WebInspector.TimelineCategory("loading", WebInspector.UIString("Loading"), 0, "#5A8BCC", "#8EB6E9", "#70A2E3"), scripting: new WebInspector.TimelineCategory("scripting", WebInspector.UIString("Scripting"), 1, "#D8AA34", "#F3D07A", "#F1C453"), rendering: new WebInspector.TimelineCategory("rendering", WebInspector.UIString("Rendering"), 2, "#8266CC", "#AF9AEB", "#9A7EE6"), painting: new WebInspector.TimelineCategory("painting", WebInspector.UIString("Painting"), 2, "#5FA050", "#8DC286", "#71B363") }; return WebInspector.TimelinePresentationModel._categories; }; WebInspector.TimelinePresentationModel._initRecordStyles = function() { if (WebInspector.TimelinePresentationModel._recordStylesMap) return WebInspector.TimelinePresentationModel._recordStylesMap; var recordTypes = WebInspector.TimelineModel.RecordType; var categories = WebInspector.TimelinePresentationModel.categories(); var recordStyles = {}; recordStyles[recordTypes.Root] = { title: "#root", category: categories["loading"] }; recordStyles[recordTypes.Program] = { title: WebInspector.UIString("Program"), category: categories["program"] }; recordStyles[recordTypes.EventDispatch] = { title: WebInspector.UIString("Event"), category: categories["scripting"] }; recordStyles[recordTypes.BeginFrame] = { title: WebInspector.UIString("Frame Start"), category: categories["rendering"] }; recordStyles[recordTypes.ScheduleStyleRecalculation] = { title: WebInspector.UIString("Schedule Style Recalculation"), category: categories["rendering"] }; recordStyles[recordTypes.RecalculateStyles] = { title: WebInspector.UIString("Recalculate Style"), category: categories["rendering"] }; recordStyles[recordTypes.InvalidateLayout] = { title: WebInspector.UIString("Invalidate Layout"), category: categories["rendering"] }; recordStyles[recordTypes.Layout] = { title: WebInspector.UIString("Layout"), category: categories["rendering"] }; recordStyles[recordTypes.Paint] = { title: WebInspector.UIString("Paint"), category: categories["painting"] }; recordStyles[recordTypes.ScrollLayer] = { title: WebInspector.UIString("Scroll"), category: categories["painting"] }; recordStyles[recordTypes.DecodeImage] = { title: WebInspector.UIString("Image Decode"), category: categories["painting"] }; recordStyles[recordTypes.ResizeImage] = { title: WebInspector.UIString("Image Resize"), category: categories["painting"] }; recordStyles[recordTypes.CompositeLayers] = { title: WebInspector.UIString("Composite Layers"), category: categories["painting"] }; recordStyles[recordTypes.ParseHTML] = { title: WebInspector.UIString("Parse HTML"), category: categories["loading"] }; recordStyles[recordTypes.TimerInstall] = { title: WebInspector.UIString("Install Timer"), category: categories["scripting"] }; recordStyles[recordTypes.TimerRemove] = { title: WebInspector.UIString("Remove Timer"), category: categories["scripting"] }; recordStyles[recordTypes.TimerFire] = { title: WebInspector.UIString("Timer Fired"), category: categories["scripting"] }; recordStyles[recordTypes.XHRReadyStateChange] = { title: WebInspector.UIString("XHR Ready State Change"), category: categories["scripting"] }; recordStyles[recordTypes.XHRLoad] = { title: WebInspector.UIString("XHR Load"), category: categories["scripting"] }; recordStyles[recordTypes.EvaluateScript] = { title: WebInspector.UIString("Evaluate Script"), category: categories["scripting"] }; recordStyles[recordTypes.ResourceSendRequest] = { title: WebInspector.UIString("Send Request"), category: categories["loading"] }; recordStyles[recordTypes.ResourceReceiveResponse] = { title: WebInspector.UIString("Receive Response"), category: categories["loading"] }; recordStyles[recordTypes.ResourceFinish] = { title: WebInspector.UIString("Finish Loading"), category: categories["loading"] }; recordStyles[recordTypes.FunctionCall] = { title: WebInspector.UIString("Function Call"), category: categories["scripting"] }; recordStyles[recordTypes.ResourceReceivedData] = { title: WebInspector.UIString("Receive Data"), category: categories["loading"] }; recordStyles[recordTypes.GCEvent] = { title: WebInspector.UIString("GC Event"), category: categories["scripting"] }; recordStyles[recordTypes.MarkDOMContent] = { title: WebInspector.UIString("DOMContentLoaded event"), category: categories["scripting"] }; recordStyles[recordTypes.MarkLoad] = { title: WebInspector.UIString("Load event"), category: categories["scripting"] }; recordStyles[recordTypes.TimeStamp] = { title: WebInspector.UIString("Stamp"), category: categories["scripting"] }; recordStyles[recordTypes.Time] = { title: WebInspector.UIString("Time"), category: categories["scripting"] }; recordStyles[recordTypes.TimeEnd] = { title: WebInspector.UIString("Time End"), category: categories["scripting"] }; recordStyles[recordTypes.ScheduleResourceRequest] = { title: WebInspector.UIString("Schedule Request"), category: categories["loading"] }; recordStyles[recordTypes.RequestAnimationFrame] = { title: WebInspector.UIString("Request Animation Frame"), category: categories["scripting"] }; recordStyles[recordTypes.CancelAnimationFrame] = { title: WebInspector.UIString("Cancel Animation Frame"), category: categories["scripting"] }; recordStyles[recordTypes.FireAnimationFrame] = { title: WebInspector.UIString("Animation Frame Fired"), category: categories["scripting"] }; WebInspector.TimelinePresentationModel._recordStylesMap = recordStyles; return recordStyles; } WebInspector.TimelinePresentationModel.recordStyle = function(record) { var recordStyles = WebInspector.TimelinePresentationModel._initRecordStyles(); var result = recordStyles[record.type]; if (!result) { result = { title: WebInspector.UIString("Unknown: %s", record.type), category: WebInspector.TimelinePresentationModel.categories()["program"] }; recordStyles[record.type] = result; } return result; } WebInspector.TimelinePresentationModel.categoryForRecord = function(record) { return WebInspector.TimelinePresentationModel.recordStyle(record).category; } WebInspector.TimelinePresentationModel.isEventDivider = function(record) { var recordTypes = WebInspector.TimelineModel.RecordType; if (record.type === recordTypes.TimeStamp) return true; if (record.type === recordTypes.MarkDOMContent || record.type === recordTypes.MarkLoad) { var mainFrame = WebInspector.resourceTreeModel.mainFrame; if (mainFrame && mainFrame.id === record.frameId) return true; } return false; } WebInspector.TimelinePresentationModel.forAllRecords = function(recordsArray, preOrderCallback, postOrderCallback) { if (!recordsArray) return; var stack = [{array: recordsArray, index: 0}]; while (stack.length) { var entry = stack[stack.length - 1]; var records = entry.array; if (entry.index < records.length) { var record = records[entry.index]; if (preOrderCallback && preOrderCallback(record)) return; if (record.children) stack.push({array: record.children, index: 0, record: record}); else if (postOrderCallback && postOrderCallback(record)) return; ++entry.index; } else { if (entry.record && postOrderCallback && postOrderCallback(entry.record)) return; stack.pop(); } } } WebInspector.TimelinePresentationModel.needsPreviewElement = function(recordType) { if (!recordType) return false; const recordTypes = WebInspector.TimelineModel.RecordType; switch (recordType) { case recordTypes.ScheduleResourceRequest: case recordTypes.ResourceSendRequest: case recordTypes.ResourceReceiveResponse: case recordTypes.ResourceReceivedData: case recordTypes.ResourceFinish: return true; default: return false; } } WebInspector.TimelinePresentationModel.createEventDivider = function(recordType, title) { var eventDivider = document.createElement("div"); eventDivider.className = "resources-event-divider"; var recordTypes = WebInspector.TimelineModel.RecordType; if (recordType === recordTypes.MarkDOMContent) eventDivider.className += " resources-blue-divider"; else if (recordType === recordTypes.MarkLoad) eventDivider.className += " resources-red-divider"; else if (recordType === recordTypes.TimeStamp) eventDivider.className += " resources-orange-divider"; else if (recordType === recordTypes.BeginFrame) eventDivider.className += " timeline-frame-divider"; if (title) eventDivider.title = title; return eventDivider; } WebInspector.TimelinePresentationModel._hiddenRecords = { } WebInspector.TimelinePresentationModel._hiddenRecords[WebInspector.TimelineModel.RecordType.MarkDOMContent] = 1; WebInspector.TimelinePresentationModel._hiddenRecords[WebInspector.TimelineModel.RecordType.MarkLoad] = 1; WebInspector.TimelinePresentationModel._hiddenRecords[WebInspector.TimelineModel.RecordType.ScheduleStyleRecalculation] = 1; WebInspector.TimelinePresentationModel._hiddenRecords[WebInspector.TimelineModel.RecordType.InvalidateLayout] = 1; WebInspector.TimelinePresentationModel.prototype = { addFilter: function(filter) { this._filters.push(filter); }, removeFilter: function(filter) { var index = this._filters.indexOf(filter); if (index !== -1) this._filters.splice(index, 1); }, rootRecord: function() { return this._rootRecord; }, frames: function() { return this._frames; }, reset: function() { this._linkifier.reset(); this._rootRecord = new WebInspector.TimelinePresentationModel.Record(this, { type: WebInspector.TimelineModel.RecordType.Root }, null, null, null, false); this._sendRequestRecords = {}; this._scheduledResourceRequests = {}; this._timerRecords = {}; this._requestAnimationFrameRecords = {}; this._timeRecords = {}; this._frames = []; this._minimumRecordTime = -1; this._lastInvalidateLayout = {}; this._lastScheduleStyleRecalculation = {}; }, addFrame: function(frame) { this._frames.push(frame); }, addRecord: function(record) { if (this._minimumRecordTime === -1 || record.startTime < this._minimumRecordTime) this._minimumRecordTime = WebInspector.TimelineModel.startTimeInSeconds(record); var records; if (record.type === WebInspector.TimelineModel.RecordType.Program) records = record.children; else records = [record]; var formattedRecords = []; var recordsCount = records.length; for (var i = 0; i < recordsCount; ++i) formattedRecords.push(this._innerAddRecord(records[i], this._rootRecord)); return formattedRecords; }, _innerAddRecord: function(record, parentRecord) { const recordTypes = WebInspector.TimelineModel.RecordType; var isHiddenRecord = record.type in WebInspector.TimelinePresentationModel._hiddenRecords; var origin; if (!isHiddenRecord) { var newParentRecord = this._findParentRecord(record); if (newParentRecord) { origin = parentRecord; parentRecord = newParentRecord; } } var children = record.children; var scriptDetails; if (record.data && record.data["scriptName"]) { scriptDetails = { scriptName: record.data["scriptName"], scriptLine: record.data["scriptLine"] } }; if ((record.type === recordTypes.TimerFire || record.type === recordTypes.FireAnimationFrame) && children && children.length) { var childRecord = children[0]; if (childRecord.type === recordTypes.FunctionCall) { scriptDetails = { scriptName: childRecord.data["scriptName"], scriptLine: childRecord.data["scriptLine"] }; children = childRecord.children.concat(children.slice(1)); } } var formattedRecord = new WebInspector.TimelinePresentationModel.Record(this, record, parentRecord, origin, scriptDetails, isHiddenRecord); if (isHiddenRecord) return formattedRecord; formattedRecord.collapsed = (parentRecord === this._rootRecord); var childrenCount = children ? children.length : 0; for (var i = 0; i < childrenCount; ++i) this._innerAddRecord(children[i], formattedRecord); formattedRecord.calculateAggregatedStats(WebInspector.TimelinePresentationModel.categories()); if (origin) { var lastChildEndTime = formattedRecord.lastChildEndTime; var aggregatedStats = formattedRecord.aggregatedStats; for (var currentRecord = formattedRecord.parent; !currentRecord.isRoot(); currentRecord = currentRecord.parent) { currentRecord._cpuTime += formattedRecord._cpuTime; if (currentRecord.lastChildEndTime < lastChildEndTime) currentRecord.lastChildEndTime = lastChildEndTime; for (var category in aggregatedStats) currentRecord.aggregatedStats[category] += aggregatedStats[category]; } } origin = formattedRecord.origin(); if (!origin.isRoot()) { origin.selfTime -= formattedRecord.endTime - formattedRecord.startTime; } return formattedRecord; }, _findParentRecord: function(record) { if (!this._glueRecords) return null; var recordTypes = WebInspector.TimelineModel.RecordType; switch (record.type) { case recordTypes.ResourceReceiveResponse: case recordTypes.ResourceFinish: case recordTypes.ResourceReceivedData: return this._sendRequestRecords[record.data["requestId"]]; case recordTypes.ResourceSendRequest: return this._rootRecord; case recordTypes.TimerFire: return this._timerRecords[record.data["timerId"]]; case recordTypes.ResourceSendRequest: return this._scheduledResourceRequests[record.data["url"]]; case recordTypes.FireAnimationFrame: return this._requestAnimationFrameRecords[record.data["id"]]; case recordTypes.Time: return this._rootRecord; case recordTypes.TimeEnd: return this._timeRecords[record.data["message"]]; } }, setGlueRecords: function(glue) { this._glueRecords = glue; }, invalidateFilteredRecords: function() { delete this._filteredRecords; }, filteredRecords: function() { if (this._filteredRecords) return this._filteredRecords; var recordsInWindow = []; var stack = [{children: this._rootRecord.children, index: 0, parentIsCollapsed: false}]; while (stack.length) { var entry = stack[stack.length - 1]; var records = entry.children; if (records && entry.index < records.length) { var record = records[entry.index]; ++entry.index; if (this.isVisible(record)) { ++record.parent._invisibleChildrenCount; if (!entry.parentIsCollapsed) recordsInWindow.push(record); } record._invisibleChildrenCount = 0; stack.push({children: record.children, index: 0, parentIsCollapsed: (entry.parentIsCollapsed || record.collapsed), parentRecord: record, windowLengthBeforeChildrenTraversal: recordsInWindow.length}); } else { stack.pop(); if (entry.parentRecord) entry.parentRecord._visibleChildrenCount = recordsInWindow.length - entry.windowLengthBeforeChildrenTraversal; } } this._filteredRecords = recordsInWindow; return recordsInWindow; }, filteredFrames: function(startTime, endTime) { function compareStartTime(value, object) { return value - object.startTime; } function compareEndTime(value, object) { return value - object.endTime; } var firstFrame = insertionIndexForObjectInListSortedByFunction(startTime, this._frames, compareStartTime); var lastFrame = insertionIndexForObjectInListSortedByFunction(endTime, this._frames, compareEndTime); while (lastFrame < this._frames.length && this._frames[lastFrame].endTime <= endTime) ++lastFrame; return this._frames.slice(firstFrame, lastFrame); }, isVisible: function(record) { for (var i = 0; i < this._filters.length; ++i) { if (!this._filters[i].accept(record)) return false; } return true; }, generateMainThreadBarPopupContent: function(info) { var firstTaskIndex = info.firstTaskIndex; var lastTaskIndex = info.lastTaskIndex; var tasks = info.tasks; var messageCount = lastTaskIndex - firstTaskIndex + 1; var cpuTime = 0; for (var i = firstTaskIndex; i <= lastTaskIndex; ++i) { var task = tasks[i]; cpuTime += task.endTime - task.startTime; } var startTime = tasks[firstTaskIndex].startTime; var endTime = tasks[lastTaskIndex].endTime; var duration = endTime - startTime; var offset = this._minimumRecordTime; var contentHelper = new WebInspector.TimelinePresentationModel.PopupContentHelper(WebInspector.UIString("CPU")); var durationText = WebInspector.UIString("%s (at %s)", Number.secondsToString(duration, true), Number.secondsToString(startTime - offset, true)); contentHelper._appendTextRow(WebInspector.UIString("Duration"), durationText); contentHelper._appendTextRow(WebInspector.UIString("CPU time"), Number.secondsToString(cpuTime, true)); contentHelper._appendTextRow(WebInspector.UIString("Message Count"), messageCount); return contentHelper._contentTable; }, __proto__: WebInspector.Object.prototype } WebInspector.TimelinePresentationModel.Record = function(presentationModel, record, parentRecord, origin, scriptDetails, hidden) { this._linkifier = presentationModel._linkifier; this._aggregatedStats = []; this._record = record; this._children = []; if (!hidden && parentRecord) { this.parent = parentRecord; parentRecord.children.push(this); } if (origin) this._origin = origin; this._selfTime = this.endTime - this.startTime; this._lastChildEndTime = this.endTime; this._startTimeOffset = this.startTime - presentationModel._minimumRecordTime; if (record.data && record.data["url"]) this.url = record.data["url"]; if (scriptDetails) { this.scriptName = scriptDetails.scriptName; this.scriptLine = scriptDetails.scriptLine; } if (parentRecord && parentRecord.callSiteStackTrace) this.callSiteStackTrace = parentRecord.callSiteStackTrace; var recordTypes = WebInspector.TimelineModel.RecordType; switch (record.type) { case recordTypes.ResourceSendRequest: presentationModel._sendRequestRecords[record.data["requestId"]] = this; break; case recordTypes.ScheduleResourceRequest: presentationModel._scheduledResourceRequests[record.data["url"]] = this; break; case recordTypes.ResourceReceiveResponse: var sendRequestRecord = presentationModel._sendRequestRecords[record.data["requestId"]]; if (sendRequestRecord) { this.url = sendRequestRecord.url; sendRequestRecord._refreshDetails(); if (sendRequestRecord.parent !== presentationModel._rootRecord && sendRequestRecord.parent.type === recordTypes.ScheduleResourceRequest) sendRequestRecord.parent._refreshDetails(); } break; case recordTypes.ResourceReceivedData: case recordTypes.ResourceFinish: var sendRequestRecord = presentationModel._sendRequestRecords[record.data["requestId"]]; if (sendRequestRecord) this.url = sendRequestRecord.url; break; case recordTypes.TimerInstall: this.timeout = record.data["timeout"]; this.singleShot = record.data["singleShot"]; presentationModel._timerRecords[record.data["timerId"]] = this; break; case recordTypes.TimerFire: var timerInstalledRecord = presentationModel._timerRecords[record.data["timerId"]]; if (timerInstalledRecord) { this.callSiteStackTrace = timerInstalledRecord.stackTrace; this.timeout = timerInstalledRecord.timeout; this.singleShot = timerInstalledRecord.singleShot; } break; case recordTypes.RequestAnimationFrame: presentationModel._requestAnimationFrameRecords[record.data["id"]] = this; break; case recordTypes.FireAnimationFrame: var requestAnimationRecord = presentationModel._requestAnimationFrameRecords[record.data["id"]]; if (requestAnimationRecord) this.callSiteStackTrace = requestAnimationRecord.stackTrace; break; case recordTypes.Time: presentationModel._timeRecords[record.data["message"]] = this; break; case recordTypes.TimeEnd: var message = record.data["message"]; var timeRecord = presentationModel._timeRecords[message]; delete presentationModel._timeRecords[message]; if (timeRecord) { this.timeRecord = timeRecord; timeRecord.timeEndRecord = this; var intervalDuration = this.startTime - timeRecord.startTime; this.intervalDuration = intervalDuration; timeRecord.intervalDuration = intervalDuration; } break; case recordTypes.ScheduleStyleRecalculation: presentationModel._lastScheduleStyleRecalculation[this.frameId] = this; break; case recordTypes.RecalculateStyles: var scheduleStyleRecalculationRecord = presentationModel._lastScheduleStyleRecalculation[this.frameId]; if (!scheduleStyleRecalculationRecord) break; this.callSiteStackTrace = scheduleStyleRecalculationRecord.stackTrace; break; case recordTypes.InvalidateLayout: presentationModel._lastInvalidateLayout[this.frameId] = this; break; case recordTypes.Layout: var invalidateLayoutRecord = presentationModel._lastInvalidateLayout[this.frameId]; if (invalidateLayoutRecord) this.callSiteStackTrace = invalidateLayoutRecord.stackTrace || invalidateLayoutRecord.callSiteStackTrace; if (this.stackTrace) this.setHasWarning(); presentationModel._lastInvalidateLayout[this.frameId] = null; break; } } WebInspector.TimelinePresentationModel.Record.prototype = { get lastChildEndTime() { return this._lastChildEndTime; }, set lastChildEndTime(time) { this._lastChildEndTime = time; }, get selfTime() { return this._selfTime; }, set selfTime(time) { this._selfTime = time; }, get cpuTime() { return this._cpuTime; }, isRoot: function() { return this.type === WebInspector.TimelineModel.RecordType.Root; }, origin: function() { return this._origin || this.parent; }, get children() { return this._children; }, get visibleChildrenCount() { return this._visibleChildrenCount || 0; }, get invisibleChildrenCount() { return this._invisibleChildrenCount || 0; }, get category() { return WebInspector.TimelinePresentationModel.recordStyle(this._record).category }, get title() { return this.type === WebInspector.TimelineModel.RecordType.TimeStamp ? this._record.data["message"] : WebInspector.TimelinePresentationModel.recordStyle(this._record).title; }, get startTime() { return WebInspector.TimelineModel.startTimeInSeconds(this._record); }, get endTime() { return WebInspector.TimelineModel.endTimeInSeconds(this._record); }, get data() { return this._record.data; }, get type() { return this._record.type; }, get frameId() { return this._record.frameId; }, get usedHeapSizeDelta() { return this._record.usedHeapSizeDelta || 0; }, get usedHeapSize() { return this._record.usedHeapSize; }, get stackTrace() { if (this._record.stackTrace && this._record.stackTrace.length) return this._record.stackTrace; return null; }, containsTime: function(time) { return this.startTime <= time && time <= this.endTime; }, generatePopupContent: function(callback) { if (WebInspector.TimelinePresentationModel.needsPreviewElement(this.type)) WebInspector.DOMPresentationUtils.buildImagePreviewContents(this.url, false, this._generatePopupContentWithImagePreview.bind(this, callback)); else this._generatePopupContentWithImagePreview(callback); }, _generatePopupContentWithImagePreview: function(callback, previewElement) { var contentHelper = new WebInspector.TimelinePresentationModel.PopupContentHelper(this.title); var text = WebInspector.UIString("%s (at %s)", Number.secondsToString(this._lastChildEndTime - this.startTime, true), Number.secondsToString(this._startTimeOffset)); contentHelper._appendTextRow(WebInspector.UIString("Duration"), text); if (this._children.length) { contentHelper._appendTextRow(WebInspector.UIString("Self Time"), Number.secondsToString(this._selfTime, true)); contentHelper._appendTextRow(WebInspector.UIString("CPU Time"), Number.secondsToString(this._cpuTime, true)); contentHelper._appendElementRow(WebInspector.UIString("Aggregated Time"), WebInspector.TimelinePresentationModel._generateAggregatedInfo(this._aggregatedStats)); } const recordTypes = WebInspector.TimelineModel.RecordType; var callSiteStackTraceLabel; var callStackLabel; switch (this.type) { case recordTypes.GCEvent: contentHelper._appendTextRow(WebInspector.UIString("Collected"), Number.bytesToString(this.data["usedHeapSizeDelta"])); break; case recordTypes.TimerInstall: case recordTypes.TimerFire: case recordTypes.TimerRemove: contentHelper._appendTextRow(WebInspector.UIString("Timer ID"), this.data["timerId"]); if (typeof this.timeout === "number") { contentHelper._appendTextRow(WebInspector.UIString("Timeout"), Number.secondsToString(this.timeout / 1000)); contentHelper._appendTextRow(WebInspector.UIString("Repeats"), !this.singleShot); } break; case recordTypes.FireAnimationFrame: contentHelper._appendTextRow(WebInspector.UIString("Callback ID"), this.data["id"]); break; case recordTypes.FunctionCall: contentHelper._appendElementRow(WebInspector.UIString("Location"), this._linkifyScriptLocation()); break; case recordTypes.ScheduleResourceRequest: case recordTypes.ResourceSendRequest: case recordTypes.ResourceReceiveResponse: case recordTypes.ResourceReceivedData: case recordTypes.ResourceFinish: contentHelper._appendElementRow(WebInspector.UIString("Resource"), WebInspector.linkifyResourceAsNode(this.url)); if (previewElement) contentHelper._appendElementRow(WebInspector.UIString("Preview"), previewElement); if (this.data["requestMethod"]) contentHelper._appendTextRow(WebInspector.UIString("Request Method"), this.data["requestMethod"]); if (typeof this.data["statusCode"] === "number") contentHelper._appendTextRow(WebInspector.UIString("Status Code"), this.data["statusCode"]); if (this.data["mimeType"]) contentHelper._appendTextRow(WebInspector.UIString("MIME Type"), this.data["mimeType"]); if (this.data["encodedDataLength"]) contentHelper._appendTextRow(WebInspector.UIString("Encoded Data Length"), WebInspector.UIString("%d Bytes", this.data["encodedDataLength"])); break; case recordTypes.EvaluateScript: if (this.data && this.url) contentHelper._appendElementRow(WebInspector.UIString("Script"), this._linkifyLocation(this.url, this.data["lineNumber"])); break; case recordTypes.Paint: contentHelper._appendTextRow(WebInspector.UIString("Location"), WebInspector.UIString("(%d, %d)", this.data["x"], this.data["y"])); contentHelper._appendTextRow(WebInspector.UIString("Dimensions"), WebInspector.UIString("%d × %d", this.data["width"], this.data["height"])); break; case recordTypes.RecalculateStyles: callSiteStackTraceLabel = WebInspector.UIString("Styles invalidated"); callStackLabel = WebInspector.UIString("Styles recalculation forced"); break; case recordTypes.Layout: callSiteStackTraceLabel = WebInspector.UIString("Layout invalidated"); if (this.stackTrace) { callStackLabel = WebInspector.UIString("Layout forced"); contentHelper._appendTextRow(WebInspector.UIString("Note"), WebInspector.UIString("Forced synchronous layout is a possible performance bottleneck.")); } break; case recordTypes.Time: case recordTypes.TimeEnd: contentHelper._appendTextRow(WebInspector.UIString("Message"), this.data["message"]); if (typeof this.intervalDuration === "number") contentHelper._appendTextRow(WebInspector.UIString("Interval Duration"), Number.secondsToString(this.intervalDuration, true)); break; default: if (this.detailsNode()) contentHelper._appendElementRow(WebInspector.UIString("Details"), this.detailsNode().childNodes[1].cloneNode()); break; } if (this.scriptName && this.type !== recordTypes.FunctionCall) contentHelper._appendElementRow(WebInspector.UIString("Function Call"), this._linkifyScriptLocation()); if (this.usedHeapSize) { if (this.usedHeapSizeDelta) { var sign = this.usedHeapSizeDelta > 0 ? "+" : "-"; contentHelper._appendTextRow(WebInspector.UIString("Used Heap Size"), WebInspector.UIString("%s (%s%s)", Number.bytesToString(this.usedHeapSize), sign, Number.bytesToString(this.usedHeapSizeDelta))); } else if (this.category === WebInspector.TimelinePresentationModel.categories().scripting) contentHelper._appendTextRow(WebInspector.UIString("Used Heap Size"), Number.bytesToString(this.usedHeapSize)); } if (this.callSiteStackTrace) contentHelper._appendStackTrace(callSiteStackTraceLabel || WebInspector.UIString("Call Site stack"), this.callSiteStackTrace, this._linkifyCallFrame.bind(this)); if (this.stackTrace) contentHelper._appendStackTrace(callStackLabel || WebInspector.UIString("Call Stack"), this.stackTrace, this._linkifyCallFrame.bind(this)); callback(contentHelper._contentTable); }, _refreshDetails: function() { delete this._detailsNode; }, detailsNode: function() { if (typeof this._detailsNode === "undefined") { this._detailsNode = this._getRecordDetails(); if (this._detailsNode) { this._detailsNode.insertBefore(document.createTextNode("("), this._detailsNode.firstChild); this._detailsNode.appendChild(document.createTextNode(")")); } } return this._detailsNode; }, _createSpanWithText: function(textContent) { var node = document.createElement("span"); node.textContent = textContent; return node; }, _getRecordDetails: function() { var details; switch (this.type) { case WebInspector.TimelineModel.RecordType.GCEvent: details = WebInspector.UIString("%s collected", Number.bytesToString(this.data["usedHeapSizeDelta"])); break; case WebInspector.TimelineModel.RecordType.TimerFire: details = this._linkifyScriptLocation(this.data["timerId"]); break; case WebInspector.TimelineModel.RecordType.FunctionCall: details = this._linkifyScriptLocation(); break; case WebInspector.TimelineModel.RecordType.FireAnimationFrame: details = this._linkifyScriptLocation(this.data["id"]); break; case WebInspector.TimelineModel.RecordType.EventDispatch: details = this.data ? this.data["type"] : null; break; case WebInspector.TimelineModel.RecordType.Paint: details = this.data["width"] + "\u2009\u00d7\u2009" + this.data["height"]; break; case WebInspector.TimelineModel.RecordType.DecodeImage: details = this.data["imageType"]; break; case WebInspector.TimelineModel.RecordType.ResizeImage: details = this.data["cached"] ? WebInspector.UIString("cached") : WebInspector.UIString("non-cached"); break; case WebInspector.TimelineModel.RecordType.TimerInstall: case WebInspector.TimelineModel.RecordType.TimerRemove: details = this._linkifyTopCallFrame(this.data["timerId"]); break; case WebInspector.TimelineModel.RecordType.RequestAnimationFrame: case WebInspector.TimelineModel.RecordType.CancelAnimationFrame: details = this._linkifyTopCallFrame(this.data["id"]); break; case WebInspector.TimelineModel.RecordType.ParseHTML: case WebInspector.TimelineModel.RecordType.RecalculateStyles: details = this._linkifyTopCallFrame(); break; case WebInspector.TimelineModel.RecordType.EvaluateScript: details = this.url ? this._linkifyLocation(this.url, this.data["lineNumber"], 0) : null; break; case WebInspector.TimelineModel.RecordType.XHRReadyStateChange: case WebInspector.TimelineModel.RecordType.XHRLoad: case WebInspector.TimelineModel.RecordType.ScheduleResourceRequest: case WebInspector.TimelineModel.RecordType.ResourceSendRequest: case WebInspector.TimelineModel.RecordType.ResourceReceivedData: case WebInspector.TimelineModel.RecordType.ResourceReceiveResponse: case WebInspector.TimelineModel.RecordType.ResourceFinish: details = WebInspector.displayNameForURL(this.url); break; case WebInspector.TimelineModel.RecordType.Time: case WebInspector.TimelineModel.RecordType.TimeEnd: case WebInspector.TimelineModel.RecordType.TimeStamp: details = this.data["message"]; break; default: details = this._linkifyScriptLocation() || this._linkifyTopCallFrame() || null; break; } if (typeof details === "string") return this._createSpanWithText(details); return details ? details : null; }, _linkifyLocation: function(url, lineNumber, columnNumber) { columnNumber = columnNumber ? columnNumber - 1 : 0; return this._linkifier.linkifyLocation(url, lineNumber - 1, columnNumber, "timeline-details"); }, _linkifyCallFrame: function(callFrame) { return this._linkifyLocation(callFrame.url, callFrame.lineNumber, callFrame.columnNumber); }, _linkifyTopCallFrame: function(defaultValue) { if (this.stackTrace) return this._linkifyCallFrame(this.stackTrace[0]); if (this.callSiteStackTrace) return this._linkifyCallFrame(this.callSiteStackTrace[0]); return defaultValue; }, _linkifyScriptLocation: function(defaultValue) { return this.scriptName ? this._linkifyLocation(this.scriptName, this.scriptLine, 0) : defaultValue; }, calculateAggregatedStats: function(categories) { this._aggregatedStats = {}; for (var category in categories) this._aggregatedStats[category] = 0; this._cpuTime = this._selfTime; for (var index = this._children.length; index; --index) { var child = this._children[index - 1]; for (var category in categories) this._aggregatedStats[category] += child._aggregatedStats[category]; } for (var category in this._aggregatedStats) this._cpuTime += this._aggregatedStats[category]; this._aggregatedStats[this.category.name] += this._selfTime; }, get aggregatedStats() { return this._aggregatedStats; }, setHasWarning: function() { this.hasWarning = true; for (var parent = this.parent; parent && !parent.childHasWarning; parent = parent.parent) parent.childHasWarning = true; } } WebInspector.TimelinePresentationModel._generateAggregatedInfo = function(aggregatedStats) { var cell = document.createElement("span"); cell.className = "timeline-aggregated-info"; for (var index in aggregatedStats) { var label = document.createElement("div"); label.className = "timeline-aggregated-category timeline-" + index; cell.appendChild(label); var text = document.createElement("span"); text.textContent = Number.secondsToString(aggregatedStats[index], true); cell.appendChild(text); } return cell; } WebInspector.TimelinePresentationModel.PopupContentHelper = function(title) { this._contentTable = document.createElement("table"); var titleCell = this._createCell(WebInspector.UIString("%s - Details", title), "timeline-details-title"); titleCell.colSpan = 2; var titleRow = document.createElement("tr"); titleRow.appendChild(titleCell); this._contentTable.appendChild(titleRow); } WebInspector.TimelinePresentationModel.PopupContentHelper.prototype = { _createCell: function(content, styleName) { var text = document.createElement("label"); text.appendChild(document.createTextNode(content)); var cell = document.createElement("td"); cell.className = "timeline-details"; if (styleName) cell.className += " " + styleName; cell.textContent = content; return cell; }, _appendTextRow: function(title, content) { var row = document.createElement("tr"); row.appendChild(this._createCell(title, "timeline-details-row-title")); row.appendChild(this._createCell(content, "timeline-details-row-data")); this._contentTable.appendChild(row); }, _appendElementRow: function(title, content, titleStyle) { var row = document.createElement("tr"); var titleCell = this._createCell(title, "timeline-details-row-title"); if (titleStyle) titleCell.addStyleClass(titleStyle); row.appendChild(titleCell); var cell = document.createElement("td"); cell.className = "timeline-details"; cell.appendChild(content); row.appendChild(cell); this._contentTable.appendChild(row); }, _appendStackTrace: function(title, stackTrace, callFrameLinkifier) { this._appendTextRow("", ""); var framesTable = document.createElement("table"); for (var i = 0; i < stackTrace.length; ++i) { var stackFrame = stackTrace[i]; var row = document.createElement("tr"); row.className = "timeline-details"; row.appendChild(this._createCell(stackFrame.functionName ? stackFrame.functionName : WebInspector.UIString("(anonymous function)"), "timeline-function-name")); row.appendChild(this._createCell(" @ ")); var linkCell = document.createElement("td"); var urlElement = callFrameLinkifier(stackFrame); linkCell.appendChild(urlElement); row.appendChild(linkCell); framesTable.appendChild(row); } this._appendElementRow(title, framesTable, "timeline-stacktrace-title"); } } WebInspector.TimelinePresentationModel.generatePopupContentForFrame = function(frame) { var contentHelper = new WebInspector.TimelinePresentationModel.PopupContentHelper(WebInspector.UIString("Frame")); var durationInSeconds = frame.endTime - frame.startTime; var durationText = WebInspector.UIString("%s (at %s)", Number.secondsToString(frame.endTime - frame.startTime, true), Number.secondsToString(frame.startTimeOffset, true)); contentHelper._appendTextRow(WebInspector.UIString("Duration"), durationText); contentHelper._appendTextRow(WebInspector.UIString("FPS"), Math.floor(1 / durationInSeconds)); contentHelper._appendTextRow(WebInspector.UIString("CPU time"), Number.secondsToString(frame.cpuTime, true)); contentHelper._appendElementRow(WebInspector.UIString("Aggregated Time"), WebInspector.TimelinePresentationModel._generateAggregatedInfo(frame.timeByCategory)); return contentHelper._contentTable; } WebInspector.TimelinePresentationModel.generatePopupContentForFrameStatistics = function(statistics) { function formatTimeAndFPS(time) { return WebInspector.UIString("%s (%.0f FPS)", Number.secondsToString(time, true), 1 / time); } var contentHelper = new WebInspector.TimelinePresentationModel.PopupContentHelper(WebInspector.UIString("Selected Range")); contentHelper._appendTextRow(WebInspector.UIString("Selected range"), WebInspector.UIString("%s\u2013%s (%d frames)", Number.secondsToString(statistics.startOffset, true), Number.secondsToString(statistics.endOffset, true), statistics.frameCount)); contentHelper._appendTextRow(WebInspector.UIString("Minimum Time"), formatTimeAndFPS(statistics.minDuration)); contentHelper._appendTextRow(WebInspector.UIString("Average Time"), formatTimeAndFPS(statistics.average)); contentHelper._appendTextRow(WebInspector.UIString("Maximum Time"), formatTimeAndFPS(statistics.maxDuration)); contentHelper._appendTextRow(WebInspector.UIString("Standard Deviation"), Number.secondsToString(statistics.stddev, true)); contentHelper._appendElementRow(WebInspector.UIString("Time by category"), WebInspector.TimelinePresentationModel._generateAggregatedInfo(statistics.timeByCategory)); return contentHelper._contentTable; } WebInspector.TimelinePresentationModel.createFillStyle = function(context, width, height, color0, color1, color2) { var gradient = context.createLinearGradient(0, 0, width, height); gradient.addColorStop(0, color0); gradient.addColorStop(0.25, color1); gradient.addColorStop(0.75, color1); gradient.addColorStop(1, color2); return gradient; } WebInspector.TimelinePresentationModel.createFillStyleForCategory = function(context, width, height, category) { return WebInspector.TimelinePresentationModel.createFillStyle(context, width, height, category.fillColorStop0, category.fillColorStop1, category.borderColor); } WebInspector.TimelinePresentationModel.createStyleRuleForCategory = function(category) { var selector = ".timeline-category-" + category.name + " .timeline-graph-bar, " + ".timeline-category-statusbar-item.timeline-category-" + category.name + " .timeline-category-checkbox, " + ".popover .timeline-" + category.name + ", " + ".timeline-category-" + category.name + " .timeline-tree-icon" return selector + " { background-image: -webkit-linear-gradient(" + category.fillColorStop0 + ", " + category.fillColorStop1 + " 25%, " + category.fillColorStop1 + " 75%, " + category.borderColor + ");" + " border-color: " + category.borderColor + "}"; } WebInspector.TimelinePresentationModel.Filter = function() { } WebInspector.TimelinePresentationModel.Filter.prototype = { accept: function(record) { return false; } } WebInspector.TimelineCategory = function(name, title, overviewStripGroupIndex, borderColor, fillColorStop0, fillColorStop1) { this.name = name; this.title = title; this.overviewStripGroupIndex = overviewStripGroupIndex; this.borderColor = borderColor; this.fillColorStop0 = fillColorStop0; this.fillColorStop1 = fillColorStop1; this.hidden = false; } WebInspector.TimelineCategory.Events = { VisibilityChanged: "VisibilityChanged" }; WebInspector.TimelineCategory.prototype = { get hidden() { return this._hidden; }, set hidden(hidden) { this._hidden = hidden; this.dispatchEventToListeners(WebInspector.TimelineCategory.Events.VisibilityChanged, this); }, __proto__: WebInspector.Object.prototype } ; WebInspector.TimelineFrameController = function(model, overviewPane, presentationModel) { this._lastFrame = null; this._model = model; this._overviewPane = overviewPane; this._presentationModel = presentationModel; this._model.addEventListener(WebInspector.TimelineModel.Events.RecordAdded, this._onRecordAdded, this); this._model.addEventListener(WebInspector.TimelineModel.Events.RecordsCleared, this._onRecordsCleared, this); var records = model.records; for (var i = 0; i < records.length; ++i) this._addRecord(records[i]); } WebInspector.TimelineFrameController.prototype = { _onRecordAdded: function(event) { this._addRecord(event.data); }, _onRecordsCleared: function() { this._lastFrame = null; }, _addRecord: function(record) { var records; if (record.type === WebInspector.TimelineModel.RecordType.Program) records = record["children"] || []; else records = [record]; records.forEach(this._innerAddRecord, this); }, _innerAddRecord: function(record) { if (record.type === WebInspector.TimelineModel.RecordType.BeginFrame && this._lastFrame) this._flushFrame(record); else { if (!this._lastFrame) this._lastFrame = this._createFrame(record); WebInspector.TimelineModel.aggregateTimeForRecord(this._lastFrame.timeByCategory, record); this._lastFrame.cpuTime += WebInspector.TimelineModel.durationInSeconds(record); } }, _flushFrame: function(record) { this._lastFrame.endTime = WebInspector.TimelineModel.startTimeInSeconds(record); this._lastFrame.duration = this._lastFrame.endTime - this._lastFrame.startTime; this._overviewPane.addFrame(this._lastFrame); this._presentationModel.addFrame(this._lastFrame); this._lastFrame = this._createFrame(record); }, _createFrame: function(record) { var frame = new WebInspector.TimelineFrame(); frame.startTime = WebInspector.TimelineModel.startTimeInSeconds(record); frame.startTimeOffset = this._model.recordOffsetInSeconds(record); return frame; }, dispose: function() { this._model.removeEventListener(WebInspector.TimelineModel.Events.RecordAdded, this._onRecordAdded, this); this._model.removeEventListener(WebInspector.TimelineModel.Events.RecordsCleared, this._onRecordsCleared, this); } } WebInspector.FrameStatistics = function(frames) { this.frameCount = frames.length; this.minDuration = Infinity; this.maxDuration = 0; this.timeByCategory = {}; this.startOffset = frames[0].startTimeOffset; var lastFrame = frames[this.frameCount - 1]; this.endOffset = lastFrame.startTimeOffset + lastFrame.duration; var totalDuration = 0; var sumOfSquares = 0; for (var i = 0; i < this.frameCount; ++i) { var duration = frames[i].duration; totalDuration += duration; sumOfSquares += duration * duration; this.minDuration = Math.min(this.minDuration, duration); this.maxDuration = Math.max(this.maxDuration, duration); WebInspector.TimelineModel.aggregateTimeByCategory(this.timeByCategory, frames[i].timeByCategory); } this.average = totalDuration / this.frameCount; var variance = sumOfSquares / this.frameCount - this.average * this.average; this.stddev = Math.sqrt(variance); } WebInspector.TimelineFrame = function() { this.timeByCategory = {}; this.cpuTime = 0; } ; WebInspector.TimelinePanel = function() { WebInspector.Panel.call(this, "timeline"); this.registerRequiredCSS("timelinePanel.css"); this._model = new WebInspector.TimelineModel(); this._presentationModel = new WebInspector.TimelinePresentationModel(); this._overviewModeSetting = WebInspector.settings.createSetting("timelineOverviewMode", WebInspector.TimelineOverviewPane.Mode.Events); this._glueRecordsSetting = WebInspector.settings.createSetting("timelineGlueRecords", true); this._overviewPane = new WebInspector.TimelineOverviewPane(this._model); this._overviewPane.addEventListener(WebInspector.TimelineOverviewPane.Events.WindowChanged, this._invalidateAndScheduleRefresh.bind(this, false)); this._overviewPane.addEventListener(WebInspector.TimelineOverviewPane.Events.ModeChanged, this._overviewModeChanged, this); this._overviewPane.show(this.element); this.element.addEventListener("contextmenu", this._contextMenu.bind(this), false); this.element.tabIndex = 0; this._sidebarBackgroundElement = document.createElement("div"); this._sidebarBackgroundElement.className = "sidebar split-view-sidebar-left timeline-sidebar-background"; this.element.appendChild(this._sidebarBackgroundElement); this.createSidebarViewWithTree(); this.element.appendChild(this.splitView.resizerElement()); this._containerElement = this.splitView.element; this._containerElement.id = "timeline-container"; this._containerElement.addEventListener("scroll", this._onScroll.bind(this), false); this._timelineMemorySplitter = this.element.createChild("div"); this._timelineMemorySplitter.id = "timeline-memory-splitter"; WebInspector.installDragHandle(this._timelineMemorySplitter, this._startSplitterDragging.bind(this), this._splitterDragging.bind(this), this._endSplitterDragging.bind(this), "ns-resize"); this._timelineMemorySplitter.addStyleClass("hidden"); this._memoryStatistics = new WebInspector.MemoryStatistics(this, this._model, this.splitView.sidebarWidth()); WebInspector.settings.memoryCounterGraphsHeight = WebInspector.settings.createSetting("memoryCounterGraphsHeight", 150); var itemsTreeElement = new WebInspector.SidebarSectionTreeElement(WebInspector.UIString("RECORDS"), {}, true); this.sidebarTree.appendChild(itemsTreeElement); this._sidebarListElement = document.createElement("div"); this.sidebarElement.appendChild(this._sidebarListElement); this._containerContentElement = this.splitView.mainElement; this._containerContentElement.id = "resources-container-content"; this._timelineGrid = new WebInspector.TimelineGrid(); this._itemsGraphsElement = this._timelineGrid.itemsGraphsElement; this._itemsGraphsElement.id = "timeline-graphs"; this._containerContentElement.appendChild(this._timelineGrid.element); this._timelineGrid.gridHeaderElement.id = "timeline-grid-header"; this._memoryStatistics.setMainTimelineGrid(this._timelineGrid); this.element.appendChild(this._timelineGrid.gridHeaderElement); this._topGapElement = document.createElement("div"); this._topGapElement.className = "timeline-gap"; this._itemsGraphsElement.appendChild(this._topGapElement); this._graphRowsElement = document.createElement("div"); this._itemsGraphsElement.appendChild(this._graphRowsElement); this._bottomGapElement = document.createElement("div"); this._bottomGapElement.className = "timeline-gap"; this._itemsGraphsElement.appendChild(this._bottomGapElement); this._expandElements = document.createElement("div"); this._expandElements.id = "orphan-expand-elements"; this._itemsGraphsElement.appendChild(this._expandElements); this._calculator = new WebInspector.TimelineCalculator(this._model); this._createStatusBarItems(); this._frameMode = false; this._boundariesAreValid = true; this._scrollTop = 0; this._popoverHelper = new WebInspector.PopoverHelper(this.element, this._getPopoverAnchor.bind(this), this._showPopover.bind(this)); this.element.addEventListener("mousemove", this._mouseMove.bind(this), false); this.element.addEventListener("mouseout", this._mouseOut.bind(this), false); this._durationFilter = new WebInspector.TimelineIsLongFilter(); this._timeStampRecords = []; this._expandOffset = 15; this._headerLineCount = 1; this._adjustHeaderHeight(); this._mainThreadTasks = ([]); this._cpuBarsElement = this._timelineGrid.gridHeaderElement.createChild("div", "timeline-cpu-bars"); this._mainThreadMonitoringEnabled = Capabilities.timelineCanMonitorMainThread && WebInspector.settings.showCpuOnTimelineRuler.get(); WebInspector.settings.showCpuOnTimelineRuler.addChangeListener(this._showCpuOnTimelineRulerChanged, this); this._createFileSelector(); this._model.addEventListener(WebInspector.TimelineModel.Events.RecordAdded, this._onTimelineEventRecorded, this); this._model.addEventListener(WebInspector.TimelineModel.Events.RecordsCleared, this._onRecordsCleared, this); this._registerShortcuts(); this._allRecordsCount = 0; this._presentationModel.addFilter(new WebInspector.TimelineWindowFilter(this._overviewPane)); this._presentationModel.addFilter(new WebInspector.TimelineCategoryFilter()); this._presentationModel.addFilter(this._durationFilter); } WebInspector.TimelinePanel.rowHeight = 18; WebInspector.TimelinePanel.durationFilterPresetsMs = [0, 1, 15]; WebInspector.TimelinePanel.prototype = { _showCpuOnTimelineRulerChanged: function() { var mainThreadMonitoringEnabled = WebInspector.settings.showCpuOnTimelineRuler.get(); if (this._mainThreadMonitoringEnabled !== mainThreadMonitoringEnabled) { this._mainThreadMonitoringEnabled = mainThreadMonitoringEnabled; this._refreshMainThreadBars(); } }, _startSplitterDragging: function(event) { this._dragOffset = this._timelineMemorySplitter.offsetTop + 2 - event.pageY; return true; }, _splitterDragging: function(event) { var top = event.pageY + this._dragOffset this._setSplitterPosition(top); event.preventDefault(); }, _endSplitterDragging: function(event) { delete this._dragOffset; this._memoryStatistics.show(); WebInspector.settings.memoryCounterGraphsHeight.set(this.splitView.element.offsetHeight); }, _setSplitterPosition: function(top) { const overviewHeight = 90; const sectionMinHeight = 100; top = Number.constrain(top, overviewHeight + sectionMinHeight, this.element.offsetHeight - sectionMinHeight); this.splitView.element.style.height = (top - overviewHeight) + "px"; this._timelineMemorySplitter.style.top = (top - 2) + "px"; this._memoryStatistics.setTopPosition(top); this._containerElementHeight = this._containerElement.clientHeight; this.onResize(); }, get calculator() { return this._calculator; }, get statusBarItems() { return this._statusBarItems.select("element").concat([ this._miscStatusBarItems, this.recordsCounter, this.frameStatistics ]); }, defaultFocusedElement: function() { return this.element; }, _createStatusBarItems: function() { this._statusBarItems = ([]); this.toggleTimelineButton = new WebInspector.StatusBarButton(WebInspector.UIString("Record"), "record-profile-status-bar-item"); this.toggleTimelineButton.addEventListener("click", this._toggleTimelineButtonClicked, this); this._statusBarItems.push(this.toggleTimelineButton); this.clearButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear"), "clear-status-bar-item"); this.clearButton.addEventListener("click", this._clearPanel, this); this._statusBarItems.push(this.clearButton); this.garbageCollectButton = new WebInspector.StatusBarButton(WebInspector.UIString("Collect Garbage"), "garbage-collect-status-bar-item"); this.garbageCollectButton.addEventListener("click", this._garbageCollectButtonClicked, this); this._statusBarItems.push(this.garbageCollectButton); this._glueParentButton = new WebInspector.StatusBarButton(WebInspector.UIString("Glue asynchronous events to causes"), "glue-async-status-bar-item"); this._glueParentButton.toggled = this._glueRecordsSetting.get(); this._presentationModel.setGlueRecords(this._glueParentButton.toggled); this._glueParentButton.addEventListener("click", this._glueParentButtonClicked, this); this._statusBarItems.push(this._glueParentButton); this._durationFilterSelector = new WebInspector.StatusBarComboBox(this._durationFilterChanged.bind(this)); for (var presetIndex = 0; presetIndex < WebInspector.TimelinePanel.durationFilterPresetsMs.length; ++presetIndex) { var durationMs = WebInspector.TimelinePanel.durationFilterPresetsMs[presetIndex]; var option = document.createElement("option"); if (!durationMs) { option.text = WebInspector.UIString("All"); option.title = WebInspector.UIString("Show all records"); } else { option.text = WebInspector.UIString("\u2265 %dms", durationMs); option.title = WebInspector.UIString("Hide records shorter than %dms", durationMs); } option._durationMs = durationMs; this._durationFilterSelector.addOption(option); this._durationFilterSelector.element.title = this._durationFilterSelector.selectedOption().title; } this._statusBarItems.push(this._durationFilterSelector); this._miscStatusBarItems = document.createElement("div"); this._miscStatusBarItems.className = "status-bar-items"; this._statusBarFilters = this._miscStatusBarItems.createChild("div"); var categories = WebInspector.TimelinePresentationModel.categories(); for (var categoryName in categories) { var category = categories[categoryName]; if (category.overviewStripGroupIndex < 0) continue; this._statusBarFilters.appendChild(this._createTimelineCategoryStatusBarCheckbox(category, this._onCategoryCheckboxClicked.bind(this, category))); } this.recordsCounter = document.createElement("span"); this.recordsCounter.className = "timeline-records-stats"; this.frameStatistics = document.createElement("span"); this.frameStatistics.className = "timeline-records-stats hidden"; function getAnchor() { return this.frameStatistics; } this._frameStatisticsPopoverHelper = new WebInspector.PopoverHelper(this.frameStatistics, getAnchor.bind(this), this._showFrameStatistics.bind(this)); }, _createTimelineCategoryStatusBarCheckbox: function(category, onCheckboxClicked) { var labelContainer = document.createElement("div"); labelContainer.addStyleClass("timeline-category-statusbar-item"); labelContainer.addStyleClass("timeline-category-" + category.name); labelContainer.addStyleClass("status-bar-item"); var label = document.createElement("label"); var checkElement = document.createElement("input"); checkElement.type = "checkbox"; checkElement.className = "timeline-category-checkbox"; checkElement.checked = true; checkElement.addEventListener("click", onCheckboxClicked, false); label.appendChild(checkElement); var typeElement = document.createElement("span"); typeElement.className = "type"; typeElement.textContent = category.title; label.appendChild(typeElement); labelContainer.appendChild(label); return labelContainer; }, _onCategoryCheckboxClicked: function(category, event) { category.hidden = !event.target.checked; this._invalidateAndScheduleRefresh(true); }, _setOperationInProgress: function(indicator) { this._operationInProgress = !!indicator; for (var i = 0; i < this._statusBarItems.length; ++i) this._statusBarItems[i].setEnabled(!this._operationInProgress); this._glueParentButton.setEnabled(!this._operationInProgress && !this._frameController); this._miscStatusBarItems.removeChildren(); this._miscStatusBarItems.appendChild(indicator ? indicator.element : this._statusBarFilters); }, _registerShortcuts: function() { this.registerShortcuts(WebInspector.TimelinePanelDescriptor.ShortcutKeys.StartStopRecording, this._toggleTimelineButtonClicked.bind(this)); if (InspectorFrontendHost.canSave()) this.registerShortcuts(WebInspector.TimelinePanelDescriptor.ShortcutKeys.SaveToFile, this._saveToFile.bind(this)); this.registerShortcuts(WebInspector.TimelinePanelDescriptor.ShortcutKeys.LoadFromFile, this._fileSelectorElement.click.bind(this._fileSelectorElement)); }, _createFileSelector: function() { if (this._fileSelectorElement) this.element.removeChild(this._fileSelectorElement); var fileSelectorElement = document.createElement("input"); fileSelectorElement.type = "file"; fileSelectorElement.style.zIndex = -1; fileSelectorElement.style.position = "absolute"; fileSelectorElement.onchange = this._loadFromFile.bind(this); this.element.appendChild(fileSelectorElement); this._fileSelectorElement = fileSelectorElement; }, _contextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); if (InspectorFrontendHost.canSave()) contextMenu.appendItem(WebInspector.UIString("Save Timeline data\u2026"), this._saveToFile.bind(this), this._operationInProgress); contextMenu.appendItem(WebInspector.UIString("Load Timeline data\u2026"), this._fileSelectorElement.click.bind(this._fileSelectorElement), this._operationInProgress); contextMenu.show(); }, _saveToFile: function() { if (this._operationInProgress) return; this._model.saveToFile(); }, _loadFromFile: function() { var progressIndicator = this._prepareToLoadTimeline(); if (!progressIndicator) return; this._model.loadFromFile(this._fileSelectorElement.files[0], progressIndicator); this._createFileSelector(); }, loadFromURL: function(url) { var progressIndicator = this._prepareToLoadTimeline(); if (!progressIndicator) return; this._model.loadFromURL(url, progressIndicator); }, _prepareToLoadTimeline: function() { if (this._operationInProgress) return null; if (this.toggleTimelineButton.toggled) { this.toggleTimelineButton.toggled = false; this._model.stopRecord(); } var progressIndicator = new WebInspector.ProgressIndicator(); progressIndicator.addEventListener(WebInspector.ProgressIndicator.Events.Done, this._setOperationInProgress.bind(this, null)); this._setOperationInProgress(progressIndicator); return progressIndicator; }, _rootRecord: function() { return this._presentationModel.rootRecord(); }, _updateRecordsCounter: function(recordsInWindowCount) { this.recordsCounter.textContent = WebInspector.UIString("%d of %d records shown", recordsInWindowCount, this._allRecordsCount); }, _updateFrameStatistics: function(frames) { if (frames.length) { this._lastFrameStatistics = new WebInspector.FrameStatistics(frames); var details = WebInspector.UIString("avg: %s, \u03c3: %s", Number.secondsToString(this._lastFrameStatistics.average, true), Number.secondsToString(this._lastFrameStatistics.stddev, true)); } else this._lastFrameStatistics = null; this.frameStatistics.textContent = WebInspector.UIString("%d of %d frames shown", frames.length, this._presentationModel.frames().length); if (details) { this.frameStatistics.appendChild(document.createTextNode(" (")); this.frameStatistics.createChild("span", "timeline-frames-stats").textContent = details; this.frameStatistics.appendChild(document.createTextNode(")")); } }, _showFrameStatistics: function(anchor, popover) { popover.show(WebInspector.TimelinePresentationModel.generatePopupContentForFrameStatistics(this._lastFrameStatistics), anchor); }, _updateEventDividers: function() { this._timelineGrid.removeEventDividers(); var clientWidth = this._graphRowsElementWidth; var dividers = []; for (var i = 0; i < this._timeStampRecords.length; ++i) { var record = this._timeStampRecords[i]; var positions = this._calculator.computeBarGraphWindowPosition(record); var dividerPosition = Math.round(positions.left); if (dividerPosition < 0 || dividerPosition >= clientWidth || dividers[dividerPosition]) continue; var divider = WebInspector.TimelinePresentationModel.createEventDivider(record.type, record.title); divider.style.left = dividerPosition + "px"; dividers[dividerPosition] = divider; } this._timelineGrid.addEventDividers(dividers); }, _updateFrameBars: function(frames) { var clientWidth = this._graphRowsElementWidth; if (this._frameContainer) this._frameContainer.removeChildren(); else { const frameContainerBorderWidth = 1; this._frameContainer = document.createElement("div"); this._frameContainer.addStyleClass("fill"); this._frameContainer.addStyleClass("timeline-frame-container"); this._frameContainer.style.height = this._headerLineCount * WebInspector.TimelinePanel.rowHeight + frameContainerBorderWidth + "px"; this._frameContainer.addEventListener("dblclick", this._onFrameDoubleClicked.bind(this), false); } var dividers = [ this._frameContainer ]; for (var i = 0; i < frames.length; ++i) { var frame = frames[i]; var frameStart = this._calculator.computePosition(frame.startTime); var frameEnd = this._calculator.computePosition(frame.endTime); var frameStrip = document.createElement("div"); frameStrip.className = "timeline-frame-strip"; var actualStart = Math.max(frameStart, 0); var width = frameEnd - actualStart; frameStrip.style.left = actualStart + "px"; frameStrip.style.width = width + "px"; frameStrip._frame = frame; const minWidthForFrameInfo = 60; if (width > minWidthForFrameInfo) frameStrip.textContent = Number.secondsToString(frame.endTime - frame.startTime, true); this._frameContainer.appendChild(frameStrip); if (actualStart > 0) { var frameMarker = WebInspector.TimelinePresentationModel.createEventDivider(WebInspector.TimelineModel.RecordType.BeginFrame); frameMarker.style.left = frameStart + "px"; dividers.push(frameMarker); } } this._timelineGrid.addEventDividers(dividers); }, _onFrameDoubleClicked: function(event) { var frameBar = event.target.enclosingNodeOrSelfWithClass("timeline-frame-strip"); if (!frameBar) return; this._overviewPane.zoomToFrame(frameBar._frame); }, _overviewModeChanged: function(event) { var mode = event.data; var shouldShowMemory = mode === WebInspector.TimelineOverviewPane.Mode.Memory; var frameMode = mode === WebInspector.TimelineOverviewPane.Mode.Frames; this._overviewModeSetting.set(mode); if (frameMode !== this._frameMode) { this._frameMode = frameMode; this._glueParentButton.setEnabled(!frameMode); this._presentationModel.setGlueRecords(this._glueParentButton.toggled && !frameMode); this._repopulateRecords(); if (frameMode) { this.element.addStyleClass("timeline-frame-overview"); this.recordsCounter.addStyleClass("hidden"); this.frameStatistics.removeStyleClass("hidden"); this._frameController = new WebInspector.TimelineFrameController(this._model, this._overviewPane, this._presentationModel); } else { this._frameController.dispose(); this._frameController = null; this.element.removeStyleClass("timeline-frame-overview"); this.recordsCounter.removeStyleClass("hidden"); this.frameStatistics.addStyleClass("hidden"); } } if (shouldShowMemory === this._memoryStatistics.visible()) return; if (!shouldShowMemory) { this._timelineMemorySplitter.addStyleClass("hidden"); this._memoryStatistics.hide(); this.splitView.element.style.height = "auto"; this.splitView.element.style.bottom = "0"; this.onResize(); } else { this._timelineMemorySplitter.removeStyleClass("hidden"); this._memoryStatistics.show(); this.splitView.element.style.bottom = "auto"; this._setSplitterPosition(WebInspector.settings.memoryCounterGraphsHeight.get()); } }, _toggleTimelineButtonClicked: function() { if (this._operationInProgress) return; if (this.toggleTimelineButton.toggled) { this._model.stopRecord(); this.toggleTimelineButton.title = WebInspector.UIString("Record"); } else { this._model.startRecord(); this.toggleTimelineButton.title = WebInspector.UIString("Stop"); WebInspector.userMetrics.TimelineStarted.record(); } this.toggleTimelineButton.toggled = !this.toggleTimelineButton.toggled; }, _durationFilterChanged: function() { var option = this._durationFilterSelector.selectedOption(); var minimumRecordDuration = +option._durationMs / 1000.0; this._durationFilter.setMinimumRecordDuration(minimumRecordDuration); this._overviewPane.setMinimumRecordDuration(minimumRecordDuration); this._durationFilterSelector.element.title = option.title; this._invalidateAndScheduleRefresh(true); }, _garbageCollectButtonClicked: function() { ProfilerAgent.collectGarbage(); }, _glueParentButtonClicked: function() { var newValue = !this._glueParentButton.toggled; this._glueParentButton.toggled = newValue; this._presentationModel.setGlueRecords(newValue); this._glueRecordsSetting.set(newValue); this._repopulateRecords(); }, _repopulateRecords: function() { this._resetPanel(); this._automaticallySizeWindow = false; var records = this._model.records; for (var i = 0; i < records.length; ++i) this._innerAddRecordToTimeline(records[i]); this._invalidateAndScheduleRefresh(false); }, _onTimelineEventRecorded: function(event) { if (this._innerAddRecordToTimeline(event.data)) this._invalidateAndScheduleRefresh(false); }, _innerAddRecordToTimeline: function(record) { if (record.type === WebInspector.TimelineModel.RecordType.Program) { this._mainThreadTasks.push({ startTime: WebInspector.TimelineModel.startTimeInSeconds(record), endTime: WebInspector.TimelineModel.endTimeInSeconds(record) }); } var records = this._presentationModel.addRecord(record); this._allRecordsCount += records.length; var timeStampRecords = this._timeStampRecords; var hasVisibleRecords = false; var presentationModel = this._presentationModel; function processRecord(record) { if (WebInspector.TimelinePresentationModel.isEventDivider(record)) timeStampRecords.push(record); hasVisibleRecords |= presentationModel.isVisible(record); } WebInspector.TimelinePresentationModel.forAllRecords(records, processRecord); function isAdoptedRecord(record) { return record.parent !== presentationModel.rootRecord; } return hasVisibleRecords || records.some(isAdoptedRecord); }, sidebarResized: function(event) { var width = event.data; this._resize(width); this._sidebarBackgroundElement.style.width = width + "px"; this._overviewPane.sidebarResized(width); this._memoryStatistics.setSidebarWidth(width); this._timelineGrid.gridHeaderElement.style.left = width + "px"; }, onResize: function() { this._resize(this.splitView.sidebarWidth()); }, _resize: function(sidebarWidth) { this._closeRecordDetails(); this._scheduleRefresh(false); this._graphRowsElementWidth = this._graphRowsElement.offsetWidth; this._containerElementHeight = this._containerElement.clientHeight; var lastItemElement = this._statusBarItems[this._statusBarItems.length - 1].element; var minFloatingStatusBarItemsOffset = lastItemElement.totalOffsetLeft() + lastItemElement.offsetWidth; this._timelineGrid.gridHeaderElement.style.width = this._itemsGraphsElement.offsetWidth + "px"; this._miscStatusBarItems.style.left = Math.max(minFloatingStatusBarItemsOffset, sidebarWidth) + "px"; }, _clearPanel: function() { this._model.reset(); }, _onRecordsCleared: function() { this._resetPanel(); this._invalidateAndScheduleRefresh(true); }, _resetPanel: function() { this._presentationModel.reset(); this._timeStampRecords = []; this._boundariesAreValid = false; this._adjustScrollPosition(0); this._closeRecordDetails(); this._allRecordsCount = 0; this._automaticallySizeWindow = true; this._mainThreadTasks = []; }, elementsToRestoreScrollPositionsFor: function() { return [this._containerElement]; }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); if (!WebInspector.TimelinePanel._categoryStylesInitialized) { WebInspector.TimelinePanel._categoryStylesInitialized = true; this._injectCategoryStyles(); } this._overviewPane.setMode(this._overviewModeSetting.get()); this._refresh(); }, willHide: function() { this._closeRecordDetails(); WebInspector.Panel.prototype.willHide.call(this); }, _onScroll: function(event) { this._closeRecordDetails(); this._scrollTop = this._containerElement.scrollTop; var dividersTop = Math.max(0, this._scrollTop); this._timelineGrid.setScrollAndDividerTop(this._scrollTop, dividersTop); this._scheduleRefresh(true); }, _invalidateAndScheduleRefresh: function(preserveBoundaries) { this._presentationModel.invalidateFilteredRecords(); delete this._searchResults; this._scheduleRefresh(preserveBoundaries); }, _scheduleRefresh: function(preserveBoundaries) { this._closeRecordDetails(); this._boundariesAreValid &= preserveBoundaries; if (!this.isShowing()) return; if (preserveBoundaries) this._refresh(); else { if (!this._refreshTimeout) this._refreshTimeout = setTimeout(this._refresh.bind(this), 300); } }, _refresh: function() { if (this._refreshTimeout) { clearTimeout(this._refreshTimeout); delete this._refreshTimeout; } this._timelinePaddingLeft = !this._overviewPane.windowLeft() ? this._expandOffset : 0; this._calculator.setWindow(this._overviewPane.windowStartTime(), this._overviewPane.windowEndTime()); this._calculator.setDisplayWindow(this._timelinePaddingLeft, this._graphRowsElementWidth); var recordsInWindowCount = this._refreshRecords(); this._updateRecordsCounter(recordsInWindowCount); if (!this._boundariesAreValid) { this._updateEventDividers(); var frames = this._frameController && this._presentationModel.filteredFrames(this._overviewPane.windowStartTime(), this._overviewPane.windowEndTime()); if (frames) { this._updateFrameStatistics(frames); const maxFramesForFrameBars = 30; if (frames.length && frames.length < maxFramesForFrameBars) { this._timelineGrid.removeDividers(); this._updateFrameBars(frames); } else this._timelineGrid.updateDividers(this._calculator); } else this._timelineGrid.updateDividers(this._calculator); if (this._mainThreadMonitoringEnabled) this._refreshMainThreadBars(); } if (this._memoryStatistics.visible()) this._memoryStatistics.refresh(); this._boundariesAreValid = true; }, revealRecordAt: function(time) { var recordToReveal; function findRecordToReveal(record) { if (record.containsTime(time)) { recordToReveal = record; return true; } if (!recordToReveal || record.endTime < time && recordToReveal.endTime < record.endTime) recordToReveal = record; return false; } WebInspector.TimelinePresentationModel.forAllRecords(this._presentationModel.rootRecord().children, null, findRecordToReveal); if (!recordToReveal) { this._containerElement.scrollTop = 0; return; } this._revealRecord(recordToReveal); }, _revealRecord: function(recordToReveal) { var treeUpdated = false; for (var parent = recordToReveal.parent; parent !== this._rootRecord(); parent = parent.parent) { treeUpdated = treeUpdated || parent.collapsed; parent.collapsed = false; } if (treeUpdated) this._invalidateAndScheduleRefresh(true); var recordsInWindow = this._presentationModel.filteredRecords(); var index = recordsInWindow.indexOf(recordToReveal); this._containerElement.scrollTop = index * WebInspector.TimelinePanel.rowHeight; }, _refreshRecords: function() { var recordsInWindow = this._presentationModel.filteredRecords(); var visibleTop = this._scrollTop; var visibleBottom = visibleTop + this._containerElementHeight; const rowHeight = WebInspector.TimelinePanel.rowHeight; var startIndex = Math.max(0, Math.min(Math.floor(visibleTop / rowHeight) - this._headerLineCount, recordsInWindow.length - 1)); var endIndex = Math.min(recordsInWindow.length, Math.ceil(visibleBottom / rowHeight)); var lastVisibleLine = Math.max(0, Math.floor(visibleBottom / rowHeight) - this._headerLineCount); if (this._automaticallySizeWindow && recordsInWindow.length > lastVisibleLine) { this._automaticallySizeWindow = false; var windowStartTime = startIndex ? recordsInWindow[startIndex].startTime : this._model.minimumRecordTime(); this._overviewPane.setWindowTimes(windowStartTime, recordsInWindow[Math.max(0, lastVisibleLine - 1)].endTime); recordsInWindow = this._presentationModel.filteredRecords(); endIndex = Math.min(recordsInWindow.length, lastVisibleLine); } const top = (startIndex * rowHeight) + "px"; this._topGapElement.style.height = top; this.sidebarElement.style.top = top; this._bottomGapElement.style.height = (recordsInWindow.length - endIndex) * rowHeight + "px"; var listRowElement = this._sidebarListElement.firstChild; var width = this._graphRowsElementWidth; this._itemsGraphsElement.removeChild(this._graphRowsElement); var graphRowElement = this._graphRowsElement.firstChild; var scheduleRefreshCallback = this._invalidateAndScheduleRefresh.bind(this, true); this._itemsGraphsElement.removeChild(this._expandElements); this._expandElements.removeChildren(); for (var i = 0; i < endIndex; ++i) { var record = recordsInWindow[i]; var isEven = !(i % 2); if (i < startIndex) { var lastChildIndex = i + record.visibleChildrenCount; if (lastChildIndex >= startIndex && lastChildIndex < endIndex) { var expandElement = new WebInspector.TimelineExpandableElement(this._expandElements); var positions = this._calculator.computeBarGraphWindowPosition(record); expandElement._update(record, i, positions.left - this._expandOffset, positions.width); } } else { if (!listRowElement) { listRowElement = new WebInspector.TimelineRecordListRow().element; this._sidebarListElement.appendChild(listRowElement); } if (!graphRowElement) { graphRowElement = new WebInspector.TimelineRecordGraphRow(this._itemsGraphsElement, scheduleRefreshCallback).element; this._graphRowsElement.appendChild(graphRowElement); } listRowElement.row.update(record, isEven, visibleTop); graphRowElement.row.update(record, isEven, this._calculator, this._expandOffset, i); listRowElement = listRowElement.nextSibling; graphRowElement = graphRowElement.nextSibling; } } while (listRowElement) { var nextElement = listRowElement.nextSibling; listRowElement.row.dispose(); listRowElement = nextElement; } while (graphRowElement) { var nextElement = graphRowElement.nextSibling; graphRowElement.row.dispose(); graphRowElement = nextElement; } this._itemsGraphsElement.insertBefore(this._graphRowsElement, this._bottomGapElement); this._itemsGraphsElement.appendChild(this._expandElements); this._adjustScrollPosition((recordsInWindow.length + this._headerLineCount) * rowHeight); this._updateSearchHighlight(false); return recordsInWindow.length; }, _refreshMainThreadBars: function() { const barOffset = 3; const minGap = 3; var minWidth = WebInspector.TimelineCalculator._minWidth; var widthAdjustment = minWidth / 2; var width = this._graphRowsElementWidth; var boundarySpan = this._overviewPane.windowEndTime() - this._overviewPane.windowStartTime(); var scale = boundarySpan / (width - minWidth - this._timelinePaddingLeft); var startTime = this._overviewPane.windowStartTime() - this._timelinePaddingLeft * scale; var endTime = startTime + width * scale; var tasks = this._mainThreadMonitoringEnabled ? this._mainThreadTasks : []; function compareEndTime(value, task) { return value < task.endTime ? -1 : 1; } var taskIndex = insertionIndexForObjectInListSortedByFunction(startTime, tasks, compareEndTime); var container = this._cpuBarsElement; var element = container.firstChild; var lastElement; var lastLeft; var lastRight; while (taskIndex < tasks.length) { var task = tasks[taskIndex]; if (task.startTime > endTime) break; taskIndex++; var left = Math.max(0, this._calculator.computePosition(task.startTime) + barOffset - widthAdjustment); var right = Math.min(width, this._calculator.computePosition(task.endTime) + barOffset + widthAdjustment); if (lastElement) { var gap = Math.floor(left) - Math.ceil(lastRight); if (gap < minGap) { lastRight = right; lastElement._tasksInfo.lastTaskIndex = taskIndex; continue; } lastElement.style.width = (lastRight - lastLeft) + "px"; } if (!element) element = container.createChild("div", "timeline-graph-bar"); element.style.left = left + "px"; element._tasksInfo = {tasks: tasks, firstTaskIndex: taskIndex, lastTaskIndex: taskIndex}; lastLeft = left; lastRight = right; lastElement = element; element = element.nextSibling; } if (lastElement) lastElement.style.width = (lastRight - lastLeft) + "px"; while (element) { var nextElement = element.nextSibling; element._tasksInfo = null; container.removeChild(element); element = nextElement; } }, _adjustHeaderHeight: function() { const headerBorderWidth = 1; const headerMargin = 2; var headerHeight = this._headerLineCount * WebInspector.TimelinePanel.rowHeight; this.sidebarElement.firstChild.style.height = headerHeight + "px"; this._timelineGrid.dividersLabelBarElement.style.height = headerHeight + headerMargin + "px"; this._itemsGraphsElement.style.top = headerHeight + headerBorderWidth + "px"; }, _adjustScrollPosition: function(totalHeight) { if ((this._scrollTop + this._containerElementHeight) > totalHeight + 1) this._containerElement.scrollTop = (totalHeight - this._containerElement.offsetHeight); }, _getPopoverAnchor: function(element) { return element.enclosingNodeOrSelfWithClass("timeline-graph-bar") || element.enclosingNodeOrSelfWithClass("timeline-tree-item") || element.enclosingNodeOrSelfWithClass("timeline-frame-strip"); }, _mouseOut: function(e) { this._hideRectHighlight(); }, _mouseMove: function(e) { var anchor = this._getPopoverAnchor(e.target); const recordType = WebInspector.TimelineModel.RecordType; if (anchor && anchor.row && (anchor.row._record.type === recordType.Paint || anchor.row._record.type === recordType.Layout)) this._highlightRect(anchor.row._record); else this._hideRectHighlight(); }, _highlightRect: function(record) { if (this._highlightedRect === record.data) return; this._highlightedRect = record.data; DOMAgent.highlightRect(this._highlightedRect.x, this._highlightedRect.y, this._highlightedRect.width, this._highlightedRect.height, WebInspector.Color.PageHighlight.Content.toProtocolRGBA(), WebInspector.Color.PageHighlight.ContentOutline.toProtocolRGBA()); }, _hideRectHighlight: function() { if (this._highlightedRect) { delete this._highlightedRect; DOMAgent.hideHighlight(); } }, _showPopover: function(anchor, popover) { if (anchor.hasStyleClass("timeline-frame-strip")) { var frame = anchor._frame; popover.show(WebInspector.TimelinePresentationModel.generatePopupContentForFrame(frame), anchor); } else { if (anchor.row && anchor.row._record) anchor.row._record.generatePopupContent(showCallback); else if (anchor._tasksInfo) popover.show(this._presentationModel.generateMainThreadBarPopupContent(anchor._tasksInfo), anchor); } function showCallback(popupContent) { popover.show(popupContent, anchor); } }, _closeRecordDetails: function() { this._popoverHelper.hidePopover(); }, _injectCategoryStyles: function() { var style = document.createElement("style"); var categories = WebInspector.TimelinePresentationModel.categories(); style.textContent = Object.values(categories).map(WebInspector.TimelinePresentationModel.createStyleRuleForCategory).join("\n"); document.head.appendChild(style); }, jumpToNextSearchResult: function() { this._jumpToAdjacentRecord(1); }, jumpToPreviousSearchResult: function() { this._jumpToAdjacentRecord(-1); }, _jumpToAdjacentRecord: function(offset) { if (!this._searchResults || !this._searchResults.length || !this._selectedSearchResult) return; var index = this._searchResults.indexOf(this._selectedSearchResult); index = (index + offset + this._searchResults.length) % this._searchResults.length; this._selectSearchResult(index); this._highlightSelectedSearchResult(true); }, _selectSearchResult: function(index) { this._selectedSearchResult = this._searchResults[index]; WebInspector.searchController.updateCurrentMatchIndex(index, this); }, _highlightSelectedSearchResult: function(revealRecord) { this._clearHighlight(); if (this._searchFilter) return; var record = this._selectedSearchResult; if (!record) return; for (var element = this._sidebarListElement.firstChild; element; element = element.nextSibling) { if (element.row._record === record) { element.row.highlight(this._searchRegExp, this._highlightDomChanges); return; } } if (revealRecord) this._revealRecord(record); }, _clearHighlight: function() { if (this._highlightDomChanges) WebInspector.revertDomChanges(this._highlightDomChanges); this._highlightDomChanges = []; }, _updateSearchHighlight: function(revealRecord) { if (this._searchFilter || !this._searchRegExp) { this._clearHighlight(); return; } if (!this._searchResults) this._updateSearchResults(); this._highlightSelectedSearchResult(revealRecord); }, _updateSearchResults: function() { var searchRegExp = this._searchRegExp; if (!searchRegExp) return; var matches = []; var presentationModel = this._presentationModel; function processRecord(record) { if (presentationModel.isVisible(record) && WebInspector.TimelineRecordListRow.testContentMatching(record, searchRegExp)) matches.push(record); return false; } WebInspector.TimelinePresentationModel.forAllRecords(presentationModel.rootRecord().children, processRecord); var matchesCount = matches.length; if (matchesCount) { this._searchResults = matches; WebInspector.searchController.updateSearchMatchesCount(matchesCount, this); var selectedIndex = matches.indexOf(this._selectedSearchResult); if (selectedIndex === -1) selectedIndex = 0; this._selectSearchResult(selectedIndex); } else { WebInspector.searchController.updateSearchMatchesCount(0, this); delete this._selectedSearchResult; } }, searchCanceled: function() { this._clearHighlight(); delete this._searchResults; delete this._selectedSearchResult; delete this._searchRegExp; }, canFilter: function() { return true; }, performFilter: function(searchQuery) { this._presentationModel.removeFilter(this._searchFilter); delete this._searchFilter; this.searchCanceled(); if (searchQuery) { this._searchFilter = new WebInspector.TimelineSearchFilter(createPlainTextSearchRegex(searchQuery, "i")); this._presentationModel.addFilter(this._searchFilter); } this._invalidateAndScheduleRefresh(true); }, performSearch: function(searchQuery) { this._searchRegExp = createPlainTextSearchRegex(searchQuery, "i"); delete this._searchResults; this._updateSearchHighlight(true); }, __proto__: WebInspector.Panel.prototype } WebInspector.TimelineCalculator = function(model) { this._model = model; } WebInspector.TimelineCalculator._minWidth = 5; WebInspector.TimelineCalculator.prototype = { computePosition: function(time) { return (time - this._minimumBoundary) / this.boundarySpan() * this._workingArea + this.paddingLeft; }, computeBarGraphPercentages: function(record) { var start = (record.startTime - this._minimumBoundary) / this.boundarySpan() * 100; var end = (record.startTime + record.selfTime - this._minimumBoundary) / this.boundarySpan() * 100; var endWithChildren = (record.lastChildEndTime - this._minimumBoundary) / this.boundarySpan() * 100; var cpuWidth = record.cpuTime / this.boundarySpan() * 100; return {start: start, end: end, endWithChildren: endWithChildren, cpuWidth: cpuWidth}; }, computeBarGraphWindowPosition: function(record) { var percentages = this.computeBarGraphPercentages(record); var widthAdjustment = 0; var left = this.computePosition(record.startTime); var width = (percentages.end - percentages.start) / 100 * this._workingArea; if (width < WebInspector.TimelineCalculator._minWidth) { widthAdjustment = WebInspector.TimelineCalculator._minWidth - width; left -= widthAdjustment / 2; width += widthAdjustment; } var widthWithChildren = (percentages.endWithChildren - percentages.start) / 100 * this._workingArea + widthAdjustment; var cpuWidth = percentages.cpuWidth / 100 * this._workingArea + widthAdjustment; if (percentages.endWithChildren > percentages.end) widthWithChildren += widthAdjustment; return {left: left, width: width, widthWithChildren: widthWithChildren, cpuWidth: cpuWidth}; }, setWindow: function(minimumBoundary, maximumBoundary) { this._minimumBoundary = minimumBoundary; this._maximumBoundary = maximumBoundary; }, setDisplayWindow: function(paddingLeft, clientWidth) { this._workingArea = clientWidth - WebInspector.TimelineCalculator._minWidth - paddingLeft; this.paddingLeft = paddingLeft; }, formatTime: function(value) { return Number.secondsToString(value + this._minimumBoundary - this._model.minimumRecordTime()); }, maximumBoundary: function() { return this._maximumBoundary; }, minimumBoundary: function() { return this._minimumBoundary; }, boundarySpan: function() { return this._maximumBoundary - this._minimumBoundary; } } WebInspector.TimelineRecordListRow = function() { this.element = document.createElement("div"); this.element.row = this; this.element.style.cursor = "pointer"; var iconElement = document.createElement("span"); iconElement.className = "timeline-tree-icon"; this.element.appendChild(iconElement); this._typeElement = document.createElement("span"); this._typeElement.className = "type"; this.element.appendChild(this._typeElement); var separatorElement = document.createElement("span"); separatorElement.className = "separator"; separatorElement.textContent = " "; this._dataElement = document.createElement("span"); this._dataElement.className = "data dimmed"; this.element.appendChild(separatorElement); this.element.appendChild(this._dataElement); } WebInspector.TimelineRecordListRow.prototype = { update: function(record, isEven, offset) { this._record = record; this._offset = offset; this.element.className = "timeline-tree-item timeline-category-" + record.category.name; if (isEven) this.element.addStyleClass("even"); if (record.hasWarning) this.element.addStyleClass("warning"); else if (record.childHasWarning) this.element.addStyleClass("child-warning"); this._typeElement.textContent = record.title; if (this._dataElement.firstChild) this._dataElement.removeChildren(); if (record.detailsNode()) this._dataElement.appendChild(record.detailsNode()); }, highlight: function(regExp, domChanges) { var matchInfo = this.element.textContent.match(regExp); if (matchInfo) WebInspector.highlightSearchResult(this.element, matchInfo.index, matchInfo[0].length, domChanges); }, dispose: function() { this.element.parentElement.removeChild(this.element); } } WebInspector.TimelineRecordListRow.testContentMatching = function(record, regExp) { var toSearchText = record.title; if (record.detailsNode()) toSearchText += " " + record.detailsNode().textContent; return regExp.test(toSearchText); } WebInspector.TimelineRecordGraphRow = function(graphContainer, scheduleRefresh) { this.element = document.createElement("div"); this.element.row = this; this._barAreaElement = document.createElement("div"); this._barAreaElement.className = "timeline-graph-bar-area"; this.element.appendChild(this._barAreaElement); this._barWithChildrenElement = document.createElement("div"); this._barWithChildrenElement.className = "timeline-graph-bar with-children"; this._barWithChildrenElement.row = this; this._barAreaElement.appendChild(this._barWithChildrenElement); this._barCpuElement = document.createElement("div"); this._barCpuElement.className = "timeline-graph-bar cpu" this._barCpuElement.row = this; this._barAreaElement.appendChild(this._barCpuElement); this._barElement = document.createElement("div"); this._barElement.className = "timeline-graph-bar"; this._barElement.row = this; this._barAreaElement.appendChild(this._barElement); this._expandElement = new WebInspector.TimelineExpandableElement(graphContainer); this._expandElement._element.addEventListener("click", this._onClick.bind(this)); this._scheduleRefresh = scheduleRefresh; } WebInspector.TimelineRecordGraphRow.prototype = { update: function(record, isEven, calculator, expandOffset, index) { this._record = record; this.element.className = "timeline-graph-side timeline-category-" + record.category.name + (isEven ? " even" : ""); var barPosition = calculator.computeBarGraphWindowPosition(record); this._barWithChildrenElement.style.left = barPosition.left + "px"; this._barWithChildrenElement.style.width = barPosition.widthWithChildren + "px"; this._barElement.style.left = barPosition.left + "px"; this._barElement.style.width = barPosition.width + "px"; this._barCpuElement.style.left = barPosition.left + "px"; this._barCpuElement.style.width = barPosition.cpuWidth + "px"; this._expandElement._update(record, index, barPosition.left - expandOffset, barPosition.width); }, _onClick: function(event) { this._record.collapsed = !this._record.collapsed; this._scheduleRefresh(false); }, dispose: function() { this.element.parentElement.removeChild(this.element); this._expandElement._dispose(); } } WebInspector.TimelineExpandableElement = function(container) { this._element = document.createElement("div"); this._element.className = "timeline-expandable"; var leftBorder = document.createElement("div"); leftBorder.className = "timeline-expandable-left"; this._element.appendChild(leftBorder); container.appendChild(this._element); } WebInspector.TimelineExpandableElement.prototype = { _update: function(record, index, left, width) { const rowHeight = WebInspector.TimelinePanel.rowHeight; if (record.visibleChildrenCount || record.invisibleChildrenCount) { this._element.style.top = index * rowHeight + "px"; this._element.style.left = left + "px"; this._element.style.width = Math.max(12, width + 25) + "px"; if (!record.collapsed) { this._element.style.height = (record.visibleChildrenCount + 1) * rowHeight + "px"; this._element.addStyleClass("timeline-expandable-expanded"); this._element.removeStyleClass("timeline-expandable-collapsed"); } else { this._element.style.height = rowHeight + "px"; this._element.addStyleClass("timeline-expandable-collapsed"); this._element.removeStyleClass("timeline-expandable-expanded"); } this._element.removeStyleClass("hidden"); } else this._element.addStyleClass("hidden"); }, _dispose: function() { this._element.parentElement.removeChild(this._element); } } WebInspector.TimelineCategoryFilter = function() { } WebInspector.TimelineCategoryFilter.prototype = { accept: function(record) { return !record.category.hidden && record.type !== WebInspector.TimelineModel.RecordType.BeginFrame; } } WebInspector.TimelineIsLongFilter = function() { this._minimumRecordDuration = 0; } WebInspector.TimelineIsLongFilter.prototype = { setMinimumRecordDuration: function(value) { this._minimumRecordDuration = value; }, accept: function(record) { return this._minimumRecordDuration ? ((record.lastChildEndTime - record.startTime) >= this._minimumRecordDuration) : true; } } WebInspector.TimelineSearchFilter = function(regExp) { this._regExp = regExp; } WebInspector.TimelineSearchFilter.prototype = { accept: function(record) { return WebInspector.TimelineRecordListRow.testContentMatching(record, this._regExp); } }
JavaScript
WebInspector.AuditsPanel = function() { WebInspector.Panel.call(this, "audits"); this.registerRequiredCSS("panelEnablerView.css"); this.registerRequiredCSS("auditsPanel.css"); this.createSidebarViewWithTree(); this.auditsTreeElement = new WebInspector.SidebarSectionTreeElement("", {}, true); this.sidebarTree.appendChild(this.auditsTreeElement); this.auditsTreeElement.listItemElement.addStyleClass("hidden"); this.auditsItemTreeElement = new WebInspector.AuditsSidebarTreeElement(this); this.auditsTreeElement.appendChild(this.auditsItemTreeElement); this.auditResultsTreeElement = new WebInspector.SidebarSectionTreeElement(WebInspector.UIString("RESULTS"), {}, true); this.sidebarTree.appendChild(this.auditResultsTreeElement); this.auditResultsTreeElement.expand(); this.clearResultsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear audit results."), "clear-status-bar-item"); this.clearResultsButton.addEventListener("click", this._clearButtonClicked, this); this.viewsContainerElement = this.splitView.mainElement; this._constructCategories(); this._launcherView = new WebInspector.AuditLauncherView(this.initiateAudit.bind(this)); for (var id in this.categoriesById) this._launcherView.addCategory(this.categoriesById[id]); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.OnLoad, this._didMainResourceLoad, this); } WebInspector.AuditsPanel.prototype = { get statusBarItems() { return [this.clearResultsButton.element]; }, get categoriesById() { return this._auditCategoriesById; }, addCategory: function(category) { this.categoriesById[category.id] = category; this._launcherView.addCategory(category); }, getCategory: function(id) { return this.categoriesById[id]; }, _constructCategories: function() { this._auditCategoriesById = {}; for (var categoryCtorID in WebInspector.AuditCategories) { var auditCategory = new WebInspector.AuditCategories[categoryCtorID](); auditCategory._id = categoryCtorID; this.categoriesById[categoryCtorID] = auditCategory; } }, _executeAudit: function(categories, resultCallback) { this._progress.setTitle(WebInspector.UIString("Running audit")); function ruleResultReadyCallback(categoryResult, ruleResult) { if (ruleResult && ruleResult.children) categoryResult.addRuleResult(ruleResult); if (this._progress.isCanceled()) this._progress.done(); } var results = []; var mainResourceURL = WebInspector.inspectedPageURL; var categoriesDone = 0; function categoryDoneCallback() { if (++categoriesDone !== categories.length) return; this._progress.done(); resultCallback(mainResourceURL, results) } var requests = WebInspector.networkLog.requests.slice(); var compositeProgress = new WebInspector.CompositeProgress(this._progress); var subprogresses = []; for (var i = 0; i < categories.length; ++i) subprogresses.push(compositeProgress.createSubProgress()); for (var i = 0; i < categories.length; ++i) { var category = categories[i]; var result = new WebInspector.AuditCategoryResult(category); results.push(result); category.run(requests, ruleResultReadyCallback.bind(this, result), categoryDoneCallback.bind(this), subprogresses[i]); } }, _auditFinishedCallback: function(launcherCallback, mainResourceURL, results) { var children = this.auditResultsTreeElement.children; var ordinal = 1; for (var i = 0; i < children.length; ++i) { if (children[i].mainResourceURL === mainResourceURL) ordinal++; } var resultTreeElement = new WebInspector.AuditResultSidebarTreeElement(this, results, mainResourceURL, ordinal); this.auditResultsTreeElement.appendChild(resultTreeElement); resultTreeElement.revealAndSelect(); if (!this._progress.isCanceled()) launcherCallback(); }, initiateAudit: function(categoryIds, progress, runImmediately, startedCallback, finishedCallback) { if (!categoryIds || !categoryIds.length) return; this._progress = progress; var categories = []; for (var i = 0; i < categoryIds.length; ++i) categories.push(this.categoriesById[categoryIds[i]]); function startAuditWhenResourcesReady() { startedCallback(); this._executeAudit(categories, this._auditFinishedCallback.bind(this, finishedCallback)); } if (runImmediately) startAuditWhenResourcesReady.call(this); else this._reloadResources(startAuditWhenResourcesReady.bind(this)); WebInspector.userMetrics.AuditsStarted.record(); }, _reloadResources: function(callback) { this._pageReloadCallback = callback; PageAgent.reload(false); }, _didMainResourceLoad: function() { if (this._pageReloadCallback) { var callback = this._pageReloadCallback; delete this._pageReloadCallback; callback(); } }, showResults: function(categoryResults) { if (!categoryResults._resultView) categoryResults._resultView = new WebInspector.AuditResultView(categoryResults); this.visibleView = categoryResults._resultView; }, showLauncherView: function() { this.visibleView = this._launcherView; }, get visibleView() { return this._visibleView; }, set visibleView(x) { if (this._visibleView === x) return; if (this._visibleView) this._visibleView.detach(); this._visibleView = x; if (x) x.show(this.viewsContainerElement); }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); if (!this._visibleView) this.auditsItemTreeElement.select(); }, _clearButtonClicked: function() { this.auditsItemTreeElement.revealAndSelect(); this.auditResultsTreeElement.removeChildren(); }, __proto__: WebInspector.Panel.prototype } WebInspector.AuditCategory = function(displayName) { this._displayName = displayName; this._rules = []; } WebInspector.AuditCategory.prototype = { get id() { return this._id; }, get displayName() { return this._displayName; }, addRule: function(rule, severity) { rule.severity = severity; this._rules.push(rule); }, run: function(requests, ruleResultCallback, categoryDoneCallback, progress) { this._ensureInitialized(); var remainingRulesCount = this._rules.length; progress.setTotalWork(remainingRulesCount); function callbackWrapper(result) { ruleResultCallback(result); progress.worked(); if (!--remainingRulesCount) categoryDoneCallback(); } for (var i = 0; i < this._rules.length; ++i) this._rules[i].run(requests, callbackWrapper, progress); }, _ensureInitialized: function() { if (!this._initialized) { if ("initialize" in this) this.initialize(); this._initialized = true; } } } WebInspector.AuditRule = function(id, displayName) { this._id = id; this._displayName = displayName; } WebInspector.AuditRule.Severity = { Info: "info", Warning: "warning", Severe: "severe" } WebInspector.AuditRule.SeverityOrder = { "info": 3, "warning": 2, "severe": 1 } WebInspector.AuditRule.prototype = { get id() { return this._id; }, get displayName() { return this._displayName; }, set severity(severity) { this._severity = severity; }, run: function(requests, callback, progress) { if (progress.isCanceled()) return; var result = new WebInspector.AuditRuleResult(this.displayName); result.severity = this._severity; this.doRun(requests, result, callback, progress); }, doRun: function(requests, result, callback, progress) { throw new Error("doRun() not implemented"); } } WebInspector.AuditCategoryResult = function(category) { this.title = category.displayName; this.ruleResults = []; } WebInspector.AuditCategoryResult.prototype = { addRuleResult: function(ruleResult) { this.ruleResults.push(ruleResult); } } WebInspector.AuditRuleResult = function(value, expanded, className) { this.value = value; this.className = className; this.expanded = expanded; this.violationCount = 0; this._formatters = { r: WebInspector.AuditRuleResult.linkifyDisplayName }; var standardFormatters = Object.keys(String.standardFormatters); for (var i = 0; i < standardFormatters.length; ++i) this._formatters[standardFormatters[i]] = String.standardFormatters[standardFormatters[i]]; } WebInspector.AuditRuleResult.linkifyDisplayName = function(url) { return WebInspector.linkifyURLAsNode(url, WebInspector.displayNameForURL(url)); } WebInspector.AuditRuleResult.resourceDomain = function(domain) { return domain || WebInspector.UIString("[empty domain]"); } WebInspector.AuditRuleResult.prototype = { addChild: function(value, expanded, className) { if (!this.children) this.children = []; var entry = new WebInspector.AuditRuleResult(value, expanded, className); this.children.push(entry); return entry; }, addURL: function(url) { this.addChild(WebInspector.AuditRuleResult.linkifyDisplayName(url)); }, addURLs: function(urls) { for (var i = 0; i < urls.length; ++i) this.addURL(urls[i]); }, addSnippet: function(snippet) { this.addChild(snippet, false, "source-code"); }, addFormatted: function(format, vararg) { var substitutions = Array.prototype.slice.call(arguments, 1); var fragment = document.createDocumentFragment(); function append(a, b) { if (!(b instanceof Node)) b = document.createTextNode(b); a.appendChild(b); return a; } var formattedResult = String.format(format, substitutions, this._formatters, fragment, append).formattedResult; if (formattedResult instanceof Node) formattedResult.normalize(); return this.addChild(formattedResult); } } WebInspector.AuditsSidebarTreeElement = function(panel) { this._panel = panel; this.small = false; WebInspector.SidebarTreeElement.call(this, "audits-sidebar-tree-item", WebInspector.UIString("Audits"), "", null, false); } WebInspector.AuditsSidebarTreeElement.prototype = { onattach: function() { WebInspector.SidebarTreeElement.prototype.onattach.call(this); }, onselect: function() { this._panel.showLauncherView(); }, get selectable() { return true; }, refresh: function() { this.refreshTitles(); }, __proto__: WebInspector.SidebarTreeElement.prototype } WebInspector.AuditResultSidebarTreeElement = function(panel, results, mainResourceURL, ordinal) { this._panel = panel; this.results = results; this.mainResourceURL = mainResourceURL; WebInspector.SidebarTreeElement.call(this, "audit-result-sidebar-tree-item", String.sprintf("%s (%d)", mainResourceURL, ordinal), "", {}, false); } WebInspector.AuditResultSidebarTreeElement.prototype = { onselect: function() { this._panel.showResults(this.results); }, get selectable() { return true; }, __proto__: WebInspector.SidebarTreeElement.prototype } WebInspector.AuditRules = {}; WebInspector.AuditCategories = {}; WebInspector.AuditCategories.PagePerformance = function() { WebInspector.AuditCategory.call(this, WebInspector.AuditCategories.PagePerformance.AuditCategoryName); } WebInspector.AuditCategories.PagePerformance.AuditCategoryName = "Web Page Performance"; WebInspector.AuditCategories.PagePerformance.prototype = { initialize: function() { this.addRule(new WebInspector.AuditRules.UnusedCssRule(), WebInspector.AuditRule.Severity.Warning); this.addRule(new WebInspector.AuditRules.CssInHeadRule(), WebInspector.AuditRule.Severity.Severe); this.addRule(new WebInspector.AuditRules.StylesScriptsOrderRule(), WebInspector.AuditRule.Severity.Severe); this.addRule(new WebInspector.AuditRules.VendorPrefixedCSSProperties(), WebInspector.AuditRule.Severity.Warning); }, __proto__: WebInspector.AuditCategory.prototype } WebInspector.AuditCategories.NetworkUtilization = function() { WebInspector.AuditCategory.call(this, WebInspector.AuditCategories.NetworkUtilization.AuditCategoryName); } WebInspector.AuditCategories.NetworkUtilization.AuditCategoryName = "Network Utilization"; WebInspector.AuditCategories.NetworkUtilization.prototype = { initialize: function() { this.addRule(new WebInspector.AuditRules.GzipRule(), WebInspector.AuditRule.Severity.Severe); this.addRule(new WebInspector.AuditRules.ImageDimensionsRule(), WebInspector.AuditRule.Severity.Warning); this.addRule(new WebInspector.AuditRules.CookieSizeRule(400), WebInspector.AuditRule.Severity.Warning); this.addRule(new WebInspector.AuditRules.StaticCookielessRule(5), WebInspector.AuditRule.Severity.Warning); this.addRule(new WebInspector.AuditRules.CombineJsResourcesRule(2), WebInspector.AuditRule.Severity.Severe); this.addRule(new WebInspector.AuditRules.CombineCssResourcesRule(2), WebInspector.AuditRule.Severity.Severe); this.addRule(new WebInspector.AuditRules.MinimizeDnsLookupsRule(4), WebInspector.AuditRule.Severity.Warning); this.addRule(new WebInspector.AuditRules.ParallelizeDownloadRule(4, 10, 0.5), WebInspector.AuditRule.Severity.Warning); this.addRule(new WebInspector.AuditRules.BrowserCacheControlRule(), WebInspector.AuditRule.Severity.Severe); this.addRule(new WebInspector.AuditRules.ProxyCacheControlRule(), WebInspector.AuditRule.Severity.Warning); }, __proto__: WebInspector.AuditCategory.prototype } ; WebInspector.AuditFormatters = function() { } WebInspector.AuditFormatters.Registry = { text: function(text) { return document.createTextNode(text); }, snippet: function(snippetText) { var div = document.createElement("div"); div.textContent = snippetText; div.className = "source-code"; return div; }, concat: function() { var parent = document.createElement("span"); for (var arg = 0; arg < arguments.length; ++arg) parent.appendChild(WebInspector.auditFormatters.apply(arguments[arg])); return parent; }, url: function(url, displayText, allowExternalNavigation) { var a = document.createElement("a"); a.href = sanitizeHref(url); a.title = url; a.textContent = displayText || url; if (allowExternalNavigation) a.target = "_blank"; return a; }, resourceLink: function(url, line) { return WebInspector.linkifyResourceAsNode(url, line, "console-message-url webkit-html-resource-link"); } }; WebInspector.AuditFormatters.prototype = { apply: function(value) { var formatter; var type = typeof value; var args; switch (type) { case "string": case "boolean": case "number": formatter = WebInspector.AuditFormatters.Registry.text; args = [ value.toString() ]; break; case "object": if (value instanceof Node) return value; if (value instanceof Array) { formatter = WebInspector.AuditFormatters.Registry.concat; args = value; } else if (value.type && value.arguments) { formatter = WebInspector.AuditFormatters.Registry[value.type]; args = value.arguments; } } if (!formatter) throw "Invalid value or formatter: " + type + JSON.stringify(value); return formatter.apply(null, args); }, partiallyApply: function(formatters, thisArgument, value) { if (value instanceof Array) return value.map(this.partiallyApply.bind(this, formatters, thisArgument)); if (typeof value === "object" && typeof formatters[value.type] === "function" && value.arguments) return formatters[value.type].apply(thisArgument, value.arguments); return value; } } WebInspector.auditFormatters = new WebInspector.AuditFormatters(); ; WebInspector.AuditLauncherView = function(runnerCallback) { WebInspector.View.call(this); this._runnerCallback = runnerCallback; this._categoryIdPrefix = "audit-category-item-"; this._auditRunning = false; this.element.addStyleClass("audit-launcher-view"); this.element.addStyleClass("panel-enabler-view"); this._contentElement = document.createElement("div"); this._contentElement.className = "audit-launcher-view-content"; this.element.appendChild(this._contentElement); this._boundCategoryClickListener = this._categoryClicked.bind(this); this._resetResourceCount(); this._sortedCategories = []; this._headerElement = document.createElement("h1"); this._headerElement.className = "no-audits"; this._headerElement.textContent = WebInspector.UIString("No audits to run"); this._contentElement.appendChild(this._headerElement); WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestStarted, this._onRequestStarted, this); WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestFinished, this._onRequestFinished, this); var defaultSelectedAuditCategory = {}; defaultSelectedAuditCategory[WebInspector.AuditLauncherView.AllCategoriesKey] = true; this._selectedCategoriesSetting = WebInspector.settings.createSetting("selectedAuditCategories", defaultSelectedAuditCategory); } WebInspector.AuditLauncherView.AllCategoriesKey = "__AllCategories"; WebInspector.AuditLauncherView.prototype = { _resetResourceCount: function() { this._loadedResources = 0; this._totalResources = 0; }, _onRequestStarted: function(event) { var request = (event.data); if (request.type === WebInspector.resourceTypes.WebSocket) return; ++this._totalResources; this._updateResourceProgress(); }, _onRequestFinished: function(event) { var request = (event.data); if (request.type === WebInspector.resourceTypes.WebSocket) return; ++this._loadedResources; this._updateResourceProgress(); }, addCategory: function(category) { if (!this._sortedCategories.length) this._createLauncherUI(); var selectedCategories = this._selectedCategoriesSetting.get(); var categoryElement = this._createCategoryElement(category.displayName, category.id); category._checkboxElement = categoryElement.firstChild; if (this._selectAllCheckboxElement.checked || selectedCategories[category.displayName]) { category._checkboxElement.checked = true; ++this._currentCategoriesCount; } function compareCategories(a, b) { var aTitle = a.displayName || ""; var bTitle = b.displayName || ""; return aTitle.localeCompare(bTitle); } var insertBefore = insertionIndexForObjectInListSortedByFunction(category, this._sortedCategories, compareCategories); this._categoriesElement.insertBefore(categoryElement, this._categoriesElement.children[insertBefore]); this._sortedCategories.splice(insertBefore, 0, category); this._selectedCategoriesUpdated(); }, _setAuditRunning: function(auditRunning) { if (this._auditRunning === auditRunning) return; this._auditRunning = auditRunning; this._updateButton(); this._toggleUIComponents(this._auditRunning); if (this._auditRunning) this._startAudit(); else this._stopAudit(); }, _startAudit: function() { var catIds = []; for (var category = 0; category < this._sortedCategories.length; ++category) { if (this._sortedCategories[category]._checkboxElement.checked) catIds.push(this._sortedCategories[category].id); } this._resetResourceCount(); this._progressIndicator = new WebInspector.ProgressIndicator(); this._buttonContainerElement.appendChild(this._progressIndicator.element); this._displayResourceLoadingProgress = true; function onAuditStarted() { this._displayResourceLoadingProgress = false; } this._runnerCallback(catIds, this._progressIndicator, this._auditPresentStateElement.checked, onAuditStarted.bind(this), this._setAuditRunning.bind(this, false)); }, _stopAudit: function() { this._displayResourceLoadingProgress = false; this._progressIndicator.cancel(); this._progressIndicator.done(); delete this._progressIndicator; }, _toggleUIComponents: function(disable) { this._selectAllCheckboxElement.disabled = disable; this._categoriesElement.disabled = disable; this._auditPresentStateElement.disabled = disable; this._auditReloadedStateElement.disabled = disable; }, _launchButtonClicked: function(event) { this._setAuditRunning(!this._auditRunning); }, _selectAllClicked: function(checkCategories, userGesture) { var childNodes = this._categoriesElement.childNodes; for (var i = 0, length = childNodes.length; i < length; ++i) childNodes[i].firstChild.checked = checkCategories; this._currentCategoriesCount = checkCategories ? this._sortedCategories.length : 0; this._selectedCategoriesUpdated(userGesture); }, _categoryClicked: function(event) { this._currentCategoriesCount += event.target.checked ? 1 : -1; this._selectAllCheckboxElement.checked = this._currentCategoriesCount === this._sortedCategories.length; this._selectedCategoriesUpdated(true); }, _createCategoryElement: function(title, id) { var labelElement = document.createElement("label"); labelElement.id = this._categoryIdPrefix + id; var element = document.createElement("input"); element.type = "checkbox"; if (id !== "") element.addEventListener("click", this._boundCategoryClickListener, false); labelElement.appendChild(element); labelElement.appendChild(document.createTextNode(title)); labelElement.__displayName = title; return labelElement; }, _createLauncherUI: function() { this._headerElement = document.createElement("h1"); this._headerElement.textContent = WebInspector.UIString("Select audits to run"); for (var child = 0; child < this._contentElement.children.length; ++child) this._contentElement.removeChild(this._contentElement.children[child]); this._contentElement.appendChild(this._headerElement); function handleSelectAllClick(event) { this._selectAllClicked(event.target.checked, true); } var categoryElement = this._createCategoryElement(WebInspector.UIString("Select All"), ""); categoryElement.id = "audit-launcher-selectall"; this._selectAllCheckboxElement = categoryElement.firstChild; this._selectAllCheckboxElement.checked = this._selectedCategoriesSetting.get()[WebInspector.AuditLauncherView.AllCategoriesKey]; this._selectAllCheckboxElement.addEventListener("click", handleSelectAllClick.bind(this), false); this._contentElement.appendChild(categoryElement); this._categoriesElement = this._contentElement.createChild("fieldset", "audit-categories-container"); this._currentCategoriesCount = 0; this._contentElement.createChild("div", "flexible-space"); this._buttonContainerElement = this._contentElement.createChild("div", "button-container"); var labelElement = this._buttonContainerElement.createChild("label"); this._auditPresentStateElement = labelElement.createChild("input"); this._auditPresentStateElement.name = "audit-mode"; this._auditPresentStateElement.type = "radio"; this._auditPresentStateElement.checked = true; this._auditPresentStateLabelElement = document.createTextNode(WebInspector.UIString("Audit Present State")); labelElement.appendChild(this._auditPresentStateLabelElement); labelElement = this._buttonContainerElement.createChild("label"); this._auditReloadedStateElement = labelElement.createChild("input"); this._auditReloadedStateElement.name = "audit-mode"; this._auditReloadedStateElement.type = "radio"; labelElement.appendChild(document.createTextNode("Reload Page and Audit on Load")); this._launchButton = this._buttonContainerElement.createChild("button"); this._launchButton.textContent = WebInspector.UIString("Run"); this._launchButton.addEventListener("click", this._launchButtonClicked.bind(this), false); this._selectAllClicked(this._selectAllCheckboxElement.checked); }, _updateResourceProgress: function() { if (this._displayResourceLoadingProgress) this._progressIndicator.setTitle(WebInspector.UIString("Loading (%d of %d)", this._loadedResources, this._totalResources)); }, _selectedCategoriesUpdated: function(userGesture) { var selectedCategories = userGesture ? {} : this._selectedCategoriesSetting.get(); var childNodes = this._categoriesElement.childNodes; for (var i = 0, length = childNodes.length; i < length; ++i) selectedCategories[childNodes[i].__displayName] = childNodes[i].firstChild.checked; selectedCategories[WebInspector.AuditLauncherView.AllCategoriesKey] = this._selectAllCheckboxElement.checked; this._selectedCategoriesSetting.set(selectedCategories); this._updateButton(); }, _updateButton: function() { this._launchButton.textContent = this._auditRunning ? WebInspector.UIString("Stop") : WebInspector.UIString("Run"); this._launchButton.disabled = !this._currentCategoriesCount; }, __proto__: WebInspector.View.prototype } ; WebInspector.AuditResultView = function(categoryResults) { WebInspector.View.call(this); this.element.className = "audit-result-view"; function categorySorter(a, b) { return (a.title || "").localeCompare(b.title || ""); } categoryResults.sort(categorySorter); for (var i = 0; i < categoryResults.length; ++i) this.element.appendChild(new WebInspector.AuditCategoryResultPane(categoryResults[i]).element); } WebInspector.AuditResultView.prototype = { __proto__: WebInspector.View.prototype } WebInspector.AuditCategoryResultPane = function(categoryResult) { WebInspector.SidebarPane.call(this, categoryResult.title); var treeOutlineElement = document.createElement("ol"); this.bodyElement.addStyleClass("audit-result-tree"); this.bodyElement.appendChild(treeOutlineElement); this._treeOutline = new TreeOutline(treeOutlineElement); this._treeOutline.expandTreeElementsWhenArrowing = true; function ruleSorter(a, b) { var result = WebInspector.AuditRule.SeverityOrder[a.severity || 0] - WebInspector.AuditRule.SeverityOrder[b.severity || 0]; if (!result) result = (a.value || "").localeCompare(b.value || ""); return result; } categoryResult.ruleResults.sort(ruleSorter); for (var i = 0; i < categoryResult.ruleResults.length; ++i) { var ruleResult = categoryResult.ruleResults[i]; var treeElement = this._appendResult(this._treeOutline, ruleResult); treeElement.listItemElement.addStyleClass("audit-result"); if (ruleResult.severity) { var severityElement = document.createElement("img"); severityElement.className = "severity-" + ruleResult.severity; treeElement.listItemElement.appendChild(severityElement); } } this.expand(); } WebInspector.AuditCategoryResultPane.prototype = { _appendResult: function(parentTreeElement, result) { var title = ""; if (typeof result.value === "string") { title = result.value; if (result.violationCount) title = String.sprintf("%s (%d)", title, result.violationCount); } var treeElement = new TreeElement(null, null, !!result.children); treeElement.title = title; parentTreeElement.appendChild(treeElement); if (result.className) treeElement.listItemElement.addStyleClass(result.className); if (typeof result.value !== "string") treeElement.listItemElement.appendChild(WebInspector.auditFormatters.apply(result.value)); if (result.children) { for (var i = 0; i < result.children.length; ++i) this._appendResult(treeElement, result.children[i]); } if (result.expanded) { treeElement.listItemElement.removeStyleClass("parent"); treeElement.listItemElement.addStyleClass("parent-expanded"); treeElement.expand(); } return treeElement; }, __proto__: WebInspector.SidebarPane.prototype } ; WebInspector.AuditRules.IPAddressRegexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; WebInspector.AuditRules.CacheableResponseCodes = { 200: true, 203: true, 206: true, 300: true, 301: true, 410: true, 304: true } WebInspector.AuditRules.getDomainToResourcesMap = function(requests, types, needFullResources) { var domainToResourcesMap = {}; for (var i = 0, size = requests.length; i < size; ++i) { var request = requests[i]; if (types && types.indexOf(request.type) === -1) continue; var parsedURL = request.url.asParsedURL(); if (!parsedURL) continue; var domain = parsedURL.host; var domainResources = domainToResourcesMap[domain]; if (domainResources === undefined) { domainResources = []; domainToResourcesMap[domain] = domainResources; } domainResources.push(needFullResources ? request : request.url); } return domainToResourcesMap; } WebInspector.AuditRules.GzipRule = function() { WebInspector.AuditRule.call(this, "network-gzip", "Enable gzip compression"); } WebInspector.AuditRules.GzipRule.prototype = { doRun: function(requests, result, callback, progress) { var totalSavings = 0; var compressedSize = 0; var candidateSize = 0; var summary = result.addChild("", true); for (var i = 0, length = requests.length; i < length; ++i) { var request = requests[i]; if (request.statusCode === 304) continue; if (this._shouldCompress(request)) { var size = request.resourceSize; candidateSize += size; if (this._isCompressed(request)) { compressedSize += size; continue; } var savings = 2 * size / 3; totalSavings += savings; summary.addFormatted("%r could save ~%s", request.url, Number.bytesToString(savings)); result.violationCount++; } } if (!totalSavings) return callback(null); summary.value = String.sprintf("Compressing the following resources with gzip could reduce their transfer size by about two thirds (~%s):", Number.bytesToString(totalSavings)); callback(result); }, _isCompressed: function(request) { var encodingHeader = request.responseHeaderValue("Content-Encoding"); if (!encodingHeader) return false; return /\b(?:gzip|deflate)\b/.test(encodingHeader); }, _shouldCompress: function(request) { return request.type.isTextType() && request.parsedURL.host && request.resourceSize !== undefined && request.resourceSize > 150; }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.CombineExternalResourcesRule = function(id, name, type, resourceTypeName, allowedPerDomain) { WebInspector.AuditRule.call(this, id, name); this._type = type; this._resourceTypeName = resourceTypeName; this._allowedPerDomain = allowedPerDomain; } WebInspector.AuditRules.CombineExternalResourcesRule.prototype = { doRun: function(requests, result, callback, progress) { var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, [this._type], false); var penalizedResourceCount = 0; var summary = result.addChild("", true); for (var domain in domainToResourcesMap) { var domainResources = domainToResourcesMap[domain]; var extraResourceCount = domainResources.length - this._allowedPerDomain; if (extraResourceCount <= 0) continue; penalizedResourceCount += extraResourceCount - 1; summary.addChild(String.sprintf("%d %s resources served from %s.", domainResources.length, this._resourceTypeName, WebInspector.AuditRuleResult.resourceDomain(domain))); result.violationCount += domainResources.length; } if (!penalizedResourceCount) return callback(null); summary.value = "There are multiple resources served from same domain. Consider combining them into as few files as possible."; callback(result); }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.CombineJsResourcesRule = function(allowedPerDomain) { WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externaljs", "Combine external JavaScript", WebInspector.resourceTypes.Script, "JavaScript", allowedPerDomain); } WebInspector.AuditRules.CombineJsResourcesRule.prototype = { __proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype } WebInspector.AuditRules.CombineCssResourcesRule = function(allowedPerDomain) { WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externalcss", "Combine external CSS", WebInspector.resourceTypes.Stylesheet, "CSS", allowedPerDomain); } WebInspector.AuditRules.CombineCssResourcesRule.prototype = { __proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype } WebInspector.AuditRules.MinimizeDnsLookupsRule = function(hostCountThreshold) { WebInspector.AuditRule.call(this, "network-minimizelookups", "Minimize DNS lookups"); this._hostCountThreshold = hostCountThreshold; } WebInspector.AuditRules.MinimizeDnsLookupsRule.prototype = { doRun: function(requests, result, callback, progress) { var summary = result.addChild(""); var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, null, false); for (var domain in domainToResourcesMap) { if (domainToResourcesMap[domain].length > 1) continue; var parsedURL = domain.asParsedURL(); if (!parsedURL) continue; if (!parsedURL.host.search(WebInspector.AuditRules.IPAddressRegexp)) continue; summary.addSnippet(domain); result.violationCount++; } if (!summary.children || summary.children.length <= this._hostCountThreshold) return callback(null); summary.value = "The following domains only serve one resource each. If possible, avoid the extra DNS lookups by serving these resources from existing domains."; callback(result); }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.ParallelizeDownloadRule = function(optimalHostnameCount, minRequestThreshold, minBalanceThreshold) { WebInspector.AuditRule.call(this, "network-parallelizehosts", "Parallelize downloads across hostnames"); this._optimalHostnameCount = optimalHostnameCount; this._minRequestThreshold = minRequestThreshold; this._minBalanceThreshold = minBalanceThreshold; } WebInspector.AuditRules.ParallelizeDownloadRule.prototype = { doRun: function(requests, result, callback, progress) { function hostSorter(a, b) { var aCount = domainToResourcesMap[a].length; var bCount = domainToResourcesMap[b].length; return (aCount < bCount) ? 1 : (aCount == bCount) ? 0 : -1; } var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap( requests, [WebInspector.resourceTypes.Stylesheet, WebInspector.resourceTypes.Image], true); var hosts = []; for (var url in domainToResourcesMap) hosts.push(url); if (!hosts.length) return callback(null); hosts.sort(hostSorter); var optimalHostnameCount = this._optimalHostnameCount; if (hosts.length > optimalHostnameCount) hosts.splice(optimalHostnameCount); var busiestHostResourceCount = domainToResourcesMap[hosts[0]].length; var requestCountAboveThreshold = busiestHostResourceCount - this._minRequestThreshold; if (requestCountAboveThreshold <= 0) return callback(null); var avgResourcesPerHost = 0; for (var i = 0, size = hosts.length; i < size; ++i) avgResourcesPerHost += domainToResourcesMap[hosts[i]].length; avgResourcesPerHost /= optimalHostnameCount; avgResourcesPerHost = Math.max(avgResourcesPerHost, 1); var pctAboveAvg = (requestCountAboveThreshold / avgResourcesPerHost) - 1.0; var minBalanceThreshold = this._minBalanceThreshold; if (pctAboveAvg < minBalanceThreshold) return callback(null); var requestsOnBusiestHost = domainToResourcesMap[hosts[0]]; var entry = result.addChild(String.sprintf("This page makes %d parallelizable requests to %s. Increase download parallelization by distributing the following requests across multiple hostnames.", busiestHostResourceCount, hosts[0]), true); for (var i = 0; i < requestsOnBusiestHost.length; ++i) entry.addURL(requestsOnBusiestHost[i].url); result.violationCount = requestsOnBusiestHost.length; callback(result); }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.UnusedCssRule = function() { WebInspector.AuditRule.call(this, "page-unusedcss", "Remove unused CSS rules"); } WebInspector.AuditRules.UnusedCssRule.prototype = { doRun: function(requests, result, callback, progress) { var self = this; function evalCallback(styleSheets) { if (progress.isCanceled()) return; if (!styleSheets.length) return callback(null); var pseudoSelectorRegexp = /:hover|:link|:active|:visited|:focus|:before|:after/; var selectors = []; var testedSelectors = {}; for (var i = 0; i < styleSheets.length; ++i) { var styleSheet = styleSheets[i]; for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) { var selectorText = styleSheet.rules[curRule].selectorText; if (selectorText.match(pseudoSelectorRegexp) || testedSelectors[selectorText]) continue; selectors.push(selectorText); testedSelectors[selectorText] = 1; } } function selectorsCallback(callback, styleSheets, testedSelectors, foundSelectors) { if (progress.isCanceled()) return; var inlineBlockOrdinal = 0; var totalStylesheetSize = 0; var totalUnusedStylesheetSize = 0; var summary; for (var i = 0; i < styleSheets.length; ++i) { var styleSheet = styleSheets[i]; var stylesheetSize = 0; var unusedStylesheetSize = 0; var unusedRules = []; for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) { var rule = styleSheet.rules[curRule]; var textLength = (rule.selectorRange && rule.style.range && rule.style.range.end) ? rule.style.range.end - rule.selectorRange.start + 1 : 0; if (!textLength && rule.style.cssText) textLength = rule.style.cssText.length + rule.selectorText.length; stylesheetSize += textLength; if (!testedSelectors[rule.selectorText] || foundSelectors[rule.selectorText]) continue; unusedStylesheetSize += textLength; unusedRules.push(rule.selectorText); } totalStylesheetSize += stylesheetSize; totalUnusedStylesheetSize += unusedStylesheetSize; if (!unusedRules.length) continue; var resource = WebInspector.resourceForURL(styleSheet.sourceURL); var isInlineBlock = resource && resource.request && resource.request.type == WebInspector.resourceTypes.Document; var url = !isInlineBlock ? WebInspector.AuditRuleResult.linkifyDisplayName(styleSheet.sourceURL) : String.sprintf("Inline block #%d", ++inlineBlockOrdinal); var pctUnused = Math.round(100 * unusedStylesheetSize / stylesheetSize); if (!summary) summary = result.addChild("", true); var entry = summary.addFormatted("%s: %s (%d%) is not used by the current page.", url, Number.bytesToString(unusedStylesheetSize), pctUnused); for (var j = 0; j < unusedRules.length; ++j) entry.addSnippet(unusedRules[j]); result.violationCount += unusedRules.length; } if (!totalUnusedStylesheetSize) return callback(null); var totalUnusedPercent = Math.round(100 * totalUnusedStylesheetSize / totalStylesheetSize); summary.value = String.sprintf("%s (%d%) of CSS is not used by the current page.", Number.bytesToString(totalUnusedStylesheetSize), totalUnusedPercent); callback(result); } var foundSelectors = {}; function queryCallback(boundSelectorsCallback, selector, styleSheets, testedSelectors, nodeId) { if (nodeId) foundSelectors[selector] = true; if (boundSelectorsCallback) boundSelectorsCallback(foundSelectors); } function documentLoaded(selectors, document) { for (var i = 0; i < selectors.length; ++i) { if (progress.isCanceled()) return; WebInspector.domAgent.querySelector(document.id, selectors[i], queryCallback.bind(null, i === selectors.length - 1 ? selectorsCallback.bind(null, callback, styleSheets, testedSelectors) : null, selectors[i], styleSheets, testedSelectors)); } } WebInspector.domAgent.requestDocument(documentLoaded.bind(null, selectors)); } function styleSheetCallback(styleSheets, sourceURL, continuation, styleSheet) { if (progress.isCanceled()) return; if (styleSheet) { styleSheet.sourceURL = sourceURL; styleSheets.push(styleSheet); } if (continuation) continuation(styleSheets); } function allStylesCallback(error, styleSheetInfos) { if (progress.isCanceled()) return; if (error || !styleSheetInfos || !styleSheetInfos.length) return evalCallback([]); var styleSheets = []; for (var i = 0; i < styleSheetInfos.length; ++i) { var info = styleSheetInfos[i]; WebInspector.CSSStyleSheet.createForId(info.styleSheetId, styleSheetCallback.bind(null, styleSheets, info.sourceURL, i == styleSheetInfos.length - 1 ? evalCallback : null)); } } CSSAgent.getAllStyleSheets(allStylesCallback); }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.CacheControlRule = function(id, name) { WebInspector.AuditRule.call(this, id, name); } WebInspector.AuditRules.CacheControlRule.MillisPerMonth = 1000 * 60 * 60 * 24 * 30; WebInspector.AuditRules.CacheControlRule.prototype = { doRun: function(requests, result, callback, progress) { var cacheableAndNonCacheableResources = this._cacheableAndNonCacheableResources(requests); if (cacheableAndNonCacheableResources[0].length) this.runChecks(cacheableAndNonCacheableResources[0], result); this.handleNonCacheableResources(cacheableAndNonCacheableResources[1], result); callback(result); }, handleNonCacheableResources: function(requests, result) { }, _cacheableAndNonCacheableResources: function(requests) { var processedResources = [[], []]; for (var i = 0; i < requests.length; ++i) { var request = requests[i]; if (!this.isCacheableResource(request)) continue; if (this._isExplicitlyNonCacheable(request)) processedResources[1].push(request); else processedResources[0].push(request); } return processedResources; }, execCheck: function(messageText, requestCheckFunction, requests, result) { var requestCount = requests.length; var urls = []; for (var i = 0; i < requestCount; ++i) { if (requestCheckFunction.call(this, requests[i])) urls.push(requests[i].url); } if (urls.length) { var entry = result.addChild(messageText, true); entry.addURLs(urls); result.violationCount += urls.length; } }, freshnessLifetimeGreaterThan: function(request, timeMs) { var dateHeader = this.responseHeader(request, "Date"); if (!dateHeader) return false; var dateHeaderMs = Date.parse(dateHeader); if (isNaN(dateHeaderMs)) return false; var freshnessLifetimeMs; var maxAgeMatch = this.responseHeaderMatch(request, "Cache-Control", "max-age=(\\d+)"); if (maxAgeMatch) freshnessLifetimeMs = (maxAgeMatch[1]) ? 1000 * maxAgeMatch[1] : 0; else { var expiresHeader = this.responseHeader(request, "Expires"); if (expiresHeader) { var expDate = Date.parse(expiresHeader); if (!isNaN(expDate)) freshnessLifetimeMs = expDate - dateHeaderMs; } } return (isNaN(freshnessLifetimeMs)) ? false : freshnessLifetimeMs > timeMs; }, responseHeader: function(request, header) { return request.responseHeaderValue(header); }, hasResponseHeader: function(request, header) { return request.responseHeaderValue(header) !== undefined; }, isCompressible: function(request) { return request.type.isTextType(); }, isPubliclyCacheable: function(request) { if (this._isExplicitlyNonCacheable(request)) return false; if (this.responseHeaderMatch(request, "Cache-Control", "public")) return true; return request.url.indexOf("?") == -1 && !this.responseHeaderMatch(request, "Cache-Control", "private"); }, responseHeaderMatch: function(request, header, regexp) { return request.responseHeaderValue(header) ? request.responseHeaderValue(header).match(new RegExp(regexp, "im")) : undefined; }, hasExplicitExpiration: function(request) { return this.hasResponseHeader(request, "Date") && (this.hasResponseHeader(request, "Expires") || this.responseHeaderMatch(request, "Cache-Control", "max-age")); }, _isExplicitlyNonCacheable: function(request) { var hasExplicitExp = this.hasExplicitExpiration(request); return this.responseHeaderMatch(request, "Cache-Control", "(no-cache|no-store|must-revalidate)") || this.responseHeaderMatch(request, "Pragma", "no-cache") || (hasExplicitExp && !this.freshnessLifetimeGreaterThan(request, 0)) || (!hasExplicitExp && request.url && request.url.indexOf("?") >= 0) || (!hasExplicitExp && !this.isCacheableResource(request)); }, isCacheableResource: function(request) { return request.statusCode !== undefined && WebInspector.AuditRules.CacheableResponseCodes[request.statusCode]; }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.BrowserCacheControlRule = function() { WebInspector.AuditRules.CacheControlRule.call(this, "http-browsercache", "Leverage browser caching"); } WebInspector.AuditRules.BrowserCacheControlRule.prototype = { handleNonCacheableResources: function(requests, result) { if (requests.length) { var entry = result.addChild("The following resources are explicitly non-cacheable. Consider making them cacheable if possible:", true); result.violationCount += requests.length; for (var i = 0; i < requests.length; ++i) entry.addURL(requests[i].url); } }, runChecks: function(requests, result, callback) { this.execCheck("The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:", this._missingExpirationCheck, requests, result); this.execCheck("The following resources specify a \"Vary\" header that disables caching in most versions of Internet Explorer:", this._varyCheck, requests, result); this.execCheck("The following cacheable resources have a short freshness lifetime:", this._oneMonthExpirationCheck, requests, result); this.execCheck("To further improve cache hit rate, specify an expiration one year in the future for the following cacheable resources:", this._oneYearExpirationCheck, requests, result); }, _missingExpirationCheck: function(request) { return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.hasExplicitExpiration(request); }, _varyCheck: function(request) { var varyHeader = this.responseHeader(request, "Vary"); if (varyHeader) { varyHeader = varyHeader.replace(/User-Agent/gi, ""); varyHeader = varyHeader.replace(/Accept-Encoding/gi, ""); varyHeader = varyHeader.replace(/[, ]*/g, ""); } return varyHeader && varyHeader.length && this.isCacheableResource(request) && this.freshnessLifetimeGreaterThan(request, 0); }, _oneMonthExpirationCheck: function(request) { return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth) && this.freshnessLifetimeGreaterThan(request, 0); }, _oneYearExpirationCheck: function(request) { return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.freshnessLifetimeGreaterThan(request, 11 * WebInspector.AuditRules.CacheControlRule.MillisPerMonth) && this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth); }, __proto__: WebInspector.AuditRules.CacheControlRule.prototype } WebInspector.AuditRules.ProxyCacheControlRule = function() { WebInspector.AuditRules.CacheControlRule.call(this, "http-proxycache", "Leverage proxy caching"); } WebInspector.AuditRules.ProxyCacheControlRule.prototype = { runChecks: function(requests, result, callback) { this.execCheck("Resources with a \"?\" in the URL are not cached by most proxy caching servers:", this._questionMarkCheck, requests, result); this.execCheck("Consider adding a \"Cache-Control: public\" header to the following resources:", this._publicCachingCheck, requests, result); this.execCheck("The following publicly cacheable resources contain a Set-Cookie header. This security vulnerability can cause cookies to be shared by multiple users.", this._setCookieCacheableCheck, requests, result); }, _questionMarkCheck: function(request) { return request.url.indexOf("?") >= 0 && !this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request); }, _publicCachingCheck: function(request) { return this.isCacheableResource(request) && !this.isCompressible(request) && !this.responseHeaderMatch(request, "Cache-Control", "public") && !this.hasResponseHeader(request, "Set-Cookie"); }, _setCookieCacheableCheck: function(request) { return this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request); }, __proto__: WebInspector.AuditRules.CacheControlRule.prototype } WebInspector.AuditRules.ImageDimensionsRule = function() { WebInspector.AuditRule.call(this, "page-imagedims", "Specify image dimensions"); } WebInspector.AuditRules.ImageDimensionsRule.prototype = { doRun: function(requests, result, callback, progress) { var urlToNoDimensionCount = {}; function doneCallback() { for (var url in urlToNoDimensionCount) { var entry = entry || result.addChild("A width and height should be specified for all images in order to speed up page display. The following image(s) are missing a width and/or height:", true); var format = "%r"; if (urlToNoDimensionCount[url] > 1) format += " (%d uses)"; entry.addFormatted(format, url, urlToNoDimensionCount[url]); result.violationCount++; } callback(entry ? result : null); } function imageStylesReady(imageId, styles, isLastStyle, computedStyle) { if (progress.isCanceled()) return; const node = WebInspector.domAgent.nodeForId(imageId); var src = node.getAttribute("src"); if (!src.asParsedURL()) { for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) { if (frameOwnerCandidate.baseURL) { var completeSrc = WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL, src); break; } } } if (completeSrc) src = completeSrc; if (computedStyle.getPropertyValue("position") === "absolute") { if (isLastStyle) doneCallback(); return; } if (styles.attributesStyle) { var widthFound = !!styles.attributesStyle.getLiveProperty("width"); var heightFound = !!styles.attributesStyle.getLiveProperty("height"); } var inlineStyle = styles.inlineStyle; if (inlineStyle) { if (inlineStyle.getPropertyValue("width") !== "") widthFound = true; if (inlineStyle.getPropertyValue("height") !== "") heightFound = true; } for (var i = styles.matchedCSSRules.length - 1; i >= 0 && !(widthFound && heightFound); --i) { var style = styles.matchedCSSRules[i].style; if (style.getPropertyValue("width") !== "") widthFound = true; if (style.getPropertyValue("height") !== "") heightFound = true; } if (!widthFound || !heightFound) { if (src in urlToNoDimensionCount) ++urlToNoDimensionCount[src]; else urlToNoDimensionCount[src] = 1; } if (isLastStyle) doneCallback(); } function getStyles(nodeIds) { if (progress.isCanceled()) return; var targetResult = {}; function inlineCallback(inlineStyle, attributesStyle) { targetResult.inlineStyle = inlineStyle; targetResult.attributesStyle = attributesStyle; } function matchedCallback(result) { if (result) targetResult.matchedCSSRules = result.matchedCSSRules; } if (!nodeIds || !nodeIds.length) doneCallback(); for (var i = 0; nodeIds && i < nodeIds.length; ++i) { WebInspector.cssModel.getMatchedStylesAsync(nodeIds[i], false, false, matchedCallback); WebInspector.cssModel.getInlineStylesAsync(nodeIds[i], inlineCallback); WebInspector.cssModel.getComputedStyleAsync(nodeIds[i], imageStylesReady.bind(null, nodeIds[i], targetResult, i === nodeIds.length - 1)); } } function onDocumentAvailable(root) { if (progress.isCanceled()) return; WebInspector.domAgent.querySelectorAll(root.id, "img[src]", getStyles); } if (progress.isCanceled()) return; WebInspector.domAgent.requestDocument(onDocumentAvailable); }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.CssInHeadRule = function() { WebInspector.AuditRule.call(this, "page-cssinhead", "Put CSS in the document head"); } WebInspector.AuditRules.CssInHeadRule.prototype = { doRun: function(requests, result, callback, progress) { function evalCallback(evalResult) { if (progress.isCanceled()) return; if (!evalResult) return callback(null); var summary = result.addChild(""); var outputMessages = []; for (var url in evalResult) { var urlViolations = evalResult[url]; if (urlViolations[0]) { result.addFormatted("%s style block(s) in the %r body should be moved to the document head.", urlViolations[0], url); result.violationCount += urlViolations[0]; } for (var i = 0; i < urlViolations[1].length; ++i) result.addFormatted("Link node %r should be moved to the document head in %r", urlViolations[1][i], url); result.violationCount += urlViolations[1].length; } summary.value = String.sprintf("CSS in the document body adversely impacts rendering performance."); callback(result); } function externalStylesheetsReceived(root, inlineStyleNodeIds, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; var externalStylesheetNodeIds = nodeIds; var result = null; if (inlineStyleNodeIds.length || externalStylesheetNodeIds.length) { var urlToViolationsArray = {}; var externalStylesheetHrefs = []; for (var j = 0; j < externalStylesheetNodeIds.length; ++j) { var linkNode = WebInspector.domAgent.nodeForId(externalStylesheetNodeIds[j]); var completeHref = WebInspector.ParsedURL.completeURL(linkNode.ownerDocument.baseURL, linkNode.getAttribute("href")); externalStylesheetHrefs.push(completeHref || "<empty>"); } urlToViolationsArray[root.documentURL] = [inlineStyleNodeIds.length, externalStylesheetHrefs]; result = urlToViolationsArray; } evalCallback(result); } function inlineStylesReceived(root, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; WebInspector.domAgent.querySelectorAll(root.id, "body link[rel~='stylesheet'][href]", externalStylesheetsReceived.bind(null, root, nodeIds)); } function onDocumentAvailable(root) { if (progress.isCanceled()) return; WebInspector.domAgent.querySelectorAll(root.id, "body style", inlineStylesReceived.bind(null, root)); } WebInspector.domAgent.requestDocument(onDocumentAvailable); }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.StylesScriptsOrderRule = function() { WebInspector.AuditRule.call(this, "page-stylescriptorder", "Optimize the order of styles and scripts"); } WebInspector.AuditRules.StylesScriptsOrderRule.prototype = { doRun: function(requests, result, callback, progress) { function evalCallback(resultValue) { if (progress.isCanceled()) return; if (!resultValue) return callback(null); var lateCssUrls = resultValue[0]; var cssBeforeInlineCount = resultValue[1]; var entry = result.addChild("The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, always include external CSS before external JavaScript.", true); entry.addURLs(lateCssUrls); result.violationCount += lateCssUrls.length; if (cssBeforeInlineCount) { result.addChild(String.sprintf(" %d inline script block%s found in the head between an external CSS file and another resource. To allow parallel downloading, move the inline script before the external CSS file, or after the next resource.", cssBeforeInlineCount, cssBeforeInlineCount > 1 ? "s were" : " was")); result.violationCount += cssBeforeInlineCount; } callback(result); } function cssBeforeInlineReceived(lateStyleIds, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; var cssBeforeInlineCount = nodeIds.length; var result = null; if (lateStyleIds.length || cssBeforeInlineCount) { var lateStyleUrls = []; for (var i = 0; i < lateStyleIds.length; ++i) { var lateStyleNode = WebInspector.domAgent.nodeForId(lateStyleIds[i]); var completeHref = WebInspector.ParsedURL.completeURL(lateStyleNode.ownerDocument.baseURL, lateStyleNode.getAttribute("href")); lateStyleUrls.push(completeHref || "<empty>"); } result = [ lateStyleUrls, cssBeforeInlineCount ]; } evalCallback(result); } function lateStylesReceived(root, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; WebInspector.domAgent.querySelectorAll(root.id, "head link[rel~='stylesheet'][href] ~ script:not([src])", cssBeforeInlineReceived.bind(null, nodeIds)); } function onDocumentAvailable(root) { if (progress.isCanceled()) return; WebInspector.domAgent.querySelectorAll(root.id, "head script[src] ~ link[rel~='stylesheet'][href]", lateStylesReceived.bind(null, root)); } WebInspector.domAgent.requestDocument(onDocumentAvailable); }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.CSSRuleBase = function(id, name) { WebInspector.AuditRule.call(this, id, name); } WebInspector.AuditRules.CSSRuleBase.prototype = { doRun: function(requests, result, callback, progress) { CSSAgent.getAllStyleSheets(sheetsCallback.bind(this)); function sheetsCallback(error, headers) { if (error) return callback(null); for (var i = 0; i < headers.length; ++i) { var header = headers[i]; if (header.disabled) continue; this._visitStyleSheet(header.styleSheetId, i === headers.length - 1 ? finishedCallback : null, result, progress); } } function finishedCallback() { callback(result); } }, _visitStyleSheet: function(styleSheetId, callback, result, progress) { WebInspector.CSSStyleSheet.createForId(styleSheetId, sheetCallback.bind(this)); function sheetCallback(styleSheet) { if (progress.isCanceled()) return; if (!styleSheet) { if (callback) callback(); return; } this.visitStyleSheet(styleSheet, result); for (var i = 0; i < styleSheet.rules.length; ++i) this._visitRule(styleSheet, styleSheet.rules[i], result); this.didVisitStyleSheet(styleSheet, result); if (callback) callback(); } }, _visitRule: function(styleSheet, rule, result) { this.visitRule(styleSheet, rule, result); var allProperties = rule.style.allProperties; for (var i = 0; i < allProperties.length; ++i) this.visitProperty(styleSheet, allProperties[i], result); this.didVisitRule(styleSheet, rule, result); }, visitStyleSheet: function(styleSheet, result) { }, didVisitStyleSheet: function(styleSheet, result) { }, visitRule: function(styleSheet, rule, result) { }, didVisitRule: function(styleSheet, rule, result) { }, visitProperty: function(styleSheet, property, result) { }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.VendorPrefixedCSSProperties = function() { WebInspector.AuditRules.CSSRuleBase.call(this, "page-vendorprefixedcss", "Use normal CSS property names instead of vendor-prefixed ones"); this._webkitPrefix = "-webkit-"; } WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties = [ "background-clip", "background-origin", "background-size", "border-radius", "border-bottom-left-radius", "border-bottom-right-radius", "border-top-left-radius", "border-top-right-radius", "box-shadow", "box-sizing", "opacity", "text-shadow" ].keySet(); WebInspector.AuditRules.VendorPrefixedCSSProperties.prototype = { didVisitStyleSheet: function(styleSheet) { delete this._styleSheetResult; }, visitRule: function(rule) { this._mentionedProperties = {}; }, didVisitRule: function() { delete this._ruleResult; delete this._mentionedProperties; }, visitProperty: function(styleSheet, property, result) { if (!property.name.startsWith(this._webkitPrefix)) return; var normalPropertyName = property.name.substring(this._webkitPrefix.length).toLowerCase(); if (WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties[normalPropertyName] && !this._mentionedProperties[normalPropertyName]) { var style = property.ownerStyle; var liveProperty = style.getLiveProperty(normalPropertyName); if (liveProperty && !liveProperty.styleBased) return; var rule = style.parentRule; this._mentionedProperties[normalPropertyName] = true; if (!this._styleSheetResult) this._styleSheetResult = result.addChild(rule.sourceURL ? WebInspector.linkifyResourceAsNode(rule.sourceURL) : "<unknown>"); if (!this._ruleResult) { var anchor = WebInspector.linkifyURLAsNode(rule.sourceURL, rule.selectorText); anchor.preferredPanel = "resources"; anchor.lineNumber = rule.sourceLine; this._ruleResult = this._styleSheetResult.addChild(anchor); } ++result.violationCount; this._ruleResult.addSnippet(String.sprintf("\"" + this._webkitPrefix + "%s\" is used, but \"%s\" is supported.", normalPropertyName, normalPropertyName)); } }, __proto__: WebInspector.AuditRules.CSSRuleBase.prototype } WebInspector.AuditRules.CookieRuleBase = function(id, name) { WebInspector.AuditRule.call(this, id, name); } WebInspector.AuditRules.CookieRuleBase.prototype = { doRun: function(requests, result, callback, progress) { var self = this; function resultCallback(receivedCookies, isAdvanced) { if (progress.isCanceled()) return; self.processCookies(isAdvanced ? receivedCookies : [], requests, result); callback(result); } WebInspector.Cookies.getCookiesAsync(resultCallback); }, mapResourceCookies: function(requestsByDomain, allCookies, callback) { for (var i = 0; i < allCookies.length; ++i) { for (var requestDomain in requestsByDomain) { if (WebInspector.Cookies.cookieDomainMatchesResourceDomain(allCookies[i].domain(), requestDomain)) this._callbackForResourceCookiePairs(requestsByDomain[requestDomain], allCookies[i], callback); } } }, _callbackForResourceCookiePairs: function(requests, cookie, callback) { if (!requests) return; for (var i = 0; i < requests.length; ++i) { if (WebInspector.Cookies.cookieMatchesResourceURL(cookie, requests[i].url)) callback(requests[i], cookie); } }, __proto__: WebInspector.AuditRule.prototype } WebInspector.AuditRules.CookieSizeRule = function(avgBytesThreshold) { WebInspector.AuditRules.CookieRuleBase.call(this, "http-cookiesize", "Minimize cookie size"); this._avgBytesThreshold = avgBytesThreshold; this._maxBytesThreshold = 1000; } WebInspector.AuditRules.CookieSizeRule.prototype = { _average: function(cookieArray) { var total = 0; for (var i = 0; i < cookieArray.length; ++i) total += cookieArray[i].size(); return cookieArray.length ? Math.round(total / cookieArray.length) : 0; }, _max: function(cookieArray) { var result = 0; for (var i = 0; i < cookieArray.length; ++i) result = Math.max(cookieArray[i].size(), result); return result; }, processCookies: function(allCookies, requests, result) { function maxSizeSorter(a, b) { return b.maxCookieSize - a.maxCookieSize; } function avgSizeSorter(a, b) { return b.avgCookieSize - a.avgCookieSize; } var cookiesPerResourceDomain = {}; function collectorCallback(request, cookie) { var cookies = cookiesPerResourceDomain[request.parsedURL.host]; if (!cookies) { cookies = []; cookiesPerResourceDomain[request.parsedURL.host] = cookies; } cookies.push(cookie); } if (!allCookies.length) return; var sortedCookieSizes = []; var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, null, true); var matchingResourceData = {}; this.mapResourceCookies(domainToResourcesMap, allCookies, collectorCallback.bind(this)); for (var requestDomain in cookiesPerResourceDomain) { var cookies = cookiesPerResourceDomain[requestDomain]; sortedCookieSizes.push({ domain: requestDomain, avgCookieSize: this._average(cookies), maxCookieSize: this._max(cookies) }); } var avgAllCookiesSize = this._average(allCookies); var hugeCookieDomains = []; sortedCookieSizes.sort(maxSizeSorter); for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) { var maxCookieSize = sortedCookieSizes[i].maxCookieSize; if (maxCookieSize > this._maxBytesThreshold) hugeCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(sortedCookieSizes[i].domain) + ": " + Number.bytesToString(maxCookieSize)); } var bigAvgCookieDomains = []; sortedCookieSizes.sort(avgSizeSorter); for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) { var domain = sortedCookieSizes[i].domain; var avgCookieSize = sortedCookieSizes[i].avgCookieSize; if (avgCookieSize > this._avgBytesThreshold && avgCookieSize < this._maxBytesThreshold) bigAvgCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(domain) + ": " + Number.bytesToString(avgCookieSize)); } result.addChild(String.sprintf("The average cookie size for all requests on this page is %s", Number.bytesToString(avgAllCookiesSize))); var message; if (hugeCookieDomains.length) { var entry = result.addChild("The following domains have a cookie size in excess of 1KB. This is harmful because requests with cookies larger than 1KB typically cannot fit into a single network packet.", true); entry.addURLs(hugeCookieDomains); result.violationCount += hugeCookieDomains.length; } if (bigAvgCookieDomains.length) { var entry = result.addChild(String.sprintf("The following domains have an average cookie size in excess of %d bytes. Reducing the size of cookies for these domains can reduce the time it takes to send requests.", this._avgBytesThreshold), true); entry.addURLs(bigAvgCookieDomains); result.violationCount += bigAvgCookieDomains.length; } }, __proto__: WebInspector.AuditRules.CookieRuleBase.prototype } WebInspector.AuditRules.StaticCookielessRule = function(minResources) { WebInspector.AuditRules.CookieRuleBase.call(this, "http-staticcookieless", "Serve static content from a cookieless domain"); this._minResources = minResources; } WebInspector.AuditRules.StaticCookielessRule.prototype = { processCookies: function(allCookies, requests, result) { var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, [WebInspector.resourceTypes.Stylesheet, WebInspector.resourceTypes.Image], true); var totalStaticResources = 0; for (var domain in domainToResourcesMap) totalStaticResources += domainToResourcesMap[domain].length; if (totalStaticResources < this._minResources) return; var matchingResourceData = {}; this.mapResourceCookies(domainToResourcesMap, allCookies, this._collectorCallback.bind(this, matchingResourceData)); var badUrls = []; var cookieBytes = 0; for (var url in matchingResourceData) { badUrls.push(url); cookieBytes += matchingResourceData[url] } if (badUrls.length < this._minResources) return; var entry = result.addChild(String.sprintf("%s of cookies were sent with the following static resources. Serve these static resources from a domain that does not set cookies:", Number.bytesToString(cookieBytes)), true); entry.addURLs(badUrls); result.violationCount = badUrls.length; }, _collectorCallback: function(matchingResourceData, request, cookie) { matchingResourceData[request.url] = (matchingResourceData[request.url] || 0) + cookie.size(); }, __proto__: WebInspector.AuditRules.CookieRuleBase.prototype } ;
JavaScript
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function($) { var types = ['DOMMouseScroll', 'mousewheel']; if ($.event.fixHooks) { for ( var i=types.length; i; ) { $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i=types.length; i; ) { this.addEventListener( types[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i=types.length; i; ) { this.removeEventListener( types[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } // New school multidimensional scroll (touchpads) deltas deltaY = delta; // Gecko if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = -1*delta; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } })(jQuery); /** * @version 2.0 * @package jquery * @subpackage lofslidernews * @copyright Copyright (C) JAN 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved. * @website http://landofcoder.com * @license This plugin is dual-licensed under the GNU General Public License and the MIT License */ // JavaScript Document (function($) { $.fn.lofJSidernews = function( settings ) { return this.each(function() { // get instance of the lofSiderNew. new $.lofSidernews( this, settings ); }); } $.lofSidernews = function( obj, settings ){ this.settings = { direction : '', mainItemSelector : 'li', navInnerSelector : 'ul', navSelector : 'li' , navigatorEvent : 'click'/* click|mouseenter */, wapperSelector: '.sliders-wrap-inner', interval : 5000, auto : false, // whether to automatic play the slideshow maxItemDisplay : 3, startItem : 0, navPosition : 'vertical',/* values: horizontal|vertical*/ navigatorHeight : 100, navigatorWidth : 310, duration : 600, navItemsSelector : '.navigator-wrap-inner li', navOuterSelector : '.navigator-wrapper' , isPreloaded : true, easing : 'easeInOutQuad', onPlaySlider:function(obj, slider){}, onComplete:function(slider, index){ } } $.extend( this.settings, settings ||{} ); this.nextNo = null; this.previousNo = null; this.maxWidth = this.settings.mainWidth || 684; this.wrapper = $( obj ).find( this.settings.wapperSelector ); var wrapOuter = $('<div class="sliders-wrapper"></div>').width( this.maxWidth ); this.wrapper.wrap( wrapOuter ); this.slides = this.wrapper.find( this.settings.mainItemSelector ); if( !this.wrapper.length || !this.slides.length ) return ; // set width of wapper if( this.settings.maxItemDisplay > this.slides.length ){ this.settings.maxItemDisplay = this.slides.length; } this.currentNo = isNaN(this.settings.startItem)||this.settings.startItem > this.slides.length?0:this.settings.startItem; this.navigatorOuter = $( obj ).find( this.settings.navOuterSelector ); this.navigatorItems = $( obj ).find( this.settings.navItemsSelector ) ; this.navigatorInner = this.navigatorOuter.find( this.settings.navInnerSelector ); // if use automactic calculate width of navigator if( this.settings.navigatorHeight == null || this.settings.navigatorWidth == null ){ this.settings.navigatorHeight = this.navigatorItems.eq(0).outerWidth(true); this.settings.navigatorWidth = this.navigatorItems.eq(0).outerHeight(true); } if( this.settings.navPosition == 'horizontal' ){ this.navigatorInner.width( this.slides.length * this.settings.navigatorWidth ); this.navigatorOuter.width( this.settings.maxItemDisplay * this.settings.navigatorWidth ); this.navigatorOuter.height( this.settings.navigatorHeight ); } else { this.navigatorInner.height( this.slides.length * this.settings.navigatorHeight ); this.navigatorOuter.height( this.settings.maxItemDisplay * this.settings.navigatorHeight ); this.navigatorOuter.width( this.settings.navigatorWidth ); } this.slides.width( this.settings.mainWidth ); this.navigratorStep = this.__getPositionMode( this.settings.navPosition ); this.directionMode = this.__getDirectionMode(); if( this.settings.direction == 'opacity') { this.wrapper.addClass( 'lof-opacity' ); $(this.slides).css({'opacity':0,'z-index':1}).eq(this.currentNo).css({'opacity':1,'z-index':3}); } else { this.wrapper.css({'left':'-'+this.currentNo*this.maxSize+'px', 'width':( this.maxWidth ) * this.slides.length } ); } if( this.settings.isPreloaded ) { this.preLoadImage( this.onComplete ); } else { this.onComplete(); } $buttonControl = $( ".button-control", obj); if( this.settings.auto ){ $buttonControl.addClass("action-stop"); } else { $buttonControl.addClass("action-start"); } var self = this; $( obj ).hover(function(){ self.stop(); $buttonControl.addClass("action-start").removeClass("action-stop").addClass("hover-stop"); }, function(){ if( $buttonControl.hasClass("hover-stop") ){ if( self.settings.auto ){ $buttonControl.removeClass("action-start").removeClass("hover-stop").addClass("action-stop"); self.play( self.settings.interval,'next', true ); } } } ); $buttonControl.click( function() { if( $buttonControl.hasClass("action-start") ){ self.settings.auto =true; self.play( self.settings.interval,'next', true ); $buttonControl.removeClass("action-start").addClass("action-stop"); } else{ self.settings.auto =false; self.stop(); $buttonControl.addClass("action-start").removeClass("action-stop"); } } ); } $.lofSidernews.fn = $.lofSidernews.prototype; $.lofSidernews.fn.extend = $.lofSidernews.extend = $.extend; $.lofSidernews.fn.extend({ startUp:function( obj, wrapper ) { seft = this; this.navigatorItems.each( function(index, item ){ $(item).bind( seft.settings.navigatorEvent,( function(){ seft.jumping( index, true ); seft.setNavActive( index, item ); } )); $(item).css( {'height': seft.settings.navigatorHeight, 'width': seft.settings.navigatorWidth} ); }) this.registerWheelHandler( this.navigatorOuter, this ); this.setNavActive( this.currentNo ); this.settings.onComplete( this.slides.eq(this.currentNo ),this.currentNo ); if( this.settings.buttons && typeof (this.settings.buttons) == "object" ){ this.registerButtonsControl( 'click', this.settings.buttons, this ); } if( this.settings.auto ) this.play( this.settings.interval,'next', true ); return this; }, onComplete:function(){ setTimeout( function(){ $('.preload').fadeOut( 900, function(){ $('.preload').remove(); } ); }, 400 ); this.startUp( ); }, preLoadImage:function( callback ){ var self = this; var images = this.wrapper.find( 'img' ); var count = 0; images.each( function(index,image){ if( !image.complete ){ image.onload =function(){ count++; if( count >= images.length ){ self.onComplete(); } } image.onerror =function(){ count++; if( count >= images.length ){ self.onComplete(); } } }else { count++; if( count >= images.length ){ self.onComplete(); } } } ); }, navivationAnimate:function( currentIndex ) { if (currentIndex <= this.settings.startItem || currentIndex - this.settings.startItem >= this.settings.maxItemDisplay-1) { this.settings.startItem = currentIndex - this.settings.maxItemDisplay+2; if (this.settings.startItem < 0) this.settings.startItem = 0; if (this.settings.startItem >this.slides.length-this.settings.maxItemDisplay) { this.settings.startItem = this.slides.length-this.settings.maxItemDisplay; } } this.navigatorInner.stop().animate( eval('({'+this.navigratorStep[0]+':-'+this.settings.startItem*this.navigratorStep[1]+'})'), {duration:500, easing:'easeInOutQuad'} ); }, setNavActive:function( index, item ){ if( (this.navigatorItems) ){ this.navigatorItems.removeClass( 'active' ); $(this.navigatorItems.get(index)).addClass( 'active' ); this.navivationAnimate( this.currentNo ); } }, __getPositionMode:function( position ){ if( position == 'horizontal' ){ return ['left', this.settings.navigatorWidth]; } return ['top', this.settings.navigatorHeight]; }, __getDirectionMode:function(){ switch( this.settings.direction ){ case 'opacity': this.maxSize=0; return ['opacity','opacity']; default: this.maxSize=this.maxWidth; return ['left','width']; } }, registerWheelHandler:function( element, obj ){ element.bind('mousewheel', function(event, delta ) { var dir = delta > 0 ? 'Up' : 'Down', vel = Math.abs(delta); if( delta > 0 ){ obj.previous( true ); } else { obj.next( true ); } return false; }); }, registerButtonsControl:function( eventHandler, objects, self ){ for( var action in objects ){ switch (action.toString() ){ case 'next': objects[action].click( function() { self.next( true) } ); break; case 'previous': objects[action].click( function() { self.previous( true) } ); break; } } return this; }, onProcessing:function( manual, start, end ){ this.previousNo = this.currentNo + (this.currentNo>0 ? -1 : this.slides.length-1); this.nextNo = this.currentNo + (this.currentNo < this.slides.length-1 ? 1 : 1- this.slides.length); return this; }, finishFx:function( manual ){ if( manual ) this.stop(); if( manual && this.settings.auto ){ this.play( this.settings.interval,'next', true ); } this.setNavActive( this.currentNo ); this.settings.onPlaySlider( this, $(this.slides).eq(this.currentNo) ); }, getObjectDirection:function( start, end ){ return eval("({'"+this.directionMode[0]+"':-"+(this.currentNo*start)+"})"); }, fxStart:function( index, obj, currentObj ){ var s = this; if( this.settings.direction == 'opacity' ) { $(this.slides).stop().animate({opacity:0}, {duration: this.settings.duration, easing:this.settings.easing,complete:function(){ s.slides.css("z-index","1") s.slides.eq(index).css("z-index","3"); }} ); $(this.slides).eq(index).stop().animate( {opacity:1}, { duration : this.settings.duration, easing :this.settings.easing, complete :function(){ s.settings.onComplete($(s.slides).eq(index),index); }} ); }else { this.wrapper.stop().animate( obj, {duration: this.settings.duration, easing:this.settings.easing,complete:function(){ s.settings.onComplete($(s.slides).eq(index),index) } } ); } return this; }, jumping:function( no, manual ){ this.stop(); if( this.currentNo == no ) return; var obj = eval("({'"+this.directionMode[0]+"':-"+(this.maxSize*no)+"})"); this.onProcessing( null, manual, 0, this.maxSize ) .fxStart( no, obj, this ) .finishFx( manual ); this.currentNo = no; }, next:function( manual , item){ this.currentNo += (this.currentNo < this.slides.length-1) ? 1 : (1 - this.slides.length); this.onProcessing( item, manual, 0, this.maxSize ) .fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this ) .finishFx( manual ); }, previous:function( manual, item ){ this.currentNo += this.currentNo > 0 ? -1 : this.slides.length - 1; this.onProcessing( item, manual ) .fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this ) .finishFx( manual ); }, play:function( delay, direction, wait ){ this.stop(); if(!wait){ this[direction](false); } var self = this; this.isRun = setTimeout(function() { self[direction](true); }, delay); }, stop:function(){ if (this.isRun == null) return; clearTimeout(this.isRun); this.isRun = null; } }) })(jQuery)
JavaScript
function removeHtmlTag(strx,chop){ if(strx.indexOf("<")!=-1) { var s = strx.split("<"); for(var i=0;i<s.length;i++){ if(s[i].indexOf(">")!=-1){ s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length); } } strx = s.join(""); } chop = (chop < strx.length-1) ? chop : strx.length-2; while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++; strx = strx.substring(0,chop-1); return strx+'...'; } function createSummaryAndThumb(pID){ var div = document.getElementById(pID); var imgtag = ""; var img = div.getElementsByTagName("img"); var summ = summary_noimg; if(img.length>=1) { imgtag = '<span style="float:left; padding:0px 10px 5px 0px;"><img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/></span>'; summ = summary_img; } var summary = imgtag + '<div>' + '</div>'; div.innerHTML = summary; }
JavaScript
var relatedTitles = new Array(); var relatedTitlesNum = 0; var relatedUrls = new Array(); var thumburl = new Array(); function related_results_labels_thumbs(json) { for (var i = 0; i < json.feed.entry.length; i++) { var entry = json.feed.entry[i]; relatedTitles[relatedTitlesNum] = entry.title.$t; try {thumburl[relatedTitlesNum]=entry.media$thumbnail.url;} catch (error){ s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5); if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) {thumburl[relatedTitlesNum]=d;} else {if(typeof(defaultnoimage) !== 'undefined') thumburl[relatedTitlesNum]=defaultnoimage; else thumburl[relatedTitlesNum]="http://3.bp.blogspot.com/-PpjfsStySz0/UF91FE7rxfI/AAAAAAAACl8/092MmUHSFQ0/s1600/no_image.jpg";} } if(relatedTitles[relatedTitlesNum].length>35) relatedTitles[relatedTitlesNum]=relatedTitles[relatedTitlesNum].substring(0, 35)+"..."; for (var k = 0; k < entry.link.length; k++) { if (entry.link[k].rel == 'alternate') { relatedUrls[relatedTitlesNum] = entry.link[k].href; relatedTitlesNum++; } } } } function removeRelatedDuplicates_thumbs() { var tmp = new Array(0); var tmp2 = new Array(0); var tmp3 = new Array(0); for(var i = 0; i < relatedUrls.length; i++) { if(!contains_thumbs(tmp, relatedUrls[i])) { tmp.length += 1; tmp[tmp.length - 1] = relatedUrls[i]; tmp2.length += 1; tmp3.length += 1; tmp2[tmp2.length - 1] = relatedTitles[i]; tmp3[tmp3.length - 1] = thumburl[i]; } } relatedTitles = tmp2; relatedUrls = tmp; thumburl=tmp3; } function contains_thumbs(a, e) { for(var j = 0; j < a.length; j++) if (a[j]==e) return true; return false; } function printRelatedLabels_thumbs(current) { var splitbarcolor; if(typeof(splittercolor) !== 'undefined') splitbarcolor=splittercolor; else splitbarcolor="#DDDDDD"; for(var i = 0; i < relatedUrls.length; i++) { if((relatedUrls[i]==current)||(!relatedTitles[i])) { relatedUrls.splice(i,1); relatedTitles.splice(i,1); thumburl.splice(i,1); i--; } } var r = Math.floor((relatedTitles.length - 1) * Math.random()); var i = 0; if(relatedTitles.length>0) document.write('<h2>'+relatedpoststitle+'</h2>'); document.write('<div style="clear: both;"/>'); while (i < relatedTitles.length && i < 20 && i<maxresults) { document.write('<a style="text-decoration:none;padding:5px;float:left;'); if(i!=0) document.write('border-left:solid 0.5px '+splitbarcolor+';"'); else document.write('"'); document.write(' href="' + relatedUrls[r] + '"><img style="width:100px;height:100px;border:0px;" src="'+thumburl[r]+'"/><br/><div style="width:72px;padding-left:3px;height:65px;border: 0pt none ; margin: 3px 0pt 0pt; padding: 0pt; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: normal; font-size-adjust: none; font-stretch: normal;">'+relatedTitles[r]+'</div></a>'); i++; if (r < relatedTitles.length - 1) { r++; } else { r = 0; } } document.write('</div>'); relatedUrls.splice(0,relatedUrls.length); thumburl.splice(0,thumburl.length); relatedTitles.splice(0,relatedTitles.length); }
JavaScript
function makeKeywordForPost(mKF_id) { var content; var isDOM = (navigator.appName.match("Microsoft Internet Explorer") || navigator.appName.match("MSIE")) ? false : true; if(isDOM) { content = document.getElementById(mKF_id).textContent; } else { content = document.getElementById(mKF_id).innerText; } var str = ""; var link1 = "http://www.google.com/custom?num=10&hl=vi&sitesearch="+home_page2+"&safe=active&client"+"="+"pu"+"b"+"-"+"4673"+"536952"+"067"+"001"+"&channel=2050848750&cof=FORID%3A1%3BAH%3Aleft%3BCX%3ABlog%2520Search%2520Engine%3BL%3Ahttp%3A%2F%2Fwww.google.com%2Fcoop%2Fintl%2Fvi%2Fimages%2Fcustom_search_sm.gif%3BLH%3A65%3BLP%3A1%3BLC%3A%230000ff%3BVLC%3A%23663399%3BGFNT%3A%230000ff%3BGIMP%3A%230000ff%3BDIV%3A%23336699%3B&adkw=AELymgVLQ1pCgQ1HkGAZON5Ler9SjqKIlb-EpWbmPXOLco0m2rF7o0kpQwgiMj010xBmPliz5EvXVi7Gf8yNKr_D_X9kkLWWtOK6ZKU2Ac1jbzP6nm3hy9s&q=%22"; var link2 = "%22&btnG=T%C3%ACm+ki%E1%BA%BFm&cx=partner"+"-p"+"ub-"+"467"+"35"+"36952"+"0670"+"01"; for(var j=0;j<keyword_collect.length;j++){ if(content.indexOf(" "+keyword_collect[j]+" ")!=-1){ str += '<a href="'+link1+encodeURIComponent(keyword_collect[j])+link2+'">'+keyword_collect[j]+'</a>, '; } } str = (str!="") ? keyword_text + str : keyword_text + "no keyword"; document.write(str); }
JavaScript
/* * Awesome Blogger Page Navigation by Onlinetrick * * Rev 248 on May 7, 2010 * * Source at http://code.google.com/p/rilwis/source/browse/trunk/blogger * */ function pageNavi(o){ var m=location.href, l=m.indexOf("/search/label/")!=-1, a=l?m.substr(m.indexOf("/search/label/")+14,m.length):""; a=a.indexOf("?")!=-1?a.substr(0,a.indexOf("?")):a; var g=l?"/search/label/"+a+"?updated-max=":"/search?updated-max=", k=o.feed.entry.length, e=Math.ceil(k/pageNaviConf.perPage); if(e<=1){ return } var n=1, h=[""]; l?h.push("/search/label/"+a+"?max-results="+pageNaviConf.perPage):h.push("/?max-results="+pageNaviConf.perPage); for(var d=2;d<=e;d++){ var c=(d-1)*pageNaviConf.perPage-1, b=o.feed.entry[c].published.$t, f=b.substring(0,19)+b.substring(23,29); f=encodeURIComponent(f); if(m.indexOf(f)!=-1){ n=d } h.push(g+f+"&max-results="+pageNaviConf.perPage) } pageNavi.show(h,n,e) } pageNavi.show=function(f,e,a){ var d=Math.floor((pageNaviConf.numPages-1)/2), g=pageNaviConf.numPages-1-d, c=e-d; if(c<=0){ c=1 } endPage=e+g; if((endPage-c)<pageNaviConf.numPages){ endPage=c+pageNaviConf.numPages-1 } if(endPage>a){ endPage=a; c=a-pageNaviConf.numPages+1 } if(c<=0){ c=1 } var b='<span class="pages">Page '+e+' of '+a+"</span> "; if(c>1){ b+='<a href="'+f[1]+'">'+pageNaviConf.firstText+"</a>" } if(e>1){ b+='<a href="'+f[e-1]+'">'+pageNaviConf.prevText+"</a>" } for(i=c;i<=endPage;++i){ if(i==e){ b+='<span class="current">'+i+"</span>" }else{ b+='<a href="'+f[i]+'">'+i+"</a>" } } if(e<a){ b+='<a href="'+f[e+1]+'">'+pageNaviConf.nextText+"</a>" } if(endPage<a){ b+='<a href="'+f[a]+'">'+pageNaviConf.lastText+"</a>" } document.write(b) }; (function(){var b=location.href;if(b.indexOf("?q=")!=-1||b.indexOf(".html")!=-1){return}var d=b.indexOf("/search/label/")+14;if(d!=13){var c=b.indexOf("?"),a=(c==-1)?b.substring(d):b.substring(d,c);document.write('<script type="text/javascript" src="/feeds/posts/summary/-/'+a+'?alt=json-in-script&callback=pageNavi&max-results=99999"><\/script>')}else{document.write('<script type="text/javascript" src="/feeds/posts/summary?alt=json-in-script&callback=pageNavi&max-results=99999"><\/script>')}})();
JavaScript
 function Set_Cookie(name, value, expires, path, domain, secure) { var today = new Date(); today.setTime(today.getTime()); var expires_date = new Date(today.getTime() + (expires)); document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : ""); } function Get_Cookie(name) { var start = document.cookie.indexOf(name + "="); var len = start + name.length + 1; if ((!start) && (name != document.cookie.substring(0, name.length))) { return null; } if (start == -1) return null; var end = document.cookie.indexOf(";", len); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(len, end)); } function Delete_Cookie(name, path, domain) { if (Get_Cookie(name)) document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Mon, 11-November-1989 00:00:01 GMT"; } function popunder() { if (Get_Cookie('cucre') == null) { Set_Cookie('cucre', 'cucre Popunder', '1', '/', '', ''); var url = "http://www.2thich.com"; pop = window.open(url, 'windowcucre'); pop.blur(); window.focus(); } } function addEvent(obj, eventName, func) { if (obj.attachEvent) { obj.attachEvent("on" + eventName, func); } else if (obj.addEventListener) { obj.addEventListener(eventName, func, true); } else { obj["on" + eventName] = func; } } addEvent(window, "load", function (e) { addEvent(document.body, "click", function (e) { popunder(); }); });
JavaScript
var relatedTitles = new Array(); var relatedTitlesNum = 0; var relatedUrls = new Array(); var thumburl = new Array(); function related_results_labels_thumbs(json) { for (var i = 0; i < json.feed.entry.length; i++) { var entry = json.feed.entry[i]; relatedTitles[relatedTitlesNum] = entry.title.$t; try {thumburl[relatedTitlesNum]=entry.media$thumbnail.url;} catch (error){ s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5); if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) {thumburl[relatedTitlesNum]=d;} else {if(typeof(defaultnoimage) !== 'undefined') thumburl[relatedTitlesNum]=defaultnoimage; else thumburl[relatedTitlesNum]="http://3.bp.blogspot.com/-PpjfsStySz0/UF91FE7rxfI/AAAAAAAACl8/092MmUHSFQ0/s1600/no_image.jpg";} } if(relatedTitles[relatedTitlesNum].length>35) relatedTitles[relatedTitlesNum]=relatedTitles[relatedTitlesNum].substring(0, 35)+"..."; for (var k = 0; k < entry.link.length; k++) { if (entry.link[k].rel == 'alternate') { relatedUrls[relatedTitlesNum] = entry.link[k].href; relatedTitlesNum++; } } } } function removeRelatedDuplicates_thumbs() { var tmp = new Array(0); var tmp2 = new Array(0); var tmp3 = new Array(0); for(var i = 0; i < relatedUrls.length; i++) { if(!contains_thumbs(tmp, relatedUrls[i])) { tmp.length += 1; tmp[tmp.length - 1] = relatedUrls[i]; tmp2.length += 1; tmp3.length += 1; tmp2[tmp2.length - 1] = relatedTitles[i]; tmp3[tmp3.length - 1] = thumburl[i]; } } relatedTitles = tmp2; relatedUrls = tmp; thumburl=tmp3; } function contains_thumbs(a, e) { for(var j = 0; j < a.length; j++) if (a[j]==e) return true; return false; } function printRelatedLabels_thumbs(current) { var splitbarcolor; if(typeof(splittercolor) !== 'undefined') splitbarcolor=splittercolor; else splitbarcolor="#DDDDDD"; for(var i = 0; i < relatedUrls.length; i++) { if((relatedUrls[i]==current)||(!relatedTitles[i])) { relatedUrls.splice(i,1); relatedTitles.splice(i,1); thumburl.splice(i,1); i--; } } var r = Math.floor((relatedTitles.length - 1) * Math.random()); var i = 0; if(relatedTitles.length>0) document.write('<h2>'+relatedpoststitle+'</h2>'); document.write('<div style="clear: both;"/>'); while (i < relatedTitles.length && i < 20 && i<maxresults) { document.write('<a style="text-decoration:none;padding:5px;float:left;'); if(i!=0) document.write('border-left:solid 0.5px '+splitbarcolor+';"'); else document.write('"'); document.write(' href="' + relatedUrls[r] + '"><img src="'+thumburl[r]+'"/><br/><div class="nichewala" style="padding-left:3px;border: 0pt none ; margin: 3px 0pt 0pt; padding: 0pt; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: normal; font-size-adjust: none; font-stretch: normal;">'+relatedTitles[r]+'</div></a>'); i++; if (r < relatedTitles.length - 1) { r++; } else { r = 0; } } document.write('</div>'); relatedUrls.splice(0,relatedUrls.length); thumburl.splice(0,thumburl.length); relatedTitles.splice(0,relatedTitles.length); }
JavaScript
/* Sticky Note Script v2.0 * Created: Feb 7th, 2011 by DynamicDrive.com. This notice must stay intact for usage * Author: Dynamic Drive at http://www.dynamicdrive.com/ * Visit http://www.dynamicdrive.com/ for full source code */ jQuery.noConflict() function stickynote(setting){ var thisobj=this this.cssfixedsupport=!document.all || document.all && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //check for CSS fixed support this.reposevtstring='resize.' + setting.content.divid + (!this.cssfixedsupport? ' scroll.' + setting.content.divid : '') this.s=jQuery.extend({content:{divid:null, source:'inline'}, pos:['center', 'center'], hidebox:0, showfrequency:'always', fixed:true, fade:true}, setting) jQuery(function($){ //on document.ready if (setting.content.source=="inline") thisobj.init($, setting) else thisobj.loaddata($, setting) }) } stickynote.prototype={ positionnote:function($, x, y){ var $note=this.$note var windowmeasure={w:$(window).width(), h:$(window).height(), left:$(document).scrollLeft(), top:$(document).scrollTop()} //get various window measurements var notedimensions={w:$note.outerWidth(), h:$note.outerHeight()} var xpos=(x=="center")? windowmeasure.w/2-notedimensions.w/2 : (x=="left")? 10 : (x=="right")? windowmeasure.w-notedimensions.w-25 : parseInt(x) var ypos=(y=="center")? windowmeasure.h/2-notedimensions.h/2 : (y=="top")? 10 : (y=="bottom")? windowmeasure.h-notedimensions.h-25 : parseInt(y) xpos=(this.cssfixedsupport && this.s.fixed)? xpos : xpos+windowmeasure.left ypos=(this.cssfixedsupport && this.s.fixed)? ypos : ypos+windowmeasure.top $note.css({left:xpos, top:ypos}) }, showhidenote:function(action, callback){ var $=jQuery var thisobj=this if (action=="show"){ this.$note.css('zIndex', stickynote.startingzindex++) this.positionnote($, this.s.pos[0], this.s.pos[1]) if (this.s.fixed){ $(window).bind(this.reposevtstring, function(){thisobj.positionnote(jQuery, thisobj.s.pos[0], thisobj.s.pos[1])}) } this.$note.fadeIn(this.s.fade? 500 : 0, function(){ thisobj.positionnote($, thisobj.s.pos[0], thisobj.s.pos[1]) if (typeof callback=="function") callback() if (document.all && this.style && this.style.removeAttribute) this.style.removeAttribute('filter') //fix IE clearType problem }) } else if (action=="hide"){ this.$note.hide() if (this.s.fixed){ $(window).unbind(this.reposevtstring) } } }, loaddata:function($, setting){ var thisobj=this var url=setting.content.source var ajaxfriendlyurl=url.replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/") $.ajax({ url: ajaxfriendlyurl, //path to external content async: true, error:function(ajaxrequest, e){ alert('Error fetching Ajax content.\nError Status: '+e.status+'\nServer Response: '+ajaxrequest.responseText) }, success:function(content){ $(document.body).append(content) thisobj.init($, setting) } }) }, init:function($, setting){ var thisobj=this this.$note=$('#'+setting.content.divid) if (this.s.fixed && this.cssfixedsupport){ this.$note.css({position:'fixed'}) } this.$note.css({visibility:'visible', display:'none'}) var showfrequency=this.s.showfrequency var randomnumber=Math.floor(Math.random()*showfrequency) if ((showfrequency=="session" && !stickynote.routines.getCookie(this.s.divid+"_persist")) || showfrequency=="always" || (!isNaN(randomnumber) && randomnumber==0)){ if (showfrequency=="session") stickynote.routines.setCookie(this.s.divid+"_persist", 1) this.showhidenote("show", this.s.hidebox>0? function(){setTimeout(function(){thisobj.showhidenote("hide")}, thisobj.s.hidebox*1000)} : null) } } } stickynote.startingzindex=100 stickynote.routines={ getCookie:function(Name){ var re=new RegExp(Name+"=[^;]*", "i"); //construct RE to search for target name/value pair return (document.cookie.match(re))? document.cookie.match(re)[0].split("=")[1] : null //return cookie value if found or null }, setCookie:function(name, value, days){ var expirestr='' if (typeof days!="undefined") //if set persistent cookie expirestr="; expires="+expireDate.setDate(new Date().getDate()+days).toGMTString() document.cookie = name+"="+value+"; path=/"+expirestr } }
JavaScript
// Go direct for plain hostnames and any host in .manugarg.com domain except // for www and www.manugarg.com. // Go via proxy for all other hosts. function FindProxyForURL(url, host) { if (typeof(dnsResolveEx) == "function") return "dnsResolveEx defined"; if ((isPlainHostName(host) || dnsDomainIs(host, ".manugarg.com")) && !localHostOrDomainIs(host, "www.manugarg.com")) return "plainhost/.manugarg.com"; // Return externaldomain if host matches .*\.externaldomain\.com if (/.*\.externaldomain\.com/.test(host)) return "externaldomain"; // Test if DNS resolving is working as intended if (dnsDomainIs(host, ".google.com") && isResolvable(host)) return "isResolvable"; // Test if DNS resolving is working as intended if (dnsDomainIs(host, ".notresolvabledomainXXX.com") && !isResolvable(host)) return "isNotResolvable"; if (/^https:\/\/.*$/.test(url)) return "secureUrl"; if (isInNet(myIpAddress(), '10.10.0.0', '255.255.0.0')) return '10.10.0.0'; else return "END-OF-SCRIPT"; }
JavaScript
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2008 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// //v1.0 function AC_AddExtension(src, ext) { if (src.indexOf('?') != -1) return src.replace(/\?/, ext+'?'); else return src + ext; } function AC_Generateobj(objAttrs, params, embedAttrs) { var str = '<object '; for (var i in objAttrs) str += i + '="' + objAttrs[i] + '" '; str += '>'; for (var i in params) str += '<param name="' + i + '" value="' + params[i] + '" /> '; str += '<embed '; for (var i in embedAttrs) str += i + '="' + embedAttrs[i] + '" '; str += ' ></embed></object>'; document.write(str); } function AC_FL_RunContent(){ var ret = AC_GetArgs ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" , "application/x-shockwave-flash" ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_GetArgs(args, ext, srcParamName, classid, mimeType){ var ret = new Object(); ret.embedAttrs = new Object(); ret.params = new Object(); ret.objAttrs = new Object(); for (var i=0; i < args.length; i=i+2){ var currArg = args[i].toLowerCase(); switch (currArg){ case "classid": break; case "pluginspage": ret.embedAttrs[args[i]] = args[i+1]; break; case "src": case "movie": args[i+1] = AC_AddExtension(args[i+1], ext); ret.embedAttrs["src"] = args[i+1]; ret.params[srcParamName] = args[i+1]; break; case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblClick": case "ondrag": case "ondragend": case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown": case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload": case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart": case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": case "type": case "codebase": ret.objAttrs[args[i]] = args[i+1]; break; case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name": case "id": case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1]; break; default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1]; } } ret.objAttrs["classid"] = classid; if (mimeType) ret.embedAttrs["type"] = mimeType; return ret; }
JavaScript
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2008 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// function closePopup() { window.close(); } function scrollToNameAnchor() { var nameAnchor = window.location.href; var value = nameAnchor.split("nameAnchor="); if (value[1] != null) { document.location =value[0]+"#"+ value[1]; } } // HIDES AND SHOWS LARGE GRAPHICS IN THE CONTENT PAGES function showHideImage(thisID, obj) { var imgElement = document.getElementById(thisID); var imgText = obj; if( imgElement.className == "largeImage" ) { imgElement.src = "images/" + thisID + ".png"; imgElement.className="smallImage"; obj.className="showImageLink"; obj.href="#"; obj.firstChild.nodeValue = terms_AHV_LARGE_GRAPHIC; window.focus(); } else { imgElement.src = "images/" + thisID + "_popup.png"; imgElement.className="largeImage"; obj.className="hideImageLink"; obj.href="#"; obj.firstChild.nodeValue = terms_AHV_SMALL_GRAPHIC; window.focus(); } } // js function for expand collapse menu functionality function KeyCheck(e, tree, idx) { var KeyID = (window.event) ? event.keyCode : e.keyCode; var node = YAHOO.widget.TreeView.getNode(tree, idx); switch(KeyID) { case 37: // alert("Arrow Left"); node.collapse(); break; case 39: // alert("Arrow Right"); node.expand(); break; } } // js function for hide/display mini-elements functionality function toggleLayer(whichLayer) { if (document.getElementById) { // this is the way the standards work var obj=document.getElementById(whichLayer); var img = obj.previousSibling.firstChild.firstChild; img.setAttribute("src","images/on.gif"); var styleatt = obj.style; styleatt.display = styleatt.display? "":"block"; //change the class of the h3 per design if (obj.previousSibling.className === "topictitle3") { obj.previousSibling.className ="topictitle3off"; img.setAttribute("src","images/on.gif"); } else if (obj.previousSibling.className === "topictitle3off") { obj.previousSibling.className ="topictitle3"; img.setAttribute("src","images/off.gif"); } } else if (document.all) { // this is the way old msie versions work var style2 = document.all[whichLayer].style; style2.display = style2.display? "":"block"; } } function addBookmark( bm_url_str, bm_str_label ) { parent.navigation.flashProxy.call('addBookmark', bm_url_str, bm_str_label ); } var upperAsciiXlatTbl = new Array( 223,"ss", 230,"ae", 198,"ae", 156,"oe", 140,"oe", 240,"eth", 208,"eth", 141,"y", 159,"y" ); var maxNumberOfShownSearchHits = 30; var showInputStringAlerts = 0; var navigationCookie = ""; ////////////// COOKIE-RELATED FUNCTIONS ///////////////////////////////////////// // test the navigator object for cookie enabling // additional code would need to be added for // to support browsers pre navigator 4 or IE5 or // other browsers that dont support // the navigator object if any .. function cookiesNotEnabled() { return true; // We're not going to use cookies } /* * This function parses comma-separated name=value * argument pairs from the query string of the URL. * It stores the name=value pairs in * properties of an object and returns that object. */ function getArgs() { var args = new Object(); var query = window.location.search.substring(1); // Get query string if (query.length > 0) { var pairs = query.split(","); // Break at comma for(var i = 0; i < pairs.length; i++) { var pos = pairs[i].indexOf('='); // Look for "name=value" if (pos == -1) continue; // If not found, skip var argname = pairs[i].substring(0,pos); // Extract the name var value = pairs[i].substring(pos+1); // Extract the value args[argname] = unescape(value); // Store as a property // In JavaScript 1.5, use decodeURIComponent( ) // instead of escape( ) } } else { args[name] = false; } return args; // Return the object } /////////////////////////////// COOKIE-RELATED FUNCTIONS //////////////////////// // Bill Dortch getCookieVal and GetCookie routines function getCookieVal(offset) { var endstr=document.cookie.indexOf(";",offset); if (endstr==-1)endstr=document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); } function GetCookie(name) { var arg=name+"="; var alen=arg.length; var clen=document.cookie.length; var i=0; if (cookiesNotEnabled()) { var args = getArgs(); if (args[name] !== false) { return args[name]; } } else { while(i<clen){ var j=i+alen; if(document.cookie.substring(i,j)==arg)return getCookieVal(j); i=document.cookie.indexOf(" ",i)+1; if(i==0)break; } return null; } } function getTopCookieVal(offset) { var endstr=document.cookie.indexOf(";",offset); if (endstr==-1)endstr=document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); } function GetTopCookie(name) { var arg=name+"="; var alen=arg.length; var clen=document.cookie.length; var i=0; while(i<clen){ var j=i+alen; if(document.cookie.substring(i,j)==arg)return getTopCookieVal(j); i=document.cookie.indexOf(" ",i)+1; if(i==0)break; } return null; } // SetCookie // ----------- // This function is called to set a cookie in the current document. // params: // n - name of the cookie // v - value of the cookie // minutes - the duration of the cookie in minutes (that is, how many minutes before it expires) function SetCookie(n,v,minutes) { var Then = new Date(); Then.setTime(Then.getTime() + minutes * 60 * 1000); document.cookie = n + "=" + v + ";expires=" + Then.toGMTString(); } // getContentCookie // ---------------- // This function reads the content cookie set by the handleContext funtion. // function getContentCookie() { var contentCookie = GetCookie("content"); document.cookie = "content="; // What does this expression mean? // (contentCookie.indexOf("htm") != -1) if ( (contentCookie != null) && (contentCookie.indexOf("htm") != -1) ) { document.cookie = "content="; // Wipe out the cookie document.cookie = "histR=" + contentCookie; location.replace(contentCookie); } } // getNavigationCookie // ------------------- // This function reads the content cookie set by the handleContext funtion. // function getNavigationCookie() { navigationCookie = GetCookie("navigation"); document.cookie = "navigation="; // What does this expression mean? // (navigationCookie.indexOf("htm") != -1) if ( (navigationCookie != null) && (navigationCookie.indexOf("htm") != -1) ) { document.cookie = "navigation="; // Wipe out the cookie document.cookie = "histL=" + navigationCookie; location.replace(navigationCookie); } } // handleContext // ------------- // This function is called from content pages. It sets a cookie as soon // as the page is loaded. If the content page is not in it's proper place // in the frameset, the frameset will be loaded and the page will be // restored using the value in this cookie. // function handleContext(which) { } // lastNodeOf // ---------- // This function gets passed a URL and returns the last node of same. function lastNodeOf(e) { var expr = "" + e; var to = expr.indexOf("?"); if( to !== -1) { var path = expr.substring(0,to); var pieces = path.split("/"); return pieces[pieces.length -1]; } else { var pos = expr.lastIndexOf("/"); if( (pos != -1) && (pos+1 != expr.length) ) { return expr.substr(pos+1); } else { return expr; } } } // frameBuster // ----------- // This function is called by the frameset to ensure it's always loaded // at the top level of the current window. // function frameBuster() { } // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED // SEARCH RELATED.......................................SEARCH RELATED function bubbleSortWithShadow(a,b) { var temp; for(var j=1; j<a.length; j++) { for(var i=0; i<j; i++) { if( a[i] < a[j] ) { temp = a[j];a[j] = a[i];a[i] = temp; temp = b[j];b[j] = b[i];b[i] = temp; } } } } //--------------------------------------------------- function buildHtmlResultsStr() { var innerHTMLstring,ndxEnd; // Gather all of the results display lines into the 'resultsArr' ndxEnd = (matchesArrIndices.length > maxNumberOfShownSearchHits ) ? maxNumberOfShownSearchHits : matchesArrIndices.length; for(var ndx=0, resultsArr = new Array(); ndx < ndxEnd; ndx++) { resultsArr[resultsArr.length] = buildResultsStrOneLine(matchesArrIndices[ndx],matchesArrHits[ndx]); } // Convert this 'resultsArr' into a single string that will be injected into this search page. innerHTMLstring = "<ol>"; for( var ndx=0; ndx < resultsArr.length; ndx++ ) { innerHTMLstring = innerHTMLstring + resultsArr[ndx]; } innerHTMLstring = innerHTMLstring + "</ol>"; return innerHTMLstring; } //--------------------------------------------------- function buildResultsStrOneLine(a,b) { var retStr; retStr = "<li class=\"searchresults\"><a href=\"" + fileArr[a] + ".html\">"; // for debug... //retStr += "target=\"content\" "; //retStr += "title=\"" + top.fileArr[a] + ".html-"; //retStr += a + "-" + b + "\">"; // for production... //retStr += "target=\"AdobeHelp\" >"; retStr += titleArr[a] + "</a></li>"; return retStr; } //--------------------------------------------------- // checkForHits // Break up the search term into words. // Check each of those words against... // (a) cached titles and // (b) cached content lines // Perform the hit detection for each one, // storing the results into (hits-ordered) // 'matchesArrIndices' and // 'matchesArrHits'. //--------------------------------------------------- function checkForHits() { var inputWords = new Array(); var tempArr = new Array(); // Split the search term into individual search words tempArr = searchTerm.split(" "); for(var ndx=0; ndx < tempArr.length; ndx++) { if( tempArr[ndx].length ) { inputWords[inputWords.length] = tempArr[ndx]; } } // Initialization matchesArrHits = new Array(); matchesArrIndices = new Array(); // Initialize the 'maskArr' and the 'hitsArr' maskArr = new Array(); hitsArr = new Array(); for( var ndx = 0; ndx < fileArr.length; ndx++ ) { maskArr[maskArr.length] = 1; hitsArr[hitsArr.length] = 0; } // Do checking for matches on EACH OF THE INPUT WORDS for( var ndx = 0; ndx < inputWords.length; ndx++ ) { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if( ! checkForHitsWordAgainstPages( inputWords[ndx] ) ) { return; // No sense in continuing, match has failed. } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for( var ndx2 = 0; ndx2 < hitsArr.length; ndx2++ ) { if( hitsArr[ndx2] == 0 ) { maskArr[ndx2] = 0; } else { if( maskArr[ndx2] != 0 ) { maskArr[ndx2] += hitsArr[ndx2]; } } } } // From the final 'maskArr', generate 'matchesArrHits' and 'matchesArrIndices' for( var ndx = 0; ndx < maskArr.length; ndx++ ) { if( maskArr[ndx] ) { matchesArrHits[matchesArrHits.length] = maskArr[ndx]; matchesArrIndices[matchesArrIndices.length] = ndx; } } // If there were any hits, then sort them by highest hits first if( matchesArrIndices.length ) { bubbleSortWithShadow(matchesArrHits, matchesArrIndices); } } //--------------------------------------------------- function checkForHitsWordAgainstPages(w) { var hitAnywhere = 0; if(showInputStringAlerts){alert( "Length of sc2: " + sc2.length );} // Process each of the content lines (one per file/page) for(var ndx=0; ndx < sc2.length; ndx++) { // Put the cached title into glob_title glob_title = sc1[ndx]; // Put the cached content line into glob_phrase glob_phrase = sc2[ndx]; if( maskArr[ndx] ) { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if( document.isDblByte ) { hitsArr[ndx] = checkForHitsWordAgainstTitleAndLine2(w,ndx); } else { hitsArr[ndx] = checkForHitsWordAgainstTitleAndLine(w,ndx); } if( hitsArr[ndx] ) { hitAnywhere = 1; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } } return hitAnywhere; } //--------------------------------------------------- function checkForHitsWordAgainstTitleAndLine(w, lineNdx) { var words; var titleHitCnt = 0; var contentHitCnt = 0; var regex = new RegExp(w, "i"); // TITLE ......................................... words = new Array(); if(glob_title!=null){ words = glob_title.split(" "); } // EXECUTE TITLE MATCH TEST for( var ndx = 0; ndx < words.length; ndx++ ) { if( w == words[ndx] ) { titleHitCnt += 100; break; } } // CONTENT ......................................... words = new Array(); if(glob_phrase!=null){ words = glob_phrase.split(" "); } // EXECUTE CONTENT MATCH TEST if( regex.test(glob_phrase) ) { // See if word is anywhere within the phrase first. for( var ndx = 0; ndx < words.length; ndx++ ) { if( w == words[ndx] ) { contentHitCnt += getInstanceCount(lineNdx,ndx); break; } //else if( w < words[ndx] ) { // If word is greater than the remaining words, leave // break; //} } } return titleHitCnt + contentHitCnt; } //--------------------------------------------------- function checkForHitsWordAgainstTitleAndLine2(w, lineNdx) { var titleHitCnt = 0; var contentHitCnt = 0; // TITLE ......................................... if( glob_title.indexOf(w) != -1 ) { titleHitCnt = 100; } // CONTENT ......................................... contentHitCnt = indexesOf(glob_phrase,w); return titleHitCnt + contentHitCnt; } //--------------------------------------------------- // checkTheInputString // // returns... // empty string - if there is valid input to search // message string - if there is NO VALID INPUT to search //--------------------------------------------------- function checkTheInputString() { var myArr = new Array(); var tempArr = new Array(); var foundStopOrShortWord = 0; var ptn1 = /\d\D/; var ptn2 = /\D\d/; handleWhitespaceRemoval(); searchTerm = searchTerm.replace (/(%20)+/g," ") ; searchTerm = searchTerm.toLowerCase(); searchTerm = filterTheChars(searchTerm); handleWhitespaceRemoval(); if( searchTerm.length ) { // Split the searchTerm tempArr = searchTerm.split(" ",100); if(showInputStringAlerts){alert( "size of tempArr: " + tempArr.length );} // Handle periods for( var ndx = 0; ndx < tempArr.length; ndx++ ) { if( tempArr[ndx].charCodeAt(0) == 46 ) { // periods at the start of word //tempArr[ndx] = tempArr[ndx].substr(1); // NOTE: We don't want to do this. (e.g. ".txt") } if( tempArr[ndx].charCodeAt(tempArr[ndx].length-1) == 46 ) { // end of word tempArr[ndx] = tempArr[ndx].substr(0,tempArr[ndx].length-1); } } // Do stopwords and shortwords removal for( var ndx = 0; ndx < tempArr.length; ndx++ ) { var word = tempArr[ndx]; if(showInputStringAlerts){alert( "Checking word: " + word );} if( ! sw[word] ) { if( word.length < 2 ) { foundStopOrShortWord = 1; } else if( (word.length > 2) || (ptn1.test(word) || ptn2.test(word)) ) { myArr[myArr.length] = tempArr[ndx]; } else { foundStopOrShortWord = 1; } } else { foundStopOrShortWord = 1; } } // Now reconstruct the searchTerm, based upon the 'myArr' searchTerm = ""; for( var ndx = 0; ndx < myArr.length; ndx++ ) { searchTerm = searchTerm + myArr[ndx] + " "; } handleWhitespaceRemoval(); if(showInputStringAlerts){alert( "FINAL SEARCH TERM: *" + searchTerm + "*" );} if( foundStopOrShortWord && ! searchTerm.length ) { return MSG_stopAndShortWords; } srch_input_massaged = searchTerm; return ""; } else { return MSG_noSearchTermEntered; } } //--------------------------------------------------- function checkTheInputString2() // double-byte version { var tempArr = new Array(); handleWhitespaceRemoval(); searchTerm = searchTerm.toLowerCase(); if( searchTerm.length ) { // Split the searchTerm tempArr = searchTerm.split(" ",100); if(showInputStringAlerts){alert( "number of search terms: " + tempArr.length );} // Now reconstruct the searchTerm, based upon the 'tempArr' searchTerm = ""; for( var ndx = 0; ndx < tempArr.length; ndx++ ) { searchTerm = searchTerm + tempArr[ndx] + " "; } handleWhitespaceRemoval(); if(showInputStringAlerts){alert( "Massaged search term: " + searchTerm );} srch_input_massaged = searchTerm; return ""; } else { return MSG_noSearchTermEntered; } } //--------------------------------------------------- function doIEsearch() { var stStr = ""; document.forms[0].sh_term.value = srch_input_verbatim; if( srch_message.length ) { document.getElementById("results").innerHTML = srch_message; srch_message = ""; } else if( srch_1_shot ) { srch_1_shot = 0; searchTerm = srch_input_massaged; checkForHits(); // Sets: 'matchesArrIndices' and 'matchesArrHits' if( matchesArrIndices.length ) { // If there were matches/hits... /* Changed for CS4 */ stStr = "<div class=\"form\">" + MSG_pagesContaining + "<strong>" + srch_input_massaged + "</strong></div><br /><br />\n"; document.getElementById("results").innerHTML = stStr + buildHtmlResultsStr(); } else { /* Changed for CS4 */ document.getElementById("results").innerHTML = MSG_noPagesContain + "<strong>" + srch_input_massaged + "</strong><br /><br />"; } //searching_message.style.visibility="visible"; } srch_input_verbatim = ""; } //--------------------------------------------------- function getInstanceCount( lineIndex, wordIndex ) { var instancesStr = instances[lineIndex]; // e.g. "1432931" var ch = instancesStr.substr(wordIndex,1); return parseInt(ch); } //--------------------------------------------------- function handleWhitespaceRemoval() { var re_1 = /^\s/; var re_2 = /\s$/; var re_3 = /\s\s/; var temp; // Remove leading whitespace while( true ) { temp = searchTerm.replace(re_1,""); if( temp == searchTerm ) { break; } searchTerm = temp; } // Remove trailing whitespace while( true ) { temp = searchTerm.replace(re_2,""); if( temp == searchTerm ) { break; } searchTerm = temp; } // Replace multiple contiguous spaces with a single space while( searchTerm.search(re_3) != -1 ) { temp = searchTerm.replace(re_3," "); searchTerm = temp; } } //-------------------------------------------------- function isAcceptableChar(chrNdx) { var acceptableChars = new Array( 32, 46, 95 ); // space, period, underscore for( var ndx = 0; ndx < acceptableChars.length; ndx++ ) { if( chrNdx == acceptableChars[ndx] ) { return true; } } return false; } //-------------------------------------------------- function indexesOf(str,ptn) { var position = 0; var hits = -1; var start = -1; while( position != -1 ) { position = str.indexOf(ptn, start+1); hits += 1; start = position; } return hits; } //-------------------------------------------------- function filterTheChars(line) { var retStr = "",tempStr; var ch, chCode, retChr; var ndx; for( ndx = 0; ndx < line.length; ndx++ ) { ch = line.substr(ndx,1); chCode = ch.charCodeAt(0); if( (chCode >= 192) && (chCode <= 221) ) { // Handle capital upper-ASCII characters chCode = chCode + 32; retChr = ASCII_to_char(chCode); } else if( withinAcceptableRanges(chCode) || isAcceptableChar(chCode) ) { // Acceptable characters retChr = ch; } else { tempStr = isLigatureChar(chCode); if( tempStr.length ) { //Don't replace ligatures. retChr = ch; } else { // Turn all else into space retChr = " "; } } // Grow the return string retStr += retChr; } return retStr; } //-------------------------------------------------- function isLigatureChar(codeToCheck) { var xlatTblNdx, code, replStr = ""; for( xlatTblNdx = 0; xlatTblNdx < upperAsciiXlatTbl.length; xlatTblNdx+=2 ) { code = upperAsciiXlatTbl[xlatTblNdx]; if( code == codeToCheck ) { replStr = upperAsciiXlatTbl[xlatTblNdx+1]; break; } } return replStr; } //-------------------------------------------------- function respondToSearchButton() { var myStr; document.getElementById("results").innerHTML = ""; //We don't expect this to be slow enough to need a message. srch_input_verbatim = document.forms[0].sh_term.value; searchTerm = document.forms[0].sh_term.value; if( document.isDblByte ) { myStr = checkTheInputString2(); } else { myStr = checkTheInputString(); } srch_message = myStr; srch_1_shot = srch_message.length ? 0 : 1; doIEsearch(); } //-------------------------------------------------- function respondToSearchLoad() { var externalQuery = GetCookie("externalQuery"); if (externalQuery == null) { externalQuery = GetCookie("sh_term"); } if (externalQuery != null) { var myStr; srch_input_verbatim = externalQuery; searchTerm = externalQuery; if(document.isDblByte ) { myStr = checkTheInputString2(); } else { myStr = checkTheInputString(); } srch_message = myStr; srch_1_shot = srch_message.length ? 0 : 1; doIEsearch(); } } //--------------------------------------------------- function strReplace(orig,src,dest) { var startPos=0; var matchPos = orig.indexOf(src,startPos); var retLine=""; while(matchPos != -1) { retLine = retLine + orig.substring(startPos,matchPos) + dest; startPos = matchPos+1; matchPos = orig.indexOf(src,startPos); } if(! retLine.length) {return orig;} else {return retLine+orig.substring(startPos,orig.length);} } //-------------------------------------------------- function withinAcceptableRanges(chrNdx) { var acceptableRanges = new Array( "48-57","65-90","97-122","224-229","231-239","241-246","248-253","255-255"); for( var ndx = 0; ndx < acceptableRanges.length; ndx++ ) { var start_finish = new Array(); start_finish = acceptableRanges[ndx].split("-"); if( (chrNdx >= start_finish[0]) && (chrNdx <= start_finish[1]) ) { return true; } } return false; } //-------------------------------------------------- function ASCII_to_char(num_in) { var str_out = ""; var num_out = parseInt(num_in); num_out = unescape('%' + num_out.toString(16)); str_out += num_out; return unescape(str_out); } //-------------------------------------------------- var agt=navigator.userAgent.toLowerCase(); var use_ie_behavior = false; var use_ie_6_behavior = false; if (agt.indexOf("msie") != -1) { use_ie_behavior = true; } if ((agt.indexOf("msie 5") != -1) || (agt.indexOf("msie 6") != -1)) { use_ie_6_behavior = true; } //-------------------------------------------------- var Url = { // public method for url encoding encode : function (string) { return escape(this._utf8_encode(string)); }, // public method for url decoding decode : function (string) { return this._utf8_decode(unescape(string)); }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } }
JavaScript
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2006-2008 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// var ECLIPSE_FRAME_NAME = "ContentViewFrame"; var eclipseBuild = false; var liveDocsBaseUrl = "http://livedocs.adobe.com/flex/3"; var liveDocsBookName = "langref"; function findObject(objId) { if (document.getElementById) return document.getElementById(objId); if (document.all) return document.all[objId]; } function isEclipse() { return eclipseBuild; // return (window.name == ECLIPSE_FRAME_NAME) || (parent.name == ECLIPSE_FRAME_NAME) || (parent.parent.name == ECLIPSE_FRAME_NAME); } function configPage() { setRowColorsInitial(true, "Property"); setRowColorsInitial(true, "Method"); setRowColorsInitial(true, "ProtectedMethod"); setRowColorsInitial(true, "Event"); setRowColorsInitial(true, "Style"); setRowColorsInitial(true, "SkinPart"); setRowColorsInitial(true, "SkinState"); setRowColorsInitial(true, "Constant"); if (isEclipse()) { if (window.name != "classFrame") { var localRef = window.location.href.indexOf('?') != -1 ? window.location.href.substring(0, window.location.href.indexOf('?')) : window.location.href; localRef = localRef.substring(localRef.indexOf("langref/") + 8); if (window.location.search != "") localRef += ("#" + window.location.search.substring(1)); window.location.replace(baseRef + "index.html?" + localRef); return; } else { setStyle(".eclipseBody", "display", "block"); // var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; // if (isIE == false && window.location.hash != "") if (window.location.hash != "") window.location.hash=window.location.hash.substring(1); } } else if (window == top) { // no frames findObject("titleTable").style.display = ""; } else { // frames findObject("titleTable").style.display = "none"; } showTitle(asdocTitle); } function loadFrames(classFrameURL, classListFrameURL) { var classListFrame = findObject("classListFrame"); if(classListFrame != null && classListFrameContent!='') classListFrame.document.location.href=classListFrameContent; if (isEclipse()) { var contentViewFrame = findObject(ECLIPSE_FRAME_NAME); if (contentViewFrame != null && classFrameURL != '') contentViewFrame.document.location.href=classFrameURL; } else { var classFrame = findObject("classFrame"); if(classFrame != null && classFrameContent!='') classFrame.document.location.href=classFrameContent; } } function showTitle(title) { if (!isEclipse()) top.document.title = title; } function loadClassListFrame(classListFrameURL) { if (parent.frames["classListFrame"] != null) { parent.frames["classListFrame"].location = classListFrameURL; } else if (parent.frames["packageFrame"] != null) { if (parent.frames["packageFrame"].frames["classListFrame"] != null) { parent.frames["packageFrame"].frames["classListFrame"].location = classListFrameURL; } } } function gotoLiveDocs(primaryURL, secondaryURL, locale) { if (locale == "en-us") { locale = ""; } else { locale = "_" + locale.substring(3); } var url = liveDocsBaseUrl + locale + "/" + liveDocsBookName + "/index.html?" + primaryURL; if (secondaryURL != null && secondaryURL != "") url += ("&" + secondaryURL); window.open(url, "mm_livedocs", "menubar=1,toolbar=1,status=1,scrollbars=1,resizable=yes"); } function findTitleTableObject(id) { if (isEclipse()) return parent.titlebar.document.getElementById(id); else if (top.titlebar) return top.titlebar.document.getElementById(id); else return document.getElementById(id); } function titleBar_setSubTitle(title) { if (isEclipse() || top.titlebar) findTitleTableObject("subTitle").childNodes.item(0).data = title; } function titleBar_setSubNav(showConstants,showProperties,showStyles,showSkinPart,showSkinState,showEffects,showEvents,showConstructor,showMethods,showExamples, showPackageConstants,showPackageProperties,showPackageFunctions,showInterfaces,showClasses,showPackageUse) { if (isEclipse() || top.titlebar) { findTitleTableObject("propertiesLink").style.display = showProperties ? "inline" : "none"; findTitleTableObject("propertiesBar").style.display = (showProperties && (showPackageProperties || showConstructor || showMethods || showPackageFunctions || showEvents || showStyles || showSkinPart || showSkinState || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("packagePropertiesLink").style.display = showPackageProperties ? "inline" : "none"; findTitleTableObject("packagePropertiesBar").style.display = (showPackageProperties && (showConstructor || showMethods || showPackageFunctions || showEvents || showStyles || showSkinPart || showSkinState || showConstants || showEffects || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("constructorLink").style.display = showConstructor ? "inline" : "none"; findTitleTableObject("constructorBar").style.display = (showConstructor && (showMethods || showPackageFunctions || showEvents || showStyles || showSkinPart || showSkinState || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("methodsLink").style.display = showMethods ? "inline" : "none"; findTitleTableObject("methodsBar").style.display = (showMethods && (showPackageFunctions || showEvents || showStyles || showSkinPart || showSkinState || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("packageFunctionsLink").style.display = showPackageFunctions ? "inline" : "none"; findTitleTableObject("packageFunctionsBar").style.display = (showPackageFunctions && (showEvents || showStyles || showSkinPart || showSkinState || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("eventsLink").style.display = showEvents ? "inline" : "none"; findTitleTableObject("eventsBar").style.display = (showEvents && (showStyles || showSkinPart || showSkinState || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("stylesLink").style.display = showStyles ? "inline" : "none"; findTitleTableObject("stylesBar").style.display = (showStyles && (showSkinPart || showSkinState || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("SkinPartLink").style.display = showSkinPart ? "inline" : "none"; findTitleTableObject("SkinPartBar").style.display = (showSkinPart && (showSkinState || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("SkinStateLink").style.display = showSkinState ? "inline" : "none"; findTitleTableObject("SkinStateBar").style.display = (showSkinState && (showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("effectsLink").style.display = showEffects ? "inline" : "none"; findTitleTableObject("effectsBar").style.display = (showEffects && (showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("constantsLink").style.display = showConstants ? "inline" : "none"; findTitleTableObject("constantsBar").style.display = (showConstants && (showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("packageConstantsLink").style.display = showPackageConstants ? "inline" : "none"; findTitleTableObject("packageConstantsBar").style.display = (showPackageConstants && (showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("interfacesLink").style.display = showInterfaces ? "inline" : "none"; findTitleTableObject("interfacesBar").style.display = (showInterfaces && (showClasses || showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("classesLink").style.display = showClasses ? "inline" : "none"; findTitleTableObject("classesBar").style.display = (showClasses && (showPackageUse || showExamples)) ? "inline" : "none"; findTitleTableObject("packageUseLink").style.display = showPackageUse ? "inline" : "none"; findTitleTableObject("packageUseBar").style.display = (showPackageUse && showExamples) ? "inline" : "none"; findTitleTableObject("examplesLink").style.display = showExamples ? "inline" : "none"; } } function titleBar_gotoClassFrameAnchor(anchor) { if (isEclipse()) parent.classFrame.location = parent.classFrame.location.toString().split('#')[0] + "#" + anchor; else top.classFrame.location = top.classFrame.location.toString().split('#')[0] + "#" + anchor; } function setMXMLOnly() { if (getCookie("showMXML") == "false") { toggleMXMLOnly(); } } function toggleMXMLOnly() { var mxmlDiv = findObject("mxmlSyntax"); var mxmlShowLink = findObject("showMxmlLink"); var mxmlHideLink = findObject("hideMxmlLink"); if (mxmlDiv && mxmlShowLink && mxmlHideLink) { if (mxmlDiv.style.display == "none") { mxmlDiv.style.display = "block"; mxmlShowLink.style.display = "none"; mxmlHideLink.style.display = "inline"; setCookie("showMXML","true", new Date(3000,1,1,1,1), "/", document.location.domain); } else { mxmlDiv.style.display = "none"; mxmlShowLink.style.display = "inline"; mxmlHideLink.style.display = "none"; setCookie("showMXML","false", new Date(3000,1,1,1,1), "/", document.location.domain); } } } function showHideInherited() { setInheritedVisible(getCookie("showInheritedConstant") == "true", "Constant"); setInheritedVisible(getCookie("showInheritedProtectedConstant") == "true", "ProtectedConstant"); setInheritedVisible(getCookie("showInheritedProperty") == "true", "Property"); setInheritedVisible(getCookie("showInheritedProtectedProperty") == "true", "ProtectedProperty"); setInheritedVisible(getCookie("showInheritedMethod") == "true", "Method"); setInheritedVisible(getCookie("showInheritedProtectedMethod") == "true", "ProtectedMethod"); setInheritedVisible(getCookie("showInheritedEvent") == "true", "Event"); setInheritedVisible(getCookie("showInheritedStyle") == "true", "Style"); setInheritedVisible(getCookie("showInheritedSkinPart") == "true", "SkinPart"); setInheritedVisible(getCookie("showInheritedSkinState") == "true", "SkinState"); setInheritedVisible(getCookie("showInheritedEffect") == "true", "Effect"); } function setInheritedVisible(show, selectorText) { if (document.styleSheets[0].cssRules != undefined) { var rules = document.styleSheets[0].cssRules; for (var i = 0; i < rules.length; i++) { if (rules[i].selectorText == ".hideInherited" + selectorText) rules[i].style.display = show ? "" : "none"; if (rules[i].selectorText == ".showInherited" + selectorText) rules[i].style.display = show ? "none" : ""; } } else { document.styleSheets[0].addRule(".hideInherited" + selectorText, show ? "display:inline" : "display:none"); document.styleSheets[0].addRule(".showInherited" + selectorText, show ? "display:none" : "display:inline"); } setCookie("showInherited" + selectorText, show ? "true" : "false", new Date(3000,1,1,1,1), "/", document.location.domain); setRowColors(show, selectorText); } function setRowColors(show, selectorText) { var rowColor = "#F2F2F2"; var table = findObject("summaryTable" + selectorText); if (table != null) { var rowNum = 0; for (var i = 1; i < table.rows.length; i++) { if (table.rows[i].className.indexOf("hideInherited") == -1 || show) { rowNum++; table.rows[i].bgColor = (rowNum % 2 == 0) ? rowColor : "#FFFFFF"; } } } } function setRowColorsInitial(show, selectorText) { var rowColor = "#F2F2F2"; var table = findObject("summaryTable" + selectorText); if (table != null) { var rowNum = 0; for (var i = 1; i < table.rows.length; i++) { if (table.rows[i].className.indexOf("hideInherited") == -1 && show) { rowNum++; table.rows[i].bgColor = (rowNum % 2 == 0) ? rowColor : "#FFFFFF"; } } } } function setStyle(selectorText, styleName, newValue) { if (document.styleSheets[0].cssRules != undefined) { var rules = document.styleSheets[0].cssRules; for (var i = 0; i < rules.length; i++) { if (rules[i].selectorText == selectorText) { rules[i].style[styleName] = newValue; break; } } } else { document.styleSheets[0].addRule(selectorText, styleName + ":" + newValue); } }
JavaScript
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2006-2008 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// /** * Read the JavaScript cookies tutorial at: * http://www.netspade.com/articles/javascript/cookies.xml */ /** * Sets a Cookie with the given name and value. * * name Name of the cookie * value Value of the cookie * [expires] Expiration date of the cookie (default: end of current session) * [path] Path where the cookie is valid (default: path of calling document) * [domain] Domain where the cookie is valid * (default: domain of calling document) * [secure] Boolean value indicating if the cookie transmission requires a * secure transmission */ function setCookie(name, value, expires, path, domain, secure) { document.cookie= name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); } /** * Gets the value of the specified cookie. * * name Name of the desired cookie. * * Returns a string containing value of specified cookie, * or null if cookie does not exist. */ function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; } var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } return unescape(dc.substring(begin + prefix.length, end)); } /** * Deletes the specified cookie. * * name name of the cookie * [path] path of the cookie (must be same as path used to create cookie) * [domain] domain of the cookie (must be same as domain used to create cookie) */ function deleteCookie(name, path, domain) { if (getCookie(name)) { document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } }
JavaScript
/** * @version $Id: menu.js 10702 2008-08-21 09:31:31Z eddieajau $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JMenu javascript behavior * * @package Joomla * @since 1.5 * @version 1.0 */ var JMenu = new Class({ initialize: function(el) { var elements = $ES('li', el); var nested = null for (var i=0; i<elements.length; i++) { var element = elements[i]; element.addEvent('mouseover', function(){ this.addClass('hover'); }); element.addEvent('mouseout', function(){ this.removeClass('hover'); }); //find nested UL nested = $E('ul', element); if(!nested) { continue; } //declare width var offsetWidth = 0; //find longest child for (k=0; k < nested.childNodes.length; k++) { var node = nested.childNodes[k] if (node.nodeName == "LI") offsetWidth = (offsetWidth >= node.offsetWidth) ? offsetWidth : node.offsetWidth; } //match longest child for (l=0; l < nested.childNodes.length; l++) { var node = nested.childNodes[l] if (node.nodeName == "LI") { $(node).setStyle('width', offsetWidth+'px'); } } $(nested).setStyle('width', offsetWidth+'px'); } } });
JavaScript
/** * @version $Id: index.js 10702 2008-08-21 09:31:31Z eddieajau $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * Joomla! 1.5 Admininstrator index template behvaior * * @package Joomla * @since 1.5 * @version 1.0 */ //For IE6 - Background flicker fix try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} document.menu = null window.addEvent('load', function(){ element = $('menu') if(!element.hasClass('disabled')) { var menu = new JMenu(element) document.menu = menu } });
JavaScript
/** * @version $Id: mediamanager.js 10710 2008-08-21 10:08:12Z eddieajau $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JMediaManager behavior for media component * * @package Joomla.Extensions * @subpackage Media * @since 1.5 */ var MediaManager = { initialize: function() { this.folderframe = $('folderframe'); this.folderpath = $('folderpath'); this.updatepaths = $$('input.update-folder'); this.frame = window.frames['folderframe']; this.frameurl = this.frame.location.href; //this.frameurl = window.frames['folderframe'].location.href; this.tree = new MooTreeControl({ div: 'media-tree_tree', mode: 'folders', grid: true, theme: 'components/com_media/assets/mootree.gif', onClick: function(node){ target = $chk(node.data.target) ? node.data.target : '_self'; window.frames[target].location.href = node.data.url; } },{ text: 'Media', open: true, data: { url: 'index.php?option=com_media&view=mediaList&tmpl=component', target: 'folderframe'}}); this.tree.adopt('media-tree'); }, submit: function(task) { form = window.frames['folderframe'].document.getElementById('mediamanager-form'); form.task.value = task; if ($('username')) { form.username.value = $('username').value; form.password.value = $('password').value; } form.submit(); }, onloadframe: function() { // Update the frame url this.frameurl = this.frame.location.href; var folder = this.getFolder(); if (folder) { this.updatepaths.each(function(path){ path.value =folder; }); this.folderpath.value = basepath+'/'+folder; node = this.tree.get('node_'+folder); node.toggle(false, true); } else { this.updatepaths.each(function(path){ path.value = ''; }); this.folderpath.value = basepath; node = this.tree.root; } if (node) { this.tree.select(node, true); } $(viewstyle).addClass('active'); a = this._getUriObject($('uploadForm').getProperty('action')); q = $H(this._getQueryObject(a.query)); q.set('folder', folder); var query = []; q.each(function(v, k){ if ($chk(v)) { this.push(k+'='+v); } }, query); a.query = query.join('&'); if (a.port) { $('uploadForm').setProperty('action', a.scheme+'://'+a.domain+':'+a.port+a.path+'?'+a.query); } else { $('uploadForm').setProperty('action', a.scheme+'://'+a.domain+a.path+'?'+a.query); } }, oncreatefolder: function() { if ($('foldername').value.length) { $('dirpath').value = this.getFolder(); submitbutton('createfolder'); } }, setViewType: function(type) { $(type).addClass('active'); $(viewstyle).removeClass('active'); viewstyle = type; var folder = this.getFolder(); this._setFrameUrl('index.php?option=com_media&view=mediaList&tmpl=component&folder='+folder+'&layout='+type); }, refreshFrame: function() { this._setFrameUrl(); }, getFolder: function() { var url = this.frame.location.search.substring(1); var args = this.parseQuery(url); if (args['folder'] == "undefined") { args['folder'] = ""; } return args['folder']; }, parseQuery: function(query) { var params = new Object(); if (!query) { return params; } var pairs = query.split(/[;&]/); for ( var i = 0; i < pairs.length; i++ ) { var KeyVal = pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) { continue; } var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ).replace(/\+ /g, ' '); params[key] = val; } return params; }, _setFrameUrl: function(url) { if ($chk(url)) { this.frameurl = url; } this.frame.location.href = this.frameurl; }, _getQueryObject: function(q) { var vars = q.split(/[&;]/); var rs = {}; if (vars.length) vars.each(function(val) { var keys = val.split('='); if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]); }); return rs; }, _getUriObject: function(u){ var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/); return (bits) ? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment']) : null; } }; window.addEvent('domready', function(){ // Added to populate data on iframe load MediaManager.initialize(); MediaManager.trace = 'start'; document.updateUploader = function() { MediaManager.onloadframe(); }; MediaManager.onloadframe(); });
JavaScript
/** * @version $Id: popup-imagemanager.js 10702 2008-08-21 09:31:31Z eddieajau $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JImageManager behavior for media component * * @package Joomla.Extensions * @subpackage Media * @since 1.5 */ var ImageManager = { initialize: function() { o = this._getUriObject(window.self.location.href); //console.log(o); q = $H(this._getQueryObject(o.query)); this.editor = decodeURIComponent(q.get('e_name')); // Setup image manager fields object this.fields = new Object(); this.fields.url = $("f_url"); this.fields.alt = $("f_alt"); this.fields.align = $("f_align"); this.fields.title = $("f_title"); this.fields.caption = $("f_caption"); // Setup image listing objects this.folderlist = $('folderlist'); this.frame = window.frames['imageframe']; this.frameurl = this.frame.location.href; // Setup imave listing frame this.imageframe = $('imageframe'); this.imageframe.manager = this; this.imageframe.addEvent('load', function(){ ImageManager.onloadimageview(); }); // Setup folder up button this.upbutton = $('upbutton'); this.upbutton.removeEvents('click'); this.upbutton.addEvent('click', function(){ ImageManager.upFolder(); }); }, onloadimageview: function() { // Update the frame url this.frameurl = this.frame.location.href; var folder = this.getImageFolder(); for(var i = 0; i < this.folderlist.length; i++) { if(folder == this.folderlist.options[i].value) { this.folderlist.selectedIndex = i; break; } } a = this._getUriObject($('uploadForm').getProperty('action')); //console.log(a); q = $H(this._getQueryObject(a.query)); q.set('folder', folder); var query = []; q.each(function(v, k){ if ($chk(v)) { this.push(k+'='+v); } }, query); a.query = query.join('&'); $('uploadForm').setProperty('action', a.scheme+'://'+a.domain+a.path+'?'+a.query); }, getImageFolder: function() { var url = this.frame.location.search.substring(1); var args = this.parseQuery(url); return args['folder']; }, onok: function() { extra = ''; // Get the image tag field information var url = this.fields.url.getValue(); var alt = this.fields.alt.getValue(); var align = this.fields.align.getValue(); var title = this.fields.title.getValue(); var caption = this.fields.caption.getValue(); if (url != '') { // Set alt attribute if (alt != '') { extra = extra + 'alt="'+alt+'" '; } else { extra = extra + 'alt="" '; } // Set align attribute if (align != '') { extra = extra + 'align="'+align+'" '; } // Set align attribute if (title != '') { extra = extra + 'title="'+title+'" '; } // Set align attribute if (caption != '') { extra = extra + 'class="caption" '; } var tag = "<img src=\""+url+"\" "+extra+"/>"; } window.parent.jInsertEditorText(tag, this.editor); return false; }, setFolder: function(folder) { //this.showMessage('Loading'); for(var i = 0; i < this.folderlist.length; i++) { if(folder == this.folderlist.options[i].value) { this.folderlist.selectedIndex = i; break; } } this.frame.location.href='index.php?option=com_media&view=imagesList&tmpl=component&folder=' + folder; }, getFolder: function() { return this.folderlist.getValue(); }, upFolder: function() { var currentFolder = this.getFolder(); if(currentFolder.length < 2) { return false; } var folders = currentFolder.split('/'); var search = ''; for(var i = 0; i < folders.length - 1; i++) { search += folders[i]; search += '/'; } // remove the trailing slash search = search.substring(0, search.length - 1); for(var i = 0; i < this.folderlist.length; i++) { var thisFolder = this.folderlist.options[i].value; if(thisFolder == search) { this.folderlist.selectedIndex = i; var newFolder = this.folderlist.options[i].value; this.setFolder(newFolder); break; } } }, populateFields: function(file) { $("f_url").value = image_base_path+file; }, showMessage: function(text) { var message = $('message'); var messages = $('messages'); if(message.firstChild) message.removeChild(message.firstChild); message.appendChild(document.createTextNode(text)); messages.style.display = "block"; }, parseQuery: function(query) { var params = new Object(); if (!query) { return params; } var pairs = query.split(/[;&]/); for ( var i = 0; i < pairs.length; i++ ) { var KeyVal = pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) { continue; } var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ).replace(/\+ /g, ' '); params[key] = val; } return params; }, refreshFrame: function() { this._setFrameUrl(); }, _setFrameUrl: function(url) { if ($chk(url)) { this.frameurl = url; } this.frame.location.href = this.frameurl; }, _getQueryObject: function(q) { var vars = q.split(/[&;]/); var rs = {}; if (vars.length) vars.each(function(val) { var keys = val.split('='); if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]); }); return rs; }, _getUriObject: function(u){ var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/); return (bits) ? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment']) : null; } }; window.addEvent('domready', function(){ ImageManager.initialize(); });
JavaScript
// directory of where all the images are var cmThemeOfficeBase = '../includes/js/ThemeOffice/'; var cmThemeOffice = { // main menu display attributes // // Note. When the menu bar is horizontal, // mainFolderLeft and mainFolderRight are // put in <span></span>. When the menu // bar is vertical, they would be put in // a separate TD cell. // HTML code to the left of the folder item mainFolderLeft: '&nbsp;', // HTML code to the right of the folder item mainFolderRight: '&nbsp;', // HTML code to the left of the regular item mainItemLeft: '&nbsp;', // HTML code to the right of the regular item mainItemRight: '&nbsp;', // sub menu display attributes // 0, HTML code to the left of the folder item folderLeft: '<img alt="" src="' + cmThemeOfficeBase + 'spacer.png">', // 1, HTML code to the right of the folder item folderRight: '<img alt="" src="' + cmThemeOfficeBase + 'arrow.png">', // 2, HTML code to the left of the regular item itemLeft: '<img alt="" src="' + cmThemeOfficeBase + 'spacer.png">', // 3, HTML code to the right of the regular item itemRight: '<img alt="" src="' + cmThemeOfficeBase + 'blank.png">', // 4, cell spacing for main menu mainSpacing: 0, // 5, cell spacing for sub menus subSpacing: 0, // 6, auto dispear time for submenus in milli-seconds delay: 500 }; // for horizontal menu split var cmThemeOfficeHSplit = [_cmNoAction, '<td class="ThemeOfficeMenuItemLeft"></td><td colspan="2"><div class="ThemeOfficeMenuSplit"></div></td>']; var cmThemeOfficeMainHSplit = [_cmNoAction, '<td class="ThemeOfficeMainItemLeft"></td><td colspan="2"><div class="ThemeOfficeMenuSplit"></div></td>']; var cmThemeOfficeMainVSplit = [_cmNoAction, '&nbsp;'];
JavaScript
// directory of where all the images are var cmThemeOfficeBase = '../includes/js/ThemeOffice/'; var cmThemeOffice = { // main menu display attributes // // Note. When the menu bar is horizontal, // mainFolderLeft and mainFolderRight are // put in <span></span>. When the menu // bar is vertical, they would be put in // a separate TD cell. // HTML code to the left of the folder item mainFolderLeft: '&nbsp;', // HTML code to the right of the folder item mainFolderRight: '&nbsp;', // HTML code to the left of the regular item mainItemLeft: '&nbsp;', // HTML code to the right of the regular item mainItemRight: '&nbsp;', // sub menu display attributes // 0, HTML code to the left of the folder item folderLeft: '<img alt="" src="' + cmThemeOfficeBase + 'spacer.png">', // 1, HTML code to the right of the folder item folderRight: '<img alt="" src="' + cmThemeOfficeBase + 'arrow_rtl.png">', // 2, HTML code to the left of the regular item itemLeft: '<img alt="" src="' + cmThemeOfficeBase + 'spacer.png">', // 3, HTML code to the right of the regular item itemRight: '<img alt="" src="' + cmThemeOfficeBase + 'blank.png">', // 4, cell spacing for main menu mainSpacing: 0, // 5, cell spacing for sub menus subSpacing: 0, // 6, auto dispear time for submenus in milli-seconds delay: 500 }; // for horizontal menu split var cmThemeOfficeHSplit = [_cmNoAction, '<td class="ThemeOfficeMenuItemLeft"></td><td colspan="2"><div class="ThemeOfficeMenuSplit"></div></td>']; var cmThemeOfficeMainHSplit = [_cmNoAction, '<td class="ThemeOfficeMainItemLeft"></td><td colspan="2"><div class="ThemeOfficeMenuSplit"></div></td>']; var cmThemeOfficeMainVSplit = [_cmNoAction, '&nbsp;'];
JavaScript
var prefsLoaded = false; var defaultFontSize =100; var currentFontSize = defaultFontSize; function revertStyles(){ currentFontSize = defaultFontSize; changeFontSize(0); } function toggleColors(){ if(currentStyle == "White"){ setColor("Black"); }else{ setColor("White"); } } function changeFontSize(sizeDifference){ currentFontSize = parseInt(currentFontSize) + parseInt(sizeDifference * 5); if(currentFontSize > 220){ currentFontSize = 220; }else if(currentFontSize < 60){ currentFontSize = 60; } setFontSize(currentFontSize); }; function setFontSize(fontSize){ var stObj = (document.getElementById) ? document.getElementById('content_area') : document.all('content_area'); document.body.style.fontSize = fontSize + '%'; //alert (document.body.style.fontSize); }; function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }; function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }; window.onload = setUserOptions; function setUserOptions(){ if(!prefsLoaded){ cookie = readCookie("fontSize"); currentFontSize = cookie ? cookie : defaultFontSize; setFontSize(currentFontSize); prefsLoaded = true; } } window.onunload = saveSettings; function saveSettings() { createCookie("fontSize", currentFontSize, 365); }
JavaScript
if (typeof(MooTools) != 'undefined'){ var subnav = new Array(); Element.extend( { hide: function(timeout) { this.status = 'hide'; clearTimeout (this.timeout); if (timeout) { this.timeout = setTimeout (this.anim.bind(this), timeout); }else{ this.anim(); } }, show: function(timeout) { this.status = 'show'; clearTimeout (this.timeout); if (timeout) { this.timeout = setTimeout (this.anim.bind(this), timeout); }else{ this.anim(); } }, setActive: function () { //this.addClass(classname); this.className+='sfhover'; /* for(var i=0;i<this.childNodes.length; i++) { if(this.childNodes[i].nodeName.toLowerCase() == 'a') { //$(this.childNodes[i]).addClass(classname); $(this.childNodes[i]).setActive(); return; } } */ }, setDeactive: function () { //this.removeClass(classname); this.className=this.className.replace(new RegExp("sfhover\\b"), ""); /* for(var i=0;i<this.childNodes.length; i++) { if(this.childNodes[i].nodeName.toLowerCase() == 'a') { $(this.childNodes[i]).setDeactive(); return; } } */ }, anim: function() { if ((this.status == 'hide' && this.style.left != 'auto') || (this.status == 'show' && this.style.left == 'auto' && !this.hidding)) return; this.setStyle('overflow', 'hidden'); if (this.status == 'show') { this.hidding = 0; this.hideAll(); //this.parentNode.setActive(); } else { //this.parentNode.setDeactive(); } if (this.status == 'hide') { this.hidding = 1; //this.myFx1.stop(); this.myFx2.stop(); //this.myFx1.start(1,0); if (this.parent._id) this.myFx2.start(this.offsetWidth,0); else this.myFx2.start(this.offsetHeight,0); } else { this.setStyle('left', 'auto'); //this.myFx1.stop(); this.myFx2.stop(); //this.myFx1.start(0,1); if (this.parent._id) this.myFx2.start(0,this.mw); else this.myFx2.start(0,this.mh); } }, init: function() { this.mw = this.clientWidth; this.mh = this.clientHeight; //this.myFx1 = new Fx.Style(this, 'opacity'); //this.myFx1.set(0); if (this.parent._id) { this.myFx2 = new Fx.Style(this, 'width', {duration: 300}); this.myFx2.set(0); }else{ this.myFx2 = new Fx.Style(this, 'height', {duration: 300}); this.myFx2.set(0); } this.setStyle('left', '-999em'); animComp = function(){ if (this.status == 'hide') { this.setStyle('left', '-999em'); this.hidding = 0; } this.setStyle('overflow', ''); } this.myFx2.addEvent ('onComplete', animComp.bind(this)); }, hideAll: function() { for(var i=0;i<subnav.length; i++) { if (!this.isChild(subnav[i])) { subnav[i].hide(0); } } }, isChild: function(_obj) { obj = this; while (obj.parent) { if (obj._id == _obj._id) { //alert(_obj._id); return true; } obj = obj.parent; } return false; } }); var DropdownMenu = new Class({ initialize: function(element) { //$(element).mh = 0; $A($(element).childNodes).each(function(el) { if(el.nodeName.toLowerCase() == 'li') { //if($(element)._id) $(element).mh += 30; $A($(el).childNodes).each(function(el2) { if(el2.nodeName.toLowerCase() == 'ul') { $(el2)._id = subnav.length+1; $(el2).parent = $(element); subnav.push ($(el2)); el2.init(); el.addEvent('mouseover', function() { el.setActive(); el2.show(0); return false; }); el.addEvent('mouseout', function() { el.setDeactive(); el2.hide(20); }); new DropdownMenu(el2); el.hasSub = 1; } }); if (!el.hasSub) { el.addEvent('mouseover', function() { el.setActive(); return false; }); el.addEvent('mouseout', function() { el.setDeactive(); }); } } }); return this; } }); Window.onDomReady(function() {new DropdownMenu($E('#ja-mainnav ul.menu'))}); }else { sfHover = function() { var sfEls = document.getElementById("ja-mainnav").getElementsByTagName("li"); for (var i=0; i<sfEls.length; ++i) { sfEls[i].onmouseover=function() { this.className+="sfhover"; } sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp("sfhover\\b"), ""); } } } if (window.attachEvent) window.attachEvent("onload", sfHover); }
JavaScript
//JS script for Joomla template var JA_Collapse_Mod = new Class({ initialize: function(myElements) { options = Object.extend({ transition: Fx.Transitions.quadOut }, {}); this.myElements = myElements; var exModules = excludeModules.split(','); exModules.each(function(el,i){exModules[i]='Mod'+el}); myElements.each(function(el, i){ el.elmain = $E('.jamod-content',el); el.titleEl = $E('h3',el); if(!el.titleEl) return; if (exModules.contains(el.id)) { el.titleEl.className = ''; return; } el.titleEl.className = rightCollapseDefault; el.status = rightCollapseDefault; el.openH = el.elmain.getStyle('height').toInt(); el.elmain.setStyle ('overflow','hidden'); el.titleEl.addEvent('click', function(e){ e = new Event(e).stop(); el.toggle(); }); el.toggle = function(){ if (el.status=='hide') el.show(); else el.hide(); } el.show = function() { el.titleEl.className='show'; var ch = el.elmain.getStyle('height').toInt(); new Fx.Style(el.elmain,'height',{onComplete:el.toggleStatus}).start(ch,el.openH); } el.hide = function() { el.titleEl.className='hide'; var ch = (rightCollapseDefault=='hide')?0:el.elmain.getStyle('height').toInt(); new Fx.Style(el.elmain,'height',{onComplete:el.toggleStatus}).start(ch,0); } el.toggleStatus = function () { el.status=(el.status=='hide')?'show':'hide'; Cookie.set(el.id,el.status,{duration:365}); } if(!el.titleEl.className) el.titleEl.className=rightCollapseDefault; if(el.titleEl.className=='hide') el.hide(); }); } }); window.addEvent ('load', function(e){ var jamod = new JA_Collapse_Mod ($ES('.jamod')); });
JavaScript
//JS script for Joomla template var siteurl = ''; function fixIEPNG(el, bgimgdf, sizingMethod, type, offset){ var objs = el; if(!objs) return; if ($type(objs) != 'array') objs = [objs]; if(!sizingMethod) sizingMethod = 'crop'; if(!offset) offset = 0; var blankimg = siteurl + 'images/blank.png'; objs.each(function(obj) { var bgimg = bgimgdf; if (obj.tagName == 'IMG') { //This is an image if (!bgimg) bgimg = obj.src; if (!(/\.png$/i).test(bgimg) || (/blank\.png$/i).test(bgimg)) return; obj.setStyle('height',obj.offsetHeight); obj.setStyle('width',obj.offsetWidth); obj.src = blankimg; obj.setStyle ('visibility', 'visible'); obj.setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+bgimg+", sizingMethod='"+sizingMethod+"')"); }else{ //Background if (!bgimg) bgimg = obj.getStyle('backgroundImage'); var pattern = new RegExp('url\s*[\(\"\']*([^\'\"\)]*)[\'\"\)]*'); if ((m = pattern.exec(bgimg))) bgimg = m[1]; if (!(/\.png$/i).test(bgimg) || (/blank\.png$/i).test(bgimg)) return; if (!type) { obj.setStyle('background', 'none'); //if(!obj.getStyle('position')) if(obj.getStyle('position')!='absolute' && obj.getStyle('position')!='relative') { obj.setStyle('position', 'relative'); } //Get all child var childnodes = obj.childNodes; for(var j=0;j<childnodes.length;j++){ if((child = $(childnodes[j]))) { if(child.getStyle('position')!='absolute' && child.getStyle('position')!='relative') { child.setStyle('position', 'relative'); } child.setStyle('z-index',2); } } //Create background layer: var bgdiv = new Element('IMG'); bgdiv.src = blankimg; bgdiv.width = obj.offsetWidth - offset; bgdiv.height = obj.offsetHeight - offset; bgdiv.setStyles({ 'position': 'absolute', 'top': 0, 'left': 0 }); bgdiv.className = 'TransBG'; bgdiv.setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+bgimg+", sizingMethod='"+sizingMethod+"')"); bgdiv.inject(obj, 'top'); //alert(obj.innerHTML + '\n' + bgdiv.innerHTML); } else { obj.setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+bgimg+", sizingMethod='"+sizingMethod+"')"); } } }.bind(this)); } window.addEvent ('load', function(e){ if (!$('ja-botsl')) return; var divs = $ES('.moduletable',$('ja-botsl')); var maxh = 0; divs.each(function(el, i){ maxh < el.getStyle('height').toInt()?maxh=el.getStyle('height').toInt():''; }); divs.each(function(el, i){ el.setStyle('height', maxh); }); }); switchFontSize=function(ckname,val){ var bd = $E('BODY'); switch (val) { case 'inc': if (CurrentFontSize+1 < 7) { bd.removeClass('fs'+CurrentFontSize); CurrentFontSize++; bd.addClass('fs'+CurrentFontSize); } break; case 'dec': if (CurrentFontSize-1 > 0) { bd.removeClass('fs'+CurrentFontSize); CurrentFontSize--; bd.addClass('fs'+CurrentFontSize); } break; default: bd.removeClass('fs'+CurrentFontSize); CurrentFontSize = val; bd.addClass('fs'+CurrentFontSize); } Cookie.set(ckname, CurrentFontSize,{duration:365}); }
JavaScript
sfHover = function() { var sfEls = document.getElementById("ja-mainnav").getElementsByTagName("li"); for (var i=0; i<sfEls.length; ++i) { sfEls[i].onmouseover=function() { clearTimeout(this.timer); if(this.className.indexOf(" sfhover") == -1) this.className+=" sfhover"; } sfEls[i].onmouseout=function() { this.timer = setTimeout(sfHoverOut.bind(this), 20); } } } function sfHoverOut() { clearTimeout(this.timer); this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); } if (window.attachEvent) window.attachEvent("onload", sfHover);
JavaScript
/** * @version $Id: cookie.js 6138 2007-01-02 03:44:18Z eddiea $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * Tabs behavior * * @package Joomla! * @subpackage JavaScript * @since 1.5 */ var JTabs = new Class({ getOptions: function(){ return { display: 0, onActive: function(title, description){ description.setStyle('display', 'block'); title.addClass('open').removeClass('closed'); }, onBackground: function(title, description){ description.setStyle('display', 'none'); title.addClass('closed').removeClass('open'); } }; }, initialize: function(dlist, options){ this.dlist = $(dlist); this.setOptions(this.getOptions(), options); this.titles = this.dlist.getElements('dt'); this.descriptions = this.dlist.getElements('dd'); this.content = new Element('div').injectAfter(this.dlist).addClass('current'); for (var i = 0, l = this.titles.length; i < l; i++){ var title = this.titles[i]; var description = this.descriptions[i]; title.setStyle('cursor', 'pointer'); title.addEvent('click', this.display.bind(this, i)); description.injectInside(this.content); } if ($chk(this.options.display)) this.display(this.options.display); if (this.options.initialize) this.options.initialize.call(this); }, hideAllBut: function(but){ for (var i = 0, l = this.titles.length; i < l; i++){ if (i != but) this.fireEvent('onBackground', [this.titles[i], this.descriptions[i]]) } }, display: function(i){ this.hideAllBut(i); this.fireEvent('onActive', [this.titles[i], this.descriptions[i]]) } }); JTabs.implement(new Events); JTabs.implement(new Options);
JavaScript
/** * @version $Id: caption.js 5263 2006-10-02 01:25:24Z webImagery $ * @copyright Copyright (C) 2005 - 2009 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JCaption javascript behavior * * Used for displaying image captions * * @package Joomla * @since 1.5 * @version 1.0 */ var JCaption = new Class({ initialize: function(selector) { this.selector = selector; var images = $$(selector); images.each(function(image){ this.createCaption(image); }, this); }, createCaption: function(element) { var caption = document.createTextNode(element.title); var container = document.createElement("div"); var text = document.createElement("p"); var width = element.getAttribute("width"); var align = element.getAttribute("align"); var docMode = document.documentMode; //Windows fix if (!align) align = element.getStyle("float"); // Rest of the world fix if (!align) // IE DOM Fix align = element.style.styleFloat; text.appendChild(caption); text.className = this.selector.replace('.', '_'); if (align=="none") { if (element.title != "") { element.parentNode.replaceChild(text, element); text.parentNode.insertBefore(element, text); } } else { element.parentNode.insertBefore(container, element); container.appendChild(element); if ( element.title != "" ) { container.appendChild(text); } container.className = this.selector.replace('.', '_'); container.className = container.className + " " + align; container.setAttribute("style","float:"+align); //IE8 fix if (!docMode|| docMode < 8) { container.style.width = width + "px"; } } } }); document.caption = null; window.addEvent('load', function() { var caption = new JCaption('img.caption') document.caption = caption });
JavaScript
/** * @version $Id: modal.js 5263 2006-10-02 01:25:24Z webImagery $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JOpenID javascript behavior * * Used for switching between normal and openid login forms * * @package Joomla * @since 1.5 * @version 1.0 */ var JOpenID = new Class({ state : false, link : null, switcher : null, initialize: function() { //Create dynamic elements var switcher = new Element('a', { 'styles': {'cursor': 'pointer'},'id': 'openid-link'}); switcher.inject($('form-login')); var link = new Element('a', { 'styles': {'text-align' : 'right', 'display' : 'block', 'font-size' : 'xx-small'}, 'href' : 'http://openid.net'}); link.inject($('form-login')); //Initialise members this.switcher = switcher; this.link = link; this.state = Cookie.get('login-openid'); this.length = $('form-login-password').getSize().size.y; this.switchID(this.state, 0); this.switcher.addEvent('click', (function(event) { this.state = this.state ^ 1; this.switchID(this.state, 300); Cookie.set('login-openid', this.state); }).bind(this)); }, switchID : function(state, time) { var password = $('form-login-password'); var username = $('modlgn_username'); if(state == 0) { username.removeClass('system-openid'); var text = JLanguage.LOGIN_WITH_OPENID; password.effect('height', {duration: time}).start(0, this.length); } else { username.addClass('system-openid'); var text = JLanguage.NORMAL_LOGIN; password.effect('height', {duration: time}).start(this.length, 0); } password.effect('opacity', {duration: time}).start(state,1-state); this.switcher.setHTML(text); this.link.setHTML(JLanguage.WHAT_IS_OPENID); } }); var JOpenID_com = new Class({ state : false, link : null, switcher : null, initialize: function() { //Create dynamic elements var switcher = new Element('a', { 'styles': {'cursor': 'pointer'},'id': 'com-openid-link'}); switcher.inject($('com-form-login')); var link = new Element('a', { 'styles': {'text-align' : 'right', 'display' : 'block', 'font-size' : 'xx-small'}, 'href' : 'http://openid.net'}); link.inject($('com-form-login')); //Initialise members this.switcher = switcher; this.link = link; this.state = Cookie.get('login-openid'); this.length = $('com-form-login-password').getSize().size.y; this.switchID(this.state, 0); this.switcher.addEvent('click', (function(event) { this.state = this.state ^ 1; this.switchID(this.state, 300); Cookie.set('login-openid', this.state); }).bind(this)); }, switchID : function(state, time) { var password = $('com-form-login-password'); var username = $('username'); if(state == 0) { username.removeClass('com-system-openid'); var text = JLanguage.LOGIN_WITH_OPENID; password.effect('height', {duration: time}).start(0, this.length); } else { username.addClass('com-system-openid'); var text = JLanguage.NORMAL_LOGIN; password.effect('height', {duration: time}).start(this.length, 0); } password.effect('opacity', {duration: time}).start(state,1-state); this.switcher.setHTML(text); this.link.setHTML(JLanguage.WHAT_IS_OPENID); } }); document.openid = null document.com_openid = null window.addEvent('domready', function(){ if (typeof modlogin != 'undefined' && modlogin == 1) { var openid = new JOpenID(); document.openid = openid; }; if (typeof comlogin != 'undefined' && comlogin == 1) { var com_openid = new JOpenID_com(); document.com_openid = openid; }; });
JavaScript
/* Script: mootree.js My Object Oriented Tree - Developed by Rasmus Schultz, <http://www.mindplay.dk> - Tested with MooTools release 1.11, under Firefox 2 and Internet Explorer 6 and 7. License: MIT-style license. Credits: Inspired by: - WebFX xTree, <http://webfx.eae.net/dhtml/xtree/> - Destroydrop dTree, <http://www.destroydrop.com/javascripts/tree/> Changes: rev.12: - load() only worked once on the same node, fixed. - the script would sometimes try to get 'R' from the server, fixed. - the 'load' attribute is now supported in XML files (see example_5.html). rev.13: - enable() and disable() added - the adopt() and load() methods use these to improve performance by minimizing the number of visual updates. rev.14: - toggle() was using enable() and disable() which actually caused it to do extra work - fixed. rev.15: - adopt() now picks up 'href', 'target', 'title' and 'name' attributes of the a-tag, and stores them in the data object. - adopt() now picks up additional constructor arguments from embedded comments, e.g. icons, colors, etc. - documentation now generates properly with NaturalDocs, <http://www.naturaldocs.org/> rev.16: - onClick events added to MooTreeControl and MooTreeNode - nodes can now have id's - <MooTreeControl.get> method can be used to find a node with a given id */ var MooTreeIcon = ['I','L','Lminus','Lplus','Rminus','Rplus','T','Tminus','Tplus','_closed','_doc','_open','minus','plus']; /* Class: MooTreeControl This class implements a tree control. Properties: root - returns the root <MooTreeNode> object. selected - returns the currently selected <MooTreeNode> object, or null if nothing is currently selected. Events: onExpand - called when a node is expanded or collapsed: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:expanded or false:collapsed. onSelect - called when a node is selected or deselected: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:selected or false:deselected. onClick - called when a node is clicked: function(node) - where node is the <MooTreeNode> object that fired the event. Parameters: The constructor takes two object parameters: config and options. The first, config, contains global settings for the tree control - you can use the configuration options listed below. The second, options, should contain options for the <MooTreeNode> constructor - please refer to the options listed in the <MooTreeNode> documentation. Config: div - a string representing the div Element inside which to build the tree control. mode - optional string, defaults to 'files' - specifies default icon behavior. In 'files' mode, empty nodes have a document icon - whereas, in 'folders' mode, all nodes are displayed as folders (a'la explorer). grid - boolean, defaults to false. If set to true, a grid is drawn to outline the structure of the tree. theme - string, optional, defaults to 'mootree.gif' - specifies the 'theme' GIF to use. loader - optional, an options object for the <MooTreeNode> constructor - defaults to {icon:'mootree_loader.gif', text:'Loading...', color:'a0a0a0'} onExpand - optional function (see Events above) onSelect - optional function (see Events above) */ var MooTreeControl = new Class({ initialize: function(config, options) { options.control = this; // make sure our new MooTreeNode knows who it's owner control is options.div = config.div; // tells the root node which div to insert itself into this.root = new MooTreeNode(options); // create the root node of this tree control this.index = new Object(); // used by the get() method this.enabled = true; // enable visual updates of the control this.theme = config.theme || 'mootree.gif'; this.loader = config.loader || {icon:'mootree_loader.gif', text:'Loading...', color:'#a0a0a0'}; this.selected = null; // set the currently selected node to nothing this.mode = config.mode; // mode can be "folders" or "files", and affects the default icons this.grid = config.grid; // grid can be turned on (true) or off (false) this.onExpand = config.onExpand || new Function(); // called when any node in the tree is expanded/collapsed this.onSelect = config.onSelect || new Function(); // called when any node in the tree is selected/deselected this.onClick = config.onClick || new Function(); // called when any node in the tree is clicked this.root.update(true); }, /* Property: insert Creates a new node under the root node of this tree. Parameters: options - an object containing the same options available to the <MooTreeNode> constructor. Returns: A new <MooTreeNode> instance. */ insert: function(options) { options.control = this; return this.root.insert(options); }, /* Property: select Sets the currently selected node. This is called by <MooTreeNode> when a node is selected (e.g. by clicking it's title with the mouse). Parameters: node - the <MooTreeNode> object to select. */ select: function(node, noClick) { if (!$chk(noClick)) { this.onClick(node); node.onClick(); // fire click events } if (this.selected === node) return; // already selected if (this.selected) { // deselect previously selected node: this.selected.select(false); this.onSelect(this.selected, false); } // select new node: this.selected = node; node.select(true); this.onSelect(node, true); }, /* Property: expand Expands the entire tree, recursively. */ expand: function() { this.root.toggle(true, true); }, /* Property: collapse Collapses the entire tree, recursively. */ collapse: function() { this.root.toggle(true, false); }, /* Property: get Retrieves the node with the given id - or null, if no node with the given id exists. Parameters: id - a string, the id of the node you wish to retrieve. Note: Node id can be assigned via the <MooTreeNode> constructor, e.g. using the <MooTreeNode.insert> method. */ get: function(id) { return this.index[id] || null; }, /* Property: adopt Adopts a structure of nested ul/li/a elements as tree nodes, then removes the original elements. Parameters: id - a string representing the ul element to be adopted, or an element reference. parentNode - optional, a <MooTreeNode> object under which to import the specified ul element. Defaults to the root node of the parent control. Note: The ul/li structure must be properly nested, and each li-element must contain one a-element, e.g.: ><ul id="mytree"> > <li><a href="test.html">Item One</a></li> > <li><a href="test.html">Item Two</a> > <ul> > <li><a href="test.html">Item Two Point One</a></li> > <li><a href="test.html">Item Two Point Two</a></li> > </ul> > </li> > <li><a href="test.html"><!-- icon:_doc; color:#ff0000 -->Item Three</a></li> ></ul> The "href", "target", "title" and "name" attributes of the a-tags are picked up and stored in the data property of the node. CSS-style comments inside a-tags are parsed, and treated as arguments for <MooTreeNode> constructor, e.g. "icon", "openicon", "color", etc. */ adopt: function(id, parentNode) { if (parentNode === undefined) parentNode = this.root; this.disable(); this._adopt(id, parentNode); parentNode.update(true); $(id).remove(); this.enable(); }, _adopt: function(id, parentNode) { /* adopts a structure of ul/li elements into this tree */ e = $(id); var i=0, c = e.getChildren(); for (i=0; i<c.length; i++) { if (c[i].nodeName == 'LI') { var con={text:''}, comment='', node=null, subul=null; var n=0, z=0, se=null, s = c[i].getChildren(); for (n=0; n<s.length; n++) { switch (s[n].nodeName) { case 'A': for (z=0; z<s[n].childNodes.length; z++) { se = s[n].childNodes[z]; switch (se.nodeName) { case '#text': con.text += se.nodeValue; break; case '#comment': comment += se.nodeValue; break; } } con.data = s[n].getProperties('href','target','title','name'); break; case 'UL': subul = s[n]; break; } } if (con.label != '') { con.data.url = con.data['href']; // (for backwards compatibility) if (comment != '') { var bits = comment.split(';'); for (z=0; z<bits.length; z++) { var pcs = bits[z].trim().split(':'); if (pcs.length == 2) con[pcs[0].trim()] = pcs[1].trim(); } } if ($chk(c[i].id)) { con.id = 'node_'+c[i].id; } node = parentNode.insert(con); if (subul) this._adopt(subul, node); } } } }, /* Property: disable Call this to temporarily disable visual updates -- if you need to insert/remove many nodes at a time, many visual updates would normally occur. By temporarily disabling the control, these visual updates will be skipped. When you're done making changes, call <MooTreeControl.enable> to turn on visual updates again, and automatically repaint all nodes that were changed. */ disable: function() { this.enabled = false; }, /* Property: enable Enables visual updates again after a call to <MooTreeControl.disable> */ enable: function() { this.enabled = true; this.root.update(true, true); } }); /* Class: MooTreeNode This class implements the functionality of a single node in a <MooTreeControl>. Note: You should not manually create objects of this class -- rather, you should use <MooTreeControl.insert> to create nodes in the root of the tree, and then use the similar function <MooTreeNode.insert> to create subnodes. Both insert methods have a similar syntax, and both return the newly created <MooTreeNode> object. Parameters: options - an object. See options below. Options: text - this is the displayed text of the node, and as such as is the only required parameter. id - string, optional - if specified, must be a unique node identifier. Nodes with id can be retrieved using the <MooTreeControl.get> method. color - string, optional - if specified, must be a six-digit hexadecimal RGB color code. open - boolean value, defaults to false. Use true if you want the node open from the start. icon - use this to customize the icon of the node. The following predefined values may be used: '_open', '_closed' and '_doc'. Alternatively, specify the URL of a GIF or PNG image to use - this should be exactly 18x18 pixels in size. If you have a strip of images, you can specify an image number (e.g. 'my_icons.gif#4' for icon number 4). openicon - use this to customize the icon of the node when it's open. data - an object containing whatever data you wish to associate with this node (such as an url and/or an id, etc.) Events: onExpand - called when the node is expanded or collapsed: function(state) - where state is a boolean meaning true:expanded or false:collapsed. onSelect - called when the node is selected or deselected: function(state) - where state is a boolean meaning true:selected or false:deselected. onClick - called when the node is clicked (no arguments). */ var MooTreeNode = new Class({ initialize: function(options) { this.text = options.text; // the text displayed by this node this.id = options.id || null; // the node's unique id this.nodes = new Array(); // subnodes nested beneath this node (MooTreeNode objects) this.parent = null; // this node's parent node (another MooTreeNode object) this.last = true; // a flag telling whether this node is the last (bottom) node of it's parent this.control = options.control; // owner control of this node's tree this.selected = false; // a flag telling whether this node is the currently selected node in it's tree this.color = options.color || null; // text color of this node this.data = options.data || {}; // optional object containing whatever data you wish to associate with the node (typically an url or an id) this.onExpand = options.onExpand || new Function(); // called when the individual node is expanded/collapsed this.onSelect = options.onSelect || new Function(); // called when the individual node is selected/deselected this.onClick = options.onClick || new Function(); // called when the individual node is clicked this.open = options.open ? true : false; // flag: node open or closed? this.icon = options.icon; this.openicon = options.openicon || this.icon; // add the node to the control's node index: if (this.id) this.control.index[this.id] = this; // create the necessary divs: this.div = { main: new Element('div').addClass('mooTree_node'), indent: new Element('div'), gadget: new Element('div'), icon: new Element('div'), text: new Element('div').addClass('mooTree_text'), sub: new Element('div') } // put the other divs under the main div: this.div.main.adopt(this.div.indent); this.div.main.adopt(this.div.gadget); this.div.main.adopt(this.div.icon); this.div.main.adopt(this.div.text); // put the main and sub divs in the specified parent div: $(options.div).adopt(this.div.main); $(options.div).adopt(this.div.sub); // attach event handler to gadget: this.div.gadget._node = this; this.div.gadget.onclick = this.div.gadget.ondblclick = function() { this._node.toggle(); } // attach event handler to icon/text: this.div.icon._node = this.div.text._node = this; this.div.icon.onclick = this.div.icon.ondblclick = this.div.text.onclick = this.div.text.ondblclick = function() { this._node.control.select(this._node); } }, /* Property: insert Creates a new node, nested inside this one. Parameters: options - an object containing the same options available to the <MooTreeNode> constructor. Returns: A new <MooTreeNode> instance. */ insert: function(options) { // set the parent div and create the node: options.div = this.div.sub; options.control = this.control; var node = new MooTreeNode(options); // set the new node's parent: node.parent = this; // mark this node's last node as no longer being the last, then add the new last node: var n = this.nodes; if (n.length) n[n.length-1].last = false; n.push(node); // repaint the new node: node.update(); // repaint the new node's parent (this node): if (n.length == 1) this.update(); // recursively repaint the new node's previous sibling node: if (n.length > 1) n[n.length-2].update(true); return node; }, /* Property: remove Removes this node, and all of it's child nodes. If you want to remove all the childnodes without removing the node itself, use <MooTreeNode.clear> */ remove: function() { var p = this.parent; this._remove(); p.update(true); }, _remove: function() { // recursively remove this node's subnodes: var n = this.nodes; while (n.length) n[n.length-1]._remove(); // remove the node id from the control's index: delete this.control.index[this.id]; // remove this node's divs: this.div.main.remove(); this.div.sub.remove(); if (this.parent) { // remove this node from the parent's collection of nodes: var p = this.parent.nodes; p.remove(this); // in case we removed the parent's last node, flag it's current last node as being the last: if (p.length) p[p.length-1].last = true; } }, /* Property: clear Removes all child nodes under this node, without removing the node itself. To remove all nodes including this one, use <MooTreeNode.remove> */ clear: function() { this.control.disable(); while (this.nodes.length) this.nodes[this.nodes.length-1].remove(); this.control.enable(); }, /* Property: update Update the tree node's visual appearance. Parameters: recursive - boolean, defaults to false. If true, recursively updates all nodes beneath this one. invalidated - boolean, defaults to false. If true, updates only nodes that have been invalidated while the control has been disabled. */ update: function(recursive, invalidated) { var draw = true; if (!this.control.enabled) { // control is currently disabled, so we don't do any visual updates this.invalidated = true; draw = false; } if (invalidated) { if (!this.invalidated) { draw = false; // this one is still valid, don't draw } else { this.invalidated = false; // we're drawing this item now } } if (draw) { var x; // make selected, or not: this.div.main.className = 'mooTree_node' + (this.selected ? ' mooTree_selected' : ''); // update indentations: x = this.div.indent; this.empty(x); var p = this, i; while (p.parent) { p = p.parent; i = this.getImg(p.last || !this.control.grid ? '' : 'I'); if (x.firstChild) { i.injectBefore( x.firstChild ); } else { x.adopt(i); } } // update the text: x = this.div.text; this.empty(x); x.appendText(this.text); if (this.color) x.style.color = this.color; // update the icon: x = this.div.icon; this.empty(x); this.getImg( this.nodes.length ? ( this.open ? (this.openicon || this.icon || '_open') : (this.icon || '_closed') ) : ( this.icon || (this.control.mode == 'folders' ? '_closed' : '_doc') ), x ); // update the plus/minus gadget: x = this.div.gadget; this.empty(x); this.getImg( ( this.control.grid ? ( this.control.root == this ? (this.nodes.length ? 'R' : '') : (this.last?'L':'T') ) : '') + (this.nodes.length ? (this.open?'minus':'plus') : ''), x ); // show/hide subnodes: this.div.sub.style.display = this.open ? 'block' : 'none'; } // if recursively updating, update all child nodes: if (recursive) this.nodes.forEach( function(node) { node.update(true, invalidated); }); }, /* Property: getImg Creates a new image (actually, a div Element) -- or turns a given div into an image. You should not need to manually call this method. (though if for some reason you want to, you can) Parameters: name - the name of new image to create, defined by <MooTreeIcon> or located in an external file. div - optional. A string representing an existing div element to be turned into an image, or an element reference. Returns: The new div Element. */ getImg: function(name, div) { // if no div was specified, create a new one: if (div === undefined) div = new Element('div'); // apply the mooTree_img CSS class: div.addClass('mooTree_img'); // if a blank image was requested, simply return it now: if (name == '') return div; var img = this.control.theme; var i = MooTreeIcon.indexOf(name); if (i == -1) { // custom (external) icon: var x = name.split('#'); img = x[0]; i = (x.length == 2 ? parseInt(x[1])-1 : 0); } div.style.backgroundImage = 'url(' + img + ')'; div.style.backgroundPosition = '-' + (i*18) + 'px 0px'; return div; }, /* Property: toggle By default (with no arguments) this function toggles the node between expanded/collapsed. Can also be used to recursively expand/collapse all or part of the tree. Parameters: recursive - boolean, defaults to false. With recursive set to true, all child nodes are recursively toggle to this node's new state. state - boolean. If undefined, the node's state is toggled. If true or false, the node can be explicitly opened or closed. */ toggle: function(recursive, state) { this.open = (state === undefined ? !this.open : state); this.update(); this.onExpand(this.open); this.control.onExpand(this, this.open); if (recursive) this.nodes.forEach( function(node) { node.toggle(true, this.open); }, this); }, /* Property: select Called by <MooTreeControl> when the selection changes. You should not manually call this method - to set the selection, use the <MooTreeControl.select> method. */ select: function(state) { this.selected = state; this.update(); this.onSelect(state); }, /* Property: load Asynchronously load an XML structure into a node of this tree. Parameters: url - string, required, specifies the URL from which to load the XML document. vars - query string, optional. */ load: function(url, vars) { if (this.loading) return; // if this node is already loading, return this.loading = true; // flag this node as loading this.toggle(false, true); // expand the node to make the loader visible this.clear(); this.insert(this.control.loader); var f = function() { new XHR({ method: 'GET', onSuccess: this._loaded.bind(this), onFailure: this._load_err.bind(this) }).send(url, vars || ''); }; window.setTimeout(f.bind(this), 20); // allowing a small delay for the browser to draw the loader-icon. }, _loaded: function(text, xml) { // called on success - import nodes from the root element: this.control.disable(); this.clear(); this._import(xml.documentElement); this.control.enable(); this.loading = false; }, _import: function(e) { // import childnodes from an xml element: var n = e.childNodes; for (var i=0; i<n.length; i++) if (n[i].tagName == 'node') { var opt = {data:{}}; var a = n[i].attributes; for (var t=0; t<a.length; t++) { switch (a[t].name) { case 'text': case 'id': case 'icon': case 'openicon': case 'color': case 'open': opt[a[t].name] = a[t].value; break; default: opt.data[a[t].name] = a[t].value; } } var node = this.insert(opt); if (node.data.load) { node.open = false; // can't have a dynamically loading node that's already open! node.insert(this.control.loader); node.onExpand = function(state) { this.load(this.data.load); this.onExpand = new Function(); } } // recursively import subnodes of this node: if (n[i].childNodes.length) node._import(n[i]); } }, _load_err: function(req) { window.alert('Error loading: ' + this.text); }, /* Property: empty Utility function, used to clear the contents of an Element. */ empty: function(e) { while (e.lastChild) e.removeChild(e.lastChild); } });
JavaScript
/** * @version $Id: modal.js 5263 2006-10-02 01:25:24Z webImagery $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JCombobox javascript behavior * * Used for transforming <input type="text" ... /> tags into combobox dropdowns with appropriate <noscript> tag following * for dropdown list information * * @package Joomla * @since 1.5 * @version 1.0 */ var JCombobox = function() { this.constructor.apply(this, arguments);} JCombobox.prototype = { constructor: function() { var agt = navigator.userAgent.toLowerCase(); this.is_ie = (agt.indexOf("msie") != -1); this.is_opera = (agt.indexOf("opera") != -1); this.is_safari = (agt.indexOf("safari") != -1); var boxes = document.getElements('.combobox'); for ( var i=0; i < boxes.length; i++) { if (boxes[i].tagName == 'INPUT' && boxes[i].type == 'text') { this.populate(boxes[i]); } } }, populate: function(element) { var list = document.getElementById('combobox-'+element.id).getElementsByTagName('LI'); var select = document.createElement("select"); select.setAttribute('id','combobox-'+element.id+'-select'); for ( var i=0; i < list.length; i++) { // Do population bit here var o = document.createElement('option'); o.value = list[i].innerHTML; o.innerHTML = list[i].innerHTML; if (o.value == element.value) { o.selected = selected; } select.appendChild(o); } select.inputbox = element.id; select.onchange = function(){ var input = document.getElementById(this.inputbox); input.value = this.options[this.selectedIndex].value; } element.parentNode.insertBefore(select, element); var coords = this.getCoords(select); var widthOffset = 20; var heightOffset = 4; if (this.is_ie) { coords.x = coords.x + 2; widthOffset = 22; heightOffset = 5; } if (this.is_opera) { widthOffset = 19; heightOffset = 4; } if (this.is_safari) { coords.y = coords.y - 2; coords.x = coords.x + 2; widthOffset = 18; heightOffset = 0; } // Set text field properties based on the select box element.style.position = 'absolute'; element.style.top = coords.y + 'px'; element.style.left = coords.x + 'px'; element.style.width = select.offsetWidth - widthOffset + 'px'; element.style.height = select.offsetHeight - heightOffset + 'px'; element.style.zIndex = 1000; // Add iFrame for IE if (this.is_ie) { var iframe = document.createElement('iframe'); iframe.src = 'about:blank'; iframe.scrolling = 'no'; iframe.frameborder = '0'; iframe.style.position = 'absolute'; iframe.style.top = coords.y + 'px'; iframe.style.left = coords.x + 'px'; iframe.style.width = element.offsetWidth + 'px'; iframe.style.height = element.offsetHeight + 'px'; element.parentNode.insertBefore(iframe, element); } }, getCoords: function(el) { var coords = { x: 0, y: 0 }; while (el) { coords.x += el.offsetLeft; coords.y += el.offsetTop; el = el.offsetParent; } return coords; } } document.combobox = null Window.onDomReady(function(){ var combobox = new JCombobox() document.combobox = combobox });
JavaScript
/** * SqueezeBox - Expandable Lightbox * * Allows to open various content as modal, * centered and animated box. * * Inspired by * ... Lokesh Dhakar - The original Lightbox v2 * ... Cody Lindley - ThickBox * * @version 1.0rc1 * * @license MIT-style license * @author Harald Kirschner <mail [at] digitarald.de> * @copyright Author */ var SqueezeBox = { presets: { size: {x: 600, y: 450}, sizeLoading: {x: 200, y: 150}, marginInner: {x: 20, y: 20}, marginImage: {x: 150, y: 200}, handler: false, adopt: null, closeWithOverlay: true, zIndex: 65555, overlayOpacity: 0.7, classWindow: '', classOverlay: '', disableFx: false, onOpen: Class.empty, onClose: Class.empty, onUpdate: Class.empty, onResize: Class.empty, onMove: Class.empty, onShow: Class.empty, onHide: Class.empty, fxOverlayDuration: 250, fxResizeDuration: 750, fxContentDuration: 250, ajaxOptions: {} }, initialize: function(options) { if (this.options) return this; this.presets = $merge(this.presets, options) this.setOptions(this.presets); this.build(); this.listeners = { window: this.reposition.bind(this, [null]), close: this.close.bind(this), key: this.onkeypress.bind(this)}; this.isOpen = this.isLoading = false; this.window.close = this.listeners.close; return this; }, build: function() { this.overlay = new Element('div', { id: 'sbox-overlay', styles: { display: 'none', zIndex: this.options.zIndex } }); this.content = new Element('div', { id: 'sbox-content' }); this.btnClose = new Element('a', { id: 'sbox-btn-close', href: '#' }); this.window = new Element('div', { id: 'sbox-window', styles: { display: 'none', zIndex: this.options.zIndex + 2 } }).adopt(this.btnClose, this.content); if (!window.ie6) { this.overlay.setStyles({ position: 'fixed', top: 0, left: 0 }); this.window.setStyles({ position: 'fixed', top: '50%', left: '50%' }); } else { this.overlay.style.setExpression('marginTop', 'document.documentElement.scrollTop + "px"'); this.window.style.setExpression('marginTop', '0 - parseInt(this.offsetHeight / 2) + document.documentElement.scrollTop + "px"'); this.overlay.setStyles({ position: 'absolute', top: '0%', left: '0%' //,marginTop: "expression(document.documentElement.scrollTop + 'px')" }); this.window.setStyles({ position: 'absolute', top: '0%', left: '0%' //,marginTop: "(expression(0 - parseInt(this.offsetHeight / 2) + document.documentElement.scrollTop + 'px')" }); } $(document.body).adopt(this.overlay, this.window); this.fx = { overlay: this.overlay.effect('opacity', { duration: this.options.fxOverlayDuration, wait: false}).set(0), window: this.window.effects({ duration: this.options.fxResizeDuration, wait: false}), content: this.content.effect('opacity', { duration: this.options.fxContentDuration, wait: false}).set(0) }; }, addClick: function(el) { return el.addEvent('click', function() { if (this.fromElement(el)) return false; }.bind(this)); }, fromElement: function(el, options) { this.initialize(); this.element = $(el); if (this.element && this.element.rel) options = $merge(options || {}, Json.evaluate(this.element.rel)); this.setOptions(this.presets, options); this.assignOptions(); this.url = (this.element ? (this.options.url || this.element.href) : el) || ''; if (this.options.handler) { var handler = this.options.handler; return this.setContent(handler, this.parsers[handler].call(this, true)); } var res = false; for (var key in this.parsers) { if ((res = this.parsers[key].call(this))) return this.setContent(key, res); } return this; }, assignOptions: function() { this.overlay.setProperty('class', this.options.classOverlay); this.window.setProperty('class', this.options.classWindow); }, close: function(e) { if (e) new Event(e).stop(); if (!this.isOpen) return this; this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this)); this.window.setStyle('display', 'none'); this.trashImage(); this.toggleListeners(); this.isOpen = null; this.fireEvent('onClose', [this.content]).removeEvents(); this.options = {}; this.setOptions(this.presets).callChain(); return this; }, onError: function() { if (this.image) this.trashImage(); this.setContent('Error during loading'); }, trashImage: function() { if (this.image) this.image = this.image.onload = this.image.onerror = this.image.onabort = null; }, setContent: function(handler, content) { this.content.setProperty('class', 'sbox-content-' + handler); this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, [this.handlers[handler].call(this, content)]); if (this.overlay.opacity) return this; this.toggleOverlay(true); this.fx.overlay.start(this.options.overlayOpacity); this.reposition(); return this; }, applyContent: function(content, size) { this.applyTimer = $clear(this.applyTimer); this.hideContent(); if (!content) this.toggleLoading(true); else { if (this.isLoading) this.toggleLoading(false); this.fireEvent('onUpdate', [this.content], 20); } this.content.empty()[['string', 'array', false].contains($type(content)) ? 'setHTML' : 'adopt'](content || ''); this.callChain(); if (!this.isOpen) { this.toggleListeners(true); this.resize(size, true); this.isOpen = true; this.fireEvent('onOpen', [this.content]); } else this.resize(size); }, resize: function(size, instantly) { var sizes = window.getSize(); this.size = $merge(this.isLoading ? this.options.sizeLoading : this.options.size, size); var to = { width: this.size.x, height: this.size.y, marginLeft: - this.size.x / 2, marginTop: - this.size.y / 2 //left: (sizes.scroll.x + (sizes.size.x - this.size.x - this.options.marginInner.x) / 2).toInt(), //top: (sizes.scroll.y + (sizes.size.y - this.size.y - this.options.marginInner.y) / 2).toInt() }; $clear(this.showTimer || null); this.hideContent(); if (!instantly) this.fx.window.start(to).chain(this.showContent.bind(this)); else { this.window.setStyles(to).setStyle('display', ''); this.showTimer = this.showContent.delay(50, this); } this.reposition(sizes); }, toggleListeners: function(state) { var task = state ? 'addEvent' : 'removeEvent'; this.btnClose[task]('click', this.listeners.close); if (this.options.closeWithOverlay) this.overlay[task]('click', this.listeners.close); document[task]('keydown', this.listeners.key); window[task]('resize', this.listeners.window); window[task]('scroll', this.listeners.window); }, toggleLoading: function(state) { this.isLoading = state; this.window[state ? 'addClass' : 'removeClass']('sbox-loading'); if (state) this.fireEvent('onLoading', [this.window]); }, toggleOverlay: function(state) { this.overlay.setStyle('display', state ? '' : 'none'); $(document.body)[state ? 'addClass' : 'removeClass']('body-overlayed'); }, showContent: function() { if (this.content.opacity) this.fireEvent('onShow', [this.window]); this.fx.content.start(1); }, hideContent: function() { if (!this.content.opacity) this.fireEvent('onHide', [this.window]); this.fx.content.stop().set(0); }, onkeypress: function(e) { switch (e.key) { case 'esc': case 'x': this.close(); break; } }, reposition: function(sizes) { sizes = sizes || window.getSize(); this.overlay.setStyles({ //'left': sizes.scroll.x, 'top': sizes.scroll.y, width: sizes.size.x, height: sizes.size.y }); /* this.window.setStyles({ left: (sizes.scroll.x + (sizes.size.x - this.window.offsetWidth) / 2).toInt(), top: (sizes.scroll.y + (sizes.size.y - this.window.offsetHeight) / 2).toInt() }); */ this.fireEvent('onMove', [this.overlay, this.window, sizes]); }, removeEvents: function(type){ if (!this.$events) return this; if (!type) this.$events = null; else if (this.$events[type]) this.$events[type] = null; return this; }, parsers: { 'image': function(preset) { return (preset || this.url.test(/\.(jpg|jpeg|png|gif|bmp)$/i)) ? this.url : false; }, 'adopt': function(preset) { if ($(this.options.adopt)) return $(this.options.adopt); if (preset || ($(this.element) && !this.element.parentNode)) return $(this.element); var bits = this.url.match(/#([\w-]+)$/); return bits ? $(bits[1]) : false; }, 'url': function(preset) { return (preset || (this.url && !this.url.test(/^javascript:/i))) ? this.url: false; }, 'iframe': function(preset) { return (preset || this.url) ? this.url: false; }, 'string': function(preset) { return true; } }, handlers: { 'image': function(url) { this.image = new Image(); var events = { loaded: function() { var win = {x: window.getWidth() - this.options.marginImage.x, y: window.getHeight() - this.options.marginImage.y}; var size = {x: this.image.width, y: this.image.height}; for (var i = 0; i < 2; i++) if (size.x > win.x) { size.y *= win.x / size.x; size.x = win.x; } else if (size.y > win.y) { size.x *= win.y / size.y; size.y = win.y; } size = {x: parseInt(size.x), y: parseInt(size.y)}; if (window.webkit419) this.image = new Element('img', {'src': this.image.src}); else $(this.image); this.image.setProperties({ 'width': size.x, 'height': size.y}); this.applyContent(this.image, size); }.bind(this), failed: this.onError.bind(this) }; (function() { this.src = url; }).delay(10, this.image); this.image.onload = events.loaded; this.image.onerror = this.image.onabort = events.failed; }, 'adopt': function(el) { return el.clone(); }, 'url': function(url) { this.ajax = new Ajax(url, this.options.ajaxOptions); this.ajax.addEvent('onSuccess', function(resp) { this.applyContent(resp); this.ajax = null; }.bind(this)); this.ajax.addEvent('onFailure', this.onError.bind(this)); this.ajax.request.delay(10, this.ajax); }, 'iframe': function(url) { return new Element('iframe', { 'src': url, 'frameBorder': 0, 'width': this.options.size.x, 'height': this.options.size.y }); }, 'string': function(str) { return str; } }, extend: $extend }; SqueezeBox.extend(Events.prototype); SqueezeBox.extend(Options.prototype); SqueezeBox.extend(Chain.prototype);
JavaScript
/** * @version $Id: validate.js 7401 2007-05-14 04:12:55Z eddieajau $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * Unobtrusive Form Validation library * * Inspired by: Chris Campbell <www.particletree.com> * * @package Joomla.Framework * @subpackage Forms * @since 1.5 */ var JFormValidator = new Class({ initialize: function() { // Initialize variables this.handlers = Object(); this.custom = Object(); // Default handlers this.setHandler('username', function (value) { regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i"); return !regex.test(value); } ); this.setHandler('password', function (value) { regex=/^\S[\S ]{2,98}\S$/; return regex.test(value); } ); this.setHandler('numeric', function (value) { regex=/^(\d|-)?(\d|,)*\.?\d*$/; return regex.test(value); } ); this.setHandler('email', function (value) { regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/; return regex.test(value); } ); // Attach to forms with class 'form-validate' var forms = $$('form.form-validate'); forms.each(function(form){ this.attachToForm(form); }, this); }, setHandler: function(name, fn, en) { en = (en == '') ? true : en; this.handlers[name] = { enabled: en, exec: fn }; }, attachToForm: function(form) { // Iterate through the form object and attach the validate method to all input fields. $A(form.elements).each(function(el){ el = $(el); if ((el.getTag() == 'input' || el.getTag() == 'button') && el.getProperty('type') == 'submit') { if (el.hasClass('validate')) { el.onclick = function(){return document.formvalidator.isValid(this.form);}; } } else { el.addEvent('blur', function(){return document.formvalidator.validate(this);}); } }); }, validate: function(el) { // If the field is required make sure it has a value if ($(el).hasClass('required')) { if (!($(el).getValue())) { this.handleResponse(false, el); return false; } } // Only validate the field if the validate class is set var handler = (el.className && el.className.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? el.className.match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : ""; if (handler == '') { this.handleResponse(true, el); return true; } // Check the additional validation types if ((handler) && (handler != 'none') && (this.handlers[handler]) && $(el).getValue()) { // Execute the validation handler and return result if (this.handlers[handler].exec($(el).getValue()) != true) { this.handleResponse(false, el); return false; } } // Return validation state this.handleResponse(true, el); return true; }, isValid: function(form) { var valid = true; // Validate form fields for (var i=0;i < form.elements.length; i++) { if (this.validate(form.elements[i]) == false) { valid = false; } } // Run custom form validators if present $A(this.custom).each(function(validator){ if (validator.exec() != true) { valid = false; } }); return valid; }, handleResponse: function(state, el) { // Find the label object for the given field if it exists if (!(el.labelref)) { var labels = $$('label'); labels.each(function(label){ if (label.getProperty('for') == el.getProperty('id')) { el.labelref = label; } }); } // Set the element and its label (if exists) invalid state if (state == false) { el.addClass('invalid'); if (el.labelref) { $(el.labelref).addClass('invalid'); } } else { el.removeClass('invalid'); if (el.labelref) { $(el.labelref).removeClass('invalid'); } } } }); document.formvalidator = null; Window.onDomReady(function(){ document.formvalidator = new JFormValidator(); });
JavaScript
/* Script: Core.js Mootools - My Object Oriented javascript. License: MIT-style license. MooTools Copyright: copyright (c) 2007 Valerio Proietti, <http://mad4milk.net> MooTools Credits: - Class is slightly based on Base.js <http://dean.edwards.name/weblog/2006/03/base/> (c) 2006 Dean Edwards, License <http://creativecommons.org/licenses/LGPL/2.1/> - Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license - Documentation by Aaron Newton (aaron.newton [at] cnet [dot] com) and Valerio Proietti. */ var MooTools = { version: '1.12' }; /* Section: Core Functions */ /* Function: $defined Returns true if the passed in value/object is defined, that means is not null or undefined. Arguments: obj - object to inspect */ function $defined(obj){ return (obj != undefined); }; /* Function: $type Returns the type of object that matches the element passed in. Arguments: obj - the object to inspect. Example: >var myString = 'hello'; >$type(myString); //returns "string" Returns: 'element' - if obj is a DOM element node 'textnode' - if obj is a DOM text node 'whitespace' - if obj is a DOM whitespace node 'arguments' - if obj is an arguments object 'object' - if obj is an object 'string' - if obj is a string 'number' - if obj is a number 'boolean' - if obj is a boolean 'function' - if obj is a function 'regexp' - if obj is a regular expression 'class' - if obj is a Class. (created with new Class, or the extend of another class). 'collection' - if obj is a native htmlelements collection, such as childNodes, getElementsByTagName .. etc. false - (boolean) if the object is not defined or none of the above. */ function $type(obj){ if (!$defined(obj)) return false; if (obj.htmlElement) return 'element'; var type = typeof obj; if (type == 'object' && obj.nodeName){ switch(obj.nodeType){ case 1: return 'element'; case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace'; } } if (type == 'object' || type == 'function'){ switch(obj.constructor){ case Array: return 'array'; case RegExp: return 'regexp'; case Class: return 'class'; } if (typeof obj.length == 'number'){ if (obj.item) return 'collection'; if (obj.callee) return 'arguments'; } } return type; }; /* Function: $merge merges a number of objects recursively without referencing them or their sub-objects. Arguments: any number of objects. Example: >var mergedObj = $merge(obj1, obj2, obj3); >//obj1, obj2, and obj3 are unaltered */ function $merge(){ var mix = {}; for (var i = 0; i < arguments.length; i++){ for (var property in arguments[i]){ var ap = arguments[i][property]; var mp = mix[property]; if (mp && $type(ap) == 'object' && $type(mp) == 'object') mix[property] = $merge(mp, ap); else mix[property] = ap; } } return mix; }; /* Function: $extend Copies all the properties from the second passed object to the first passed Object. If you do myWhatever.extend = $extend the first parameter will become myWhatever, and your extend function will only need one parameter. Example: (start code) var firstOb = { 'name': 'John', 'lastName': 'Doe' }; var secondOb = { 'age': '20', 'sex': 'male', 'lastName': 'Dorian' }; $extend(firstOb, secondOb); //firstOb will become: { 'name': 'John', 'lastName': 'Dorian', 'age': '20', 'sex': 'male' }; (end) Returns: The first object, extended. */ var $extend = function(){ var args = arguments; if (!args[1]) args = [this, args[0]]; for (var property in args[1]) args[0][property] = args[1][property]; return args[0]; }; /* Function: $native Will add a .extend method to the objects passed as a parameter, but the property passed in will be copied to the object's prototype only if non previously existent. Its handy if you dont want the .extend method of an object to overwrite existing methods. Used automatically in MooTools to implement Array/String/Function/Number methods to browser that dont support them whitout manual checking. Arguments: a number of classes/native javascript objects */ var $native = function(){ for (var i = 0, l = arguments.length; i < l; i++){ arguments[i].extend = function(props){ for (var prop in props){ if (!this.prototype[prop]) this.prototype[prop] = props[prop]; if (!this[prop]) this[prop] = $native.generic(prop); } }; } }; $native.generic = function(prop){ return function(bind){ return this.prototype[prop].apply(bind, Array.prototype.slice.call(arguments, 1)); }; }; $native(Function, Array, String, Number); /* Function: $chk Returns true if the passed in value/object exists or is 0, otherwise returns false. Useful to accept zeroes. Arguments: obj - object to inspect */ function $chk(obj){ return !!(obj || obj === 0); }; /* Function: $pick Returns the first object if defined, otherwise returns the second. Arguments: obj - object to test picked - the default to return Example: (start code) function say(msg){ alert($pick(msg, 'no meessage supplied')); } (end) */ function $pick(obj, picked){ return $defined(obj) ? obj : picked; }; /* Function: $random Returns a random integer number between the two passed in values. Arguments: min - integer, the minimum value (inclusive). max - integer, the maximum value (inclusive). Returns: a random integer between min and max. */ function $random(min, max){ return Math.floor(Math.random() * (max - min + 1) + min); }; /* Function: $time Returns the current timestamp Returns: a timestamp integer. */ function $time(){ return new Date().getTime(); }; /* Function: $clear clears a timeout or an Interval. Returns: null Arguments: timer - the setInterval or setTimeout to clear. Example: >var myTimer = myFunction.delay(5000); //wait 5 seconds and execute my function. >myTimer = $clear(myTimer); //nevermind See also: <Function.delay>, <Function.periodical> */ function $clear(timer){ clearTimeout(timer); clearInterval(timer); return null; }; /* Class: Abstract Abstract class, to be used as singleton. Will add .extend to any object Arguments: an object Returns: the object with an .extend property, equivalent to <$extend>. */ var Abstract = function(obj){ obj = obj || {}; obj.extend = $extend; return obj; }; //window, document var Window = new Abstract(window); var Document = new Abstract(document); document.head = document.getElementsByTagName('head')[0]; /* Class: window Some properties are attached to the window object by the browser detection. Note: browser detection is entirely object-based. We dont sniff. Properties: window.ie - will be set to true if the current browser is internet explorer (any). window.ie6 - will be set to true if the current browser is internet explorer 6. window.ie7 - will be set to true if the current browser is internet explorer 7. window.gecko - will be set to true if the current browser is Mozilla/Gecko. window.webkit - will be set to true if the current browser is Safari/Konqueror. window.webkit419 - will be set to true if the current browser is Safari2 / webkit till version 419. window.webkit420 - will be set to true if the current browser is Safari3 (Webkit SVN Build) / webkit over version 419. window.opera - is set to true by opera itself. */ window.xpath = !!(document.evaluate); if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true; else if (document.childNodes && !document.all && !navigator.taintEnabled) window.webkit = window[window.xpath ? 'webkit420' : 'webkit419'] = true; else if (document.getBoxObjectFor != null || window.mozInnerScreenX != null) window.gecko = true; /*compatibility*/ window.khtml = window.webkit; Object.extend = $extend; /*end compatibility*/ //htmlelement if (typeof HTMLElement == 'undefined'){ var HTMLElement = function(){}; if (window.webkit) document.createElement("iframe"); //fixes safari HTMLElement.prototype = (window.webkit) ? window["[[DOMElement.prototype]]"] : {}; } HTMLElement.prototype.htmlElement = function(){}; //enables background image cache for internet explorer 6 if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){}; /* Script: Class.js Contains the Class Function, aims to ease the creation of reusable Classes. License: MIT-style license. */ /* Class: Class The base class object of the <http://mootools.net> framework. Creates a new class, its initialize method will fire upon class instantiation. Initialize wont fire on instantiation when you pass *null*. Arguments: properties - the collection of properties that apply to the class. Example: (start code) var Cat = new Class({ initialize: function(name){ this.name = name; } }); var myCat = new Cat('Micia'); alert(myCat.name); //alerts 'Micia' (end) */ var Class = function(properties){ var klass = function(){ return (arguments[0] !== null && this.initialize && $type(this.initialize) == 'function') ? this.initialize.apply(this, arguments) : this; }; $extend(klass, this); klass.prototype = properties; klass.constructor = Class; return klass; }; /* Property: empty Returns an empty function */ Class.empty = function(){}; Class.prototype = { /* Property: extend Returns the copy of the Class extended with the passed in properties. Arguments: properties - the properties to add to the base class in this new Class. Example: (start code) var Animal = new Class({ initialize: function(age){ this.age = age; } }); var Cat = Animal.extend({ initialize: function(name, age){ this.parent(age); //will call the previous initialize; this.name = name; } }); var myCat = new Cat('Micia', 20); alert(myCat.name); //alerts 'Micia' alert(myCat.age); //alerts 20 (end) */ extend: function(properties){ var proto = new this(null); for (var property in properties){ var pp = proto[property]; proto[property] = Class.Merge(pp, properties[property]); } return new Class(proto); }, /* Property: implement Implements the passed in properties to the base Class prototypes, altering the base class, unlike <Class.extend>. Arguments: properties - the properties to add to the base class. Example: (start code) var Animal = new Class({ initialize: function(age){ this.age = age; } }); Animal.implement({ setName: function(name){ this.name = name } }); var myAnimal = new Animal(20); myAnimal.setName('Micia'); alert(myAnimal.name); //alerts 'Micia' (end) */ implement: function(){ for (var i = 0, l = arguments.length; i < l; i++) $extend(this.prototype, arguments[i]); } }; //internal Class.Merge = function(previous, current){ if (previous && previous != current){ var type = $type(current); if (type != $type(previous)) return current; switch(type){ case 'function': var merged = function(){ this.parent = arguments.callee.parent; return current.apply(this, arguments); }; merged.parent = previous; return merged; case 'object': return $merge(previous, current); } } return current; }; /* Script: Class.Extras.js Contains common implementations for custom classes. In Mootools is implemented in <Ajax>, <XHR> and <Fx.Base> and many more. License: MIT-style license. */ /* Class: Chain An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>. Currently implemented in <Fx.Base>, <XHR> and <Ajax>. In <Fx.Base> for example, is used to execute a list of function, one after another, once the effect is completed. The functions will not be fired all togheter, but one every completion, to create custom complex animations. Example: (start code) var myFx = new Fx.Style('element', 'opacity'); myFx.start(1,0).chain(function(){ myFx.start(0,1); }).chain(function(){ myFx.start(1,0); }).chain(function(){ myFx.start(0,1); }); //the element will appear and disappear three times (end) */ var Chain = new Class({ /* Property: chain adds a function to the Chain instance stack. Arguments: fn - the function to append. */ chain: function(fn){ this.chains = this.chains || []; this.chains.push(fn); return this; }, /* Property: callChain Executes the first function of the Chain instance stack, then removes it. The first function will then become the second. */ callChain: function(){ if (this.chains && this.chains.length) this.chains.shift().delay(10, this); }, /* Property: clearChain Clears the stack of a Chain instance. */ clearChain: function(){ this.chains = []; } }); /* Class: Events An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>. In <Fx.Base> Class, for example, is used to give the possibility add any number of functions to the Effects events, like onComplete, onStart, onCancel. Events in a Class that implements <Events> can be either added as an option, or with addEvent. Never with .options.onEventName. Example: (start code) var myFx = new Fx.Style('element', 'opacity').addEvent('onComplete', function(){ alert('the effect is completed'); }).addEvent('onComplete', function(){ alert('I told you the effect is completed'); }); myFx.start(0,1); //upon completion it will display the 2 alerts, in order. (end) Implementing: This class can be implemented into other classes to add the functionality to them. Goes well with the <Options> class. Example: (start code) var Widget = new Class({ initialize: function(){}, finish: function(){ this.fireEvent('onComplete'); } }); Widget.implement(new Events); //later... var myWidget = new Widget(); myWidget.addEvent('onComplete', myfunction); (end) */ var Events = new Class({ /* Property: addEvent adds an event to the stack of events of the Class instance. Arguments: type - string; the event name (e.g. 'onComplete') fn - function to execute */ addEvent: function(type, fn){ if (fn != Class.empty){ this.$events = this.$events || {}; this.$events[type] = this.$events[type] || []; this.$events[type].include(fn); } return this; }, /* Property: fireEvent fires all events of the specified type in the Class instance. Arguments: type - string; the event name (e.g. 'onComplete') args - array or single object; arguments to pass to the function; if more than one argument, must be an array delay - (integer) delay (in ms) to wait to execute the event Example: (start code) var Widget = new Class({ initialize: function(arg1, arg2){ ... this.fireEvent("onInitialize", [arg1, arg2], 50); } }); Widget.implement(new Events); (end) */ fireEvent: function(type, args, delay){ if (this.$events && this.$events[type]){ this.$events[type].each(function(fn){ fn.create({'bind': this, 'delay': delay, 'arguments': args})(); }, this); } return this; }, /* Property: removeEvent removes an event from the stack of events of the Class instance. Arguments: type - string; the event name (e.g. 'onComplete') fn - function that was added */ removeEvent: function(type, fn){ if (this.$events && this.$events[type]) this.$events[type].remove(fn); return this; } }); /* Class: Options An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>. Used to automate the options settings, also adding Class <Events> when the option begins with on. Example: (start code) var Widget = new Class({ options: { color: '#fff', size: { width: 100 height: 100 } }, initialize: function(options){ this.setOptions(options); } }); Widget.implement(new Options); //later... var myWidget = new Widget({ color: '#f00', size: { width: 200 } }); //myWidget.options = {color: #f00, size: {width: 200, height: 100}} (end) */ var Options = new Class({ /* Property: setOptions sets this.options Arguments: defaults - object; the default set of options options - object; the user entered options. can be empty too. Note: if your Class has <Events> implemented, every option beginning with on, followed by a capital letter (onComplete) becomes an Class instance event. */ setOptions: function(){ this.options = $merge.apply(null, [this.options].extend(arguments)); if (this.addEvent){ for (var option in this.options){ if ($type(this.options[option] == 'function') && (/^on[A-Z]/).test(option)) this.addEvent(option, this.options[option]); } } return this; } }); /* Script: Array.js Contains Array prototypes, <$A>, <$each> License: MIT-style license. */ /* Class: Array A collection of The Array Object prototype methods. */ //custom methods Array.extend({ /* Property: forEach Iterates through an array; This method is only available for browsers without native *forEach* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:forEach> *forEach* executes the provided function (callback) once for each element present in the array. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Arguments: fn - function to execute with each item in the array; passed the item and the index of that item in the array bind - the object to bind "this" to (see <Function.bind>) Example: >['apple','banana','lemon'].each(function(item, index){ > alert(index + " = " + item); //alerts "0 = apple" etc. >}, bindObj); //optional second arg for binding, not used here */ forEach: function(fn, bind){ for (var i = 0, j = this.length; i < j; i++) fn.call(bind, this[i], i, this); }, /* Property: filter This method is provided only for browsers without native *filter* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:filter> *filter* calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array. Arguments: fn - function to execute with each item in the array; passed the item and the index of that item in the array bind - the object to bind "this" to (see <Function.bind>) Example: >var biggerThanTwenty = [10,3,25,100].filter(function(item, index){ > return item > 20; >}); >//biggerThanTwenty = [25,100] */ filter: function(fn, bind){ var results = []; for (var i = 0, j = this.length; i < j; i++){ if (fn.call(bind, this[i], i, this)) results.push(this[i]); } return results; }, /* Property: map This method is provided only for browsers without native *map* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:map> *map* calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Arguments: fn - function to execute with each item in the array; passed the item and the index of that item in the array bind - the object to bind "this" to (see <Function.bind>) Example: >var timesTwo = [1,2,3].map(function(item, index){ > return item*2; >}); >//timesTwo = [2,4,6]; */ map: function(fn, bind){ var results = []; for (var i = 0, j = this.length; i < j; i++) results[i] = fn.call(bind, this[i], i, this); return results; }, /* Property: every This method is provided only for browsers without native *every* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:every> *every* executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Arguments: fn - function to execute with each item in the array; passed the item and the index of that item in the array bind - the object to bind "this" to (see <Function.bind>) Example: >var areAllBigEnough = [10,4,25,100].every(function(item, index){ > return item > 20; >}); >//areAllBigEnough = false */ every: function(fn, bind){ for (var i = 0, j = this.length; i < j; i++){ if (!fn.call(bind, this[i], i, this)) return false; } return true; }, /* Property: some This method is provided only for browsers without native *some* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:some> *some* executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some immediately returns true. Otherwise, some returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Arguments: fn - function to execute with each item in the array; passed the item and the index of that item in the array bind - the object to bind "this" to (see <Function.bind>) Example: >var isAnyBigEnough = [10,4,25,100].some(function(item, index){ > return item > 20; >}); >//isAnyBigEnough = true */ some: function(fn, bind){ for (var i = 0, j = this.length; i < j; i++){ if (fn.call(bind, this[i], i, this)) return true; } return false; }, /* Property: indexOf This method is provided only for browsers without native *indexOf* support. For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf> *indexOf* compares a search element to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator). Arguments: item - any type of object; element to locate in the array from - integer; optional; the index of the array at which to begin the search (defaults to 0) Example: >['apple','lemon','banana'].indexOf('lemon'); //returns 1 >['apple','lemon'].indexOf('banana'); //returns -1 */ indexOf: function(item, from){ var len = this.length; for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){ if (this[i] === item) return i; } return -1; }, /* Property: each Same as <Array.forEach>. Arguments: fn - function to execute with each item in the array; passed the item and the index of that item in the array bind - optional, the object that the "this" of the function will refer to. Example: >var Animals = ['Cat', 'Dog', 'Coala']; >Animals.each(function(animal){ > document.write(animal) >}); */ /* Property: copy returns a copy of the array. Returns: a new array which is a copy of the current one. Arguments: start - integer; optional; the index where to start the copy, default is 0. If negative, it is taken as the offset from the end of the array. length - integer; optional; the number of elements to copy. By default, copies all elements from start to the end of the array. Example: >var letters = ["a","b","c"]; >var copy = letters.copy(); // ["a","b","c"] (new instance) */ copy: function(start, length){ start = start || 0; if (start < 0) start = this.length + start; length = length || (this.length - start); var newArray = []; for (var i = 0; i < length; i++) newArray[i] = this[start++]; return newArray; }, /* Property: remove Removes all occurrences of an item from the array. Arguments: item - the item to remove Returns: the Array with all occurrences of the item removed. Example: >["1","2","3","2"].remove("2") // ["1","3"]; */ remove: function(item){ var i = 0; var len = this.length; while (i < len){ if (this[i] === item){ this.splice(i, 1); len--; } else { i++; } } return this; }, /* Property: contains Tests an array for the presence of an item. Arguments: item - the item to search for in the array. from - integer; optional; the index at which to begin the search, default is 0. If negative, it is taken as the offset from the end of the array. Returns: true - the item was found false - it wasn't Example: >["a","b","c"].contains("a"); // true >["a","b","c"].contains("d"); // false */ contains: function(item, from){ return this.indexOf(item, from) != -1; }, /* Property: associate Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array. Arguments: keys - the array of keywords. Example: (start code) var Animals = ['Cat', 'Dog', 'Coala', 'Lizard']; var Speech = ['Miao', 'Bau', 'Fruuu', 'Mute']; var Speeches = Animals.associate(Speech); //Speeches['Miao'] is now Cat. //Speeches['Bau'] is now Dog. //... (end) */ associate: function(keys){ var obj = {}, length = Math.min(this.length, keys.length); for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; return obj; }, /* Property: extend Extends an array with another one. Arguments: array - the array to extend ours with Example: >var Animals = ['Cat', 'Dog', 'Coala']; >Animals.extend(['Lizard']); >//Animals is now: ['Cat', 'Dog', 'Coala', 'Lizard']; */ extend: function(array){ for (var i = 0, j = array.length; i < j; i++) this.push(array[i]); return this; }, /* Property: merge merges an array in another array, without duplicates. (case- and type-sensitive) Arguments: array - the array to merge from. Example: >['Cat','Dog'].merge(['Dog','Coala']); //returns ['Cat','Dog','Coala'] */ merge: function(array){ for (var i = 0, l = array.length; i < l; i++) this.include(array[i]); return this; }, /* Property: include includes the passed in element in the array, only if its not already present. (case- and type-sensitive) Arguments: item - item to add to the array (if not present) Example: >['Cat','Dog'].include('Dog'); //returns ['Cat','Dog'] >['Cat','Dog'].include('Coala'); //returns ['Cat','Dog','Coala'] */ include: function(item){ if (!this.contains(item)) this.push(item); return this; }, /* Property: getRandom returns a random item in the Array */ getRandom: function(){ return this[$random(0, this.length - 1)] || null; }, /* Property: getLast returns the last item in the Array */ getLast: function(){ return this[this.length - 1] || null; } }); //copies Array.prototype.each = Array.prototype.forEach; Array.each = Array.forEach; /* Section: Utility Functions */ /* Function: $A() Same as <Array.copy>, but as function. Useful to apply Array prototypes to iterable objects, as a collection of DOM elements or the arguments object. Example: (start code) function myFunction(){ $A(arguments).each(argument, function(){ alert(argument); }); }; //the above will alert all the arguments passed to the function myFunction. (end) */ function $A(array){ return Array.copy(array); }; /* Function: $each Use to iterate through iterables that are not regular arrays, such as builtin getElementsByTagName calls, arguments of a function, or an object. Arguments: iterable - an iterable element or an objct. function - function to apply to the iterable. bind - optional, the 'this' of the function will refer to this object. Function argument: The function argument will be passed the following arguments. item - the current item in the iterator being procesed index - integer; the index of the item, or key in case of an object. Examples: (start code) $each(['Sun','Mon','Tue'], function(day, index){ alert('name:' + day + ', index: ' + index); }); //alerts "name: Sun, index: 0", "name: Mon, index: 1", etc. //over an object $each({first: "Sunday", second: "Monday", third: "Tuesday"}, function(value, key){ alert("the " + key + " day of the week is " + value); }); //alerts "the first day of the week is Sunday", //"the second day of the week is Monday", etc. (end) */ function $each(iterable, fn, bind){ if (iterable && typeof iterable.length == 'number' && $type(iterable) != 'object'){ Array.forEach(iterable, fn, bind); } else { for (var name in iterable) fn.call(bind || iterable, iterable[name], name); } }; /*compatibility*/ Array.prototype.test = Array.prototype.contains; /*end compatibility*/ /* Script: String.js Contains String prototypes. License: MIT-style license. */ /* Class: String A collection of The String Object prototype methods. */ String.extend({ /* Property: test Tests a string with a regular expression. Arguments: regex - a string or regular expression object, the regular expression you want to match the string with params - optional, if first parameter is a string, any parameters you want to pass to the regex ('g' has no effect) Returns: true if a match for the regular expression is found in the string, false if not. See <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:RegExp:test> Example: >"I like cookies".test("cookie"); // returns true >"I like cookies".test("COOKIE", "i") // ignore case, returns true >"I like cookies".test("cake"); // returns false */ test: function(regex, params){ return (($type(regex) == 'string') ? new RegExp(regex, params) : regex).test(this); }, /* Property: toInt parses a string to an integer. Returns: either an int or "NaN" if the string is not a number. Example: >var value = "10px".toInt(); // value is 10 */ toInt: function(){ return parseInt(this, 10); }, /* Property: toFloat parses a string to an float. Returns: either a float or "NaN" if the string is not a number. Example: >var value = "10.848".toFloat(); // value is 10.848 */ toFloat: function(){ return parseFloat(this); }, /* Property: camelCase Converts a hiphenated string to a camelcase string. Example: >"I-like-cookies".camelCase(); //"ILikeCookies" Returns: the camel cased string */ camelCase: function(){ return this.replace(/-\D/g, function(match){ return match.charAt(1).toUpperCase(); }); }, /* Property: hyphenate Converts a camelCased string to a hyphen-ated string. Example: >"ILikeCookies".hyphenate(); //"I-like-cookies" */ hyphenate: function(){ return this.replace(/\w[A-Z]/g, function(match){ return (match.charAt(0) + '-' + match.charAt(1).toLowerCase()); }); }, /* Property: capitalize Converts the first letter in each word of a string to Uppercase. Example: >"i like cookies".capitalize(); //"I Like Cookies" Returns: the capitalized string */ capitalize: function(){ return this.replace(/\b[a-z]/g, function(match){ return match.toUpperCase(); }); }, /* Property: trim Trims the leading and trailing spaces off a string. Example: >" i like cookies ".trim() //"i like cookies" Returns: the trimmed string */ trim: function(){ return this.replace(/^\s+|\s+$/g, ''); }, /* Property: clean trims (<String.trim>) a string AND removes all the double spaces in a string. Returns: the cleaned string Example: >" i like cookies \n\n".clean() //"i like cookies" */ clean: function(){ return this.replace(/\s{2,}/g, ' ').trim(); }, /* Property: rgbToHex Converts an RGB value to hexidecimal. The string must be in the format of "rgb(255,255,255)" or "rgba(255,255,255,1)"; Arguments: array - boolean value, defaults to false. Use true if you want the array ['FF','33','00'] as output instead of "#FF3300" Returns: hex string or array. returns "transparent" if the output is set as string and the fourth value of rgba in input string is 0. Example: >"rgb(17,34,51)".rgbToHex(); //"#112233" >"rgba(17,34,51,0)".rgbToHex(); //"transparent" >"rgb(17,34,51)".rgbToHex(true); //['11','22','33'] */ rgbToHex: function(array){ var rgb = this.match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHex(array) : false; }, /* Property: hexToRgb Converts a hexidecimal color value to RGB. Input string must be the hex color value (with or without the hash). Also accepts triplets ('333'); Arguments: array - boolean value, defaults to false. Use true if you want the array [255,255,255] as output instead of "rgb(255,255,255)"; Returns: rgb string or array. Example: >"#112233".hexToRgb(); //"rgb(17,34,51)" >"#112233".hexToRgb(true); //[17,34,51] */ hexToRgb: function(array){ var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return (hex) ? hex.slice(1).hexToRgb(array) : false; }, /* Property: contains checks if the passed in string is contained in the String. also accepts an optional second parameter, to check if the string is contained in a list of separated values. Example: >'a b c'.contains('c', ' '); //true >'a bc'.contains('bc'); //true >'a bc'.contains('b', ' '); //false */ contains: function(string, s){ return (s) ? (s + this + s).indexOf(s + string + s) > -1 : this.indexOf(string) > -1; }, /* Property: escapeRegExp Returns string with escaped regular expression characters Example: >var search = 'animals.sheeps[1]'.escapeRegExp(); // search is now 'animals\.sheeps\[1\]' Returns: Escaped string */ escapeRegExp: function(){ return this.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); } }); Array.extend({ /* Property: rgbToHex see <String.rgbToHex>, but as an array method. */ rgbToHex: function(array){ if (this.length < 3) return false; if (this.length == 4 && this[3] == 0 && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (this[i] - 0).toString(16); hex.push((bit.length == 1) ? '0' + bit : bit); } return array ? hex : '#' + hex.join(''); }, /* Property: hexToRgb same as <String.hexToRgb>, but as an array method. */ hexToRgb: function(array){ if (this.length != 3) return false; var rgb = []; for (var i = 0; i < 3; i++){ rgb.push(parseInt((this[i].length == 1) ? this[i] + this[i] : this[i], 16)); } return array ? rgb : 'rgb(' + rgb.join(',') + ')'; } }); /* Script: Function.js Contains Function prototypes and utility functions . License: MIT-style license. Credits: - Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license */ /* Class: Function A collection of The Function Object prototype methods. */ Function.extend({ /* Property: create Main function to create closures. Returns: a function. Arguments: options - An Options object. Options: bind - The object that the "this" of the function will refer to. Default is the current function. event - If set to true, the function will act as an event listener and receive an event as first argument. If set to a class name, the function will receive a new instance of this class (with the event passed as argument's constructor) as first argument. Default is false. arguments - A single argument or array of arguments that will be passed to the function when called. If both the event and arguments options are set, the event is passed as first argument and the arguments array will follow. Default is no custom arguments, the function will receive the standard arguments when called. delay - Numeric value: if set, the returned function will delay the actual execution by this amount of milliseconds and return a timer handle when called. Default is no delay. periodical - Numeric value: if set, the returned function will periodically perform the actual execution with this specified interval and return a timer handle when called. Default is no periodical execution. attempt - If set to true, the returned function will try to execute and return either the results or false on error. Default is false. */ create: function(options){ var fn = this; options = $merge({ 'bind': fn, 'event': false, 'arguments': null, 'delay': false, 'periodical': false, 'attempt': false }, options); if ($chk(options.arguments) && $type(options.arguments) != 'array') options.arguments = [options.arguments]; return function(event){ var args; if (options.event){ event = event || window.event; args = [(options.event === true) ? event : new options.event(event)]; if (options.arguments) args.extend(options.arguments); } else args = options.arguments || arguments; var returns = function(){ return fn.apply($pick(options.bind, fn), args); }; if (options.delay) return setTimeout(returns, options.delay); if (options.periodical) return setInterval(returns, options.periodical); if (options.attempt) try {return returns();} catch(err){return false;}; return returns(); }; }, /* Property: pass Shortcut to create closures with arguments and bind. Returns: a function. Arguments: args - the arguments passed. must be an array if arguments > 1 bind - optional, the object that the "this" of the function will refer to. Example: >myFunction.pass([arg1, arg2], myElement); */ pass: function(args, bind){ return this.create({'arguments': args, 'bind': bind}); }, /* Property: attempt Tries to execute the function, returns either the result of the function or false on error. Arguments: args - the arguments passed. must be an array if arguments > 1 bind - optional, the object that the "this" of the function will refer to. Example: >myFunction.attempt([arg1, arg2], myElement); */ attempt: function(args, bind){ return this.create({'arguments': args, 'bind': bind, 'attempt': true})(); }, /* Property: bind method to easily create closures with "this" altered. Arguments: bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 Returns: a function. Example: >function myFunction(){ > this.setStyle('color', 'red'); > // note that 'this' here refers to myFunction, not an element > // we'll need to bind this function to the element we want to alter >}; >var myBoundFunction = myFunction.bind(myElement); >myBoundFunction(); // this will make the element myElement red. */ bind: function(bind, args){ return this.create({'bind': bind, 'arguments': args}); }, /* Property: bindAsEventListener cross browser method to pass event firer Arguments: bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 Returns: a function with the parameter bind as its "this" and as a pre-passed argument event or window.event, depending on the browser. Example: >function myFunction(event){ > alert(event.clientx) //returns the coordinates of the mouse.. >}; >myElement.onclick = myFunction.bindAsEventListener(myElement); */ bindAsEventListener: function(bind, args){ return this.create({'bind': bind, 'event': true, 'arguments': args}); }, /* Property: delay Delays the execution of a function by a specified duration. Arguments: delay - the duration to wait in milliseconds. bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 Example: >myFunction.delay(50, myElement) //wait 50 milliseconds, then call myFunction and bind myElement to it >(function(){alert('one second later...')}).delay(1000); //wait a second and alert */ delay: function(delay, bind, args){ return this.create({'delay': delay, 'bind': bind, 'arguments': args})(); }, /* Property: periodical Executes a function in the specified intervals of time Arguments: interval - the duration of the intervals between executions. bind - optional, the object that the "this" of the function will refer to. args - optional, the arguments passed. must be an array if arguments > 1 */ periodical: function(interval, bind, args){ return this.create({'periodical': interval, 'bind': bind, 'arguments': args})(); } }); /* Script: Number.js Contains the Number prototypes. License: MIT-style license. */ /* Class: Number A collection of The Number Object prototype methods. */ Number.extend({ /* Property: toInt Returns this number; useful because toInt must work on both Strings and Numbers. */ toInt: function(){ return parseInt(this); }, /* Property: toFloat Returns this number as a float; useful because toFloat must work on both Strings and Numbers. */ toFloat: function(){ return parseFloat(this); }, /* Property: limit Limits the number. Arguments: min - number, minimum value max - number, maximum value Returns: the number in the given limits. Example: >(12).limit(2, 6.5) // returns 6.5 >(-4).limit(2, 6.5) // returns 2 >(4.3).limit(2, 6.5) // returns 4.3 */ limit: function(min, max){ return Math.min(max, Math.max(min, this)); }, /* Property: round Returns the number rounded to specified precision. Arguments: precision - integer, number of digits after the decimal point. Can also be negative or zero (default). Example: >12.45.round() // returns 12 >12.45.round(1) // returns 12.5 >12.45.round(-1) // returns 10 Returns: The rounded number. */ round: function(precision){ precision = Math.pow(10, precision || 0); return Math.round(this * precision) / precision; }, /* Property: times Executes a passed in function the specified number of times Arguments: function - the function to be executed on each iteration of the loop Example: >(4).times(alert); */ times: function(fn){ for (var i = 0; i < this; i++) fn(i); } }); /* Script: Element.js Contains useful Element prototypes, to be used with the dollar function <$>. License: MIT-style license. Credits: - Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license */ /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ var Element = new Class({ /* Property: initialize Creates a new element of the type passed in. Arguments: el - string; the tag name for the element you wish to create. you can also pass in an element reference, in which case it will be extended. props - object; the properties you want to add to your element. Accepts the same keys as <Element.setProperties>, but also allows events and styles Props: the key styles will be used as setStyles, the key events will be used as addEvents. any other key is used as setProperty. Example: (start code) new Element('a', { 'styles': { 'display': 'block', 'border': '1px solid black' }, 'events': { 'click': function(){ //aaa }, 'mousedown': function(){ //aaa } }, 'class': 'myClassSuperClass', 'href': 'http://mad4milk.net' }); (end) */ initialize: function(el, props){ if ($type(el) == 'string'){ if (window.ie && props && (props.name || props.type)){ var name = (props.name) ? ' name="' + props.name + '"' : ''; var type = (props.type) ? ' type="' + props.type + '"' : ''; delete props.name; delete props.type; el = '<' + el + name + type + '>'; } el = document.createElement(el); } el = $(el); return (!props || !el) ? el : el.set(props); } }); /* Class: Elements - Every dom function such as <$$>, or in general every function that returns a collection of nodes in mootools, returns them as an Elements class. - The purpose of the Elements class is to allow <Element> methods to work also on <Elements> array. - Elements is also an Array, so it accepts all the <Array> methods. - Every node of the Elements instance is already extended with <$>. Example: >$$('myselector').each(function(el){ > //... >}); some iterations here, $$('myselector') is also an array. >$$('myselector').setStyle('color', 'red'); every element returned by $$('myselector') also accepts <Element> methods, in this example every element will be made red. */ var Elements = new Class({ initialize: function(elements){ return (elements) ? $extend(elements, this) : this; } }); Elements.extend = function(props){ for (var prop in props){ this.prototype[prop] = props[prop]; this[prop] = $native.generic(prop); } }; /* Section: Utility Functions Function: $ returns the element passed in with all the Element prototypes applied. Arguments: el - a reference to an actual element or a string representing the id of an element Example: >$('myElement') // gets a DOM element by id with all the Element prototypes applied. >var div = document.getElementById('myElement'); >$(div) //returns an Element also with all the mootools extentions applied. You'll use this when you aren't sure if a variable is an actual element or an id, as well as just shorthand for document.getElementById(). Returns: a DOM element or false (if no id was found). Note: you need to call $ on an element only once to get all the prototypes. But its no harm to call it multiple times, as it will detect if it has been already extended. */ function $(el){ if (!el) return null; if (el.htmlElement) return Garbage.collect(el); if ([window, document].contains(el)) return el; var type = $type(el); if (type == 'string'){ el = document.getElementById(el); type = (el) ? 'element' : false; } if (type != 'element') return null; if (el.htmlElement) return Garbage.collect(el); if (['object', 'embed'].contains(el.tagName.toLowerCase())) return el; $extend(el, Element.prototype); el.htmlElement = function(){}; return Garbage.collect(el); }; /* Function: $$ Selects, and extends DOM elements. Elements arrays returned with $$ will also accept all the <Element> methods. The return type of element methods run through $$ is always an array. If the return array is only made by elements, $$ will be applied automatically. Arguments: HTML Collections, arrays of elements, arrays of strings as element ids, elements, strings as selectors. Any number of the above as arguments are accepted. Note: if you load <Element.Selectors.js>, $$ will also accept CSS Selectors, otherwise the only selectors supported are tag names. Example: >$$('a') //an array of all anchor tags on the page >$$('a', 'b') //an array of all anchor and bold tags on the page >$$('#myElement') //array containing only the element with id = myElement. (only with <Element.Selectors.js>) >$$('#myElement a.myClass') //an array of all anchor tags with the class "myClass" >//within the DOM element with id "myElement" (only with <Element.Selectors.js>) >$$(myelement, myelement2, 'a', ['myid', myid2, 'myid3'], document.getElementsByTagName('div')) //an array containing: >// the element referenced as myelement if existing, >// the element referenced as myelement2 if existing, >// all the elements with a as tag in the page, >// the element with id = myid if existing >// the element with id = myid2 if existing >// the element with id = myid3 if existing >// all the elements with div as tag in the page Returns: array - array of all the dom elements matched, extended with <$>. Returns as <Elements>. */ document.getElementsBySelector = document.getElementsByTagName; function $$(){ var elements = []; for (var i = 0, j = arguments.length; i < j; i++){ var selector = arguments[i]; switch($type(selector)){ case 'element': elements.push(selector); case 'boolean': break; case false: break; case 'string': selector = document.getElementsBySelector(selector, true); default: elements.extend(selector); } } return $$.unique(elements); }; $$.unique = function(array){ var elements = []; for (var i = 0, l = array.length; i < l; i++){ if (array[i].$included) continue; var element = $(array[i]); if (element && !element.$included){ element.$included = true; elements.push(element); } } for (var n = 0, d = elements.length; n < d; n++) elements[n].$included = null; return new Elements(elements); }; Elements.Multi = function(property){ return function(){ var args = arguments; var items = []; var elements = true; for (var i = 0, j = this.length, returns; i < j; i++){ returns = this[i][property].apply(this[i], args); if ($type(returns) != 'element') elements = false; items.push(returns); }; return (elements) ? $$.unique(items) : items; }; }; Element.extend = function(properties){ for (var property in properties){ HTMLElement.prototype[property] = properties[property]; Element.prototype[property] = properties[property]; Element[property] = $native.generic(property); var elementsProperty = (Array.prototype[property]) ? property + 'Elements' : property; Elements.prototype[elementsProperty] = Elements.Multi(property); } }; /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: set you can set events, styles and properties with this shortcut. same as calling new Element. */ set: function(props){ for (var prop in props){ var val = props[prop]; switch(prop){ case 'styles': this.setStyles(val); break; case 'events': if (this.addEvents) this.addEvents(val); break; case 'properties': this.setProperties(val); break; default: this.setProperty(prop, val); } } return this; }, inject: function(el, where){ el = $(el); switch(where){ case 'before': el.parentNode.insertBefore(this, el); break; case 'after': var next = el.getNext(); if (!next) el.parentNode.appendChild(this); else el.parentNode.insertBefore(this, next); break; case 'top': var first = el.firstChild; if (first){ el.insertBefore(this, first); break; } default: el.appendChild(this); } return this; }, /* Property: injectBefore Inserts the Element before the passed element. Arguments: el - an element reference or the id of the element to be injected in. Example: >html: ><div id="myElement"></div> ><div id="mySecondElement"></div> >js: >$('mySecondElement').injectBefore('myElement'); >resulting html: ><div id="mySecondElement"></div> ><div id="myElement"></div> */ injectBefore: function(el){ return this.inject(el, 'before'); }, /* Property: injectAfter Same as <Element.injectBefore>, but inserts the element after. */ injectAfter: function(el){ return this.inject(el, 'after'); }, /* Property: injectInside Same as <Element.injectBefore>, but inserts the element inside. */ injectInside: function(el){ return this.inject(el, 'bottom'); }, /* Property: injectTop Same as <Element.injectInside>, but inserts the element inside, at the top. */ injectTop: function(el){ return this.inject(el, 'top'); }, /* Property: adopt Inserts the passed elements inside the Element. Arguments: accepts elements references, element ids as string, selectors ($$('stuff')) / array of elements, array of ids as strings and collections. */ adopt: function(){ var elements = []; $each(arguments, function(argument){ elements = elements.concat(argument); }); $$(elements).inject(this); return this; }, /* Property: remove Removes the Element from the DOM. Example: >$('myElement').remove() //bye bye */ remove: function(){ return this.parentNode.removeChild(this); }, /* Property: clone Clones the Element and returns the cloned one. Arguments: contents - boolean, when true the Element is cloned with childNodes, default true Returns: the cloned element Example: >var clone = $('myElement').clone().injectAfter('myElement'); >//clones the Element and append the clone after the Element. */ clone: function(contents){ var el = $(this.cloneNode(contents !== false)); if (!el.$events) return el; el.$events = {}; for (var type in this.$events) el.$events[type] = { 'keys': $A(this.$events[type].keys), 'values': $A(this.$events[type].values) }; return el.removeEvents(); }, /* Property: replaceWith Replaces the Element with an element passed. Arguments: el - a string representing the element to be injected in (myElementId, or div), or an element reference. If you pass div or another tag, the element will be created. Returns: the passed in element Example: >$('myOldElement').replaceWith($('myNewElement')); //$('myOldElement') is gone, and $('myNewElement') is in its place. */ replaceWith: function(el){ el = $(el); this.parentNode.replaceChild(el, this); return el; }, /* Property: appendText Appends text node to a DOM element. Arguments: text - the text to append. Example: ><div id="myElement">hey</div> >$('myElement').appendText(' howdy'); //myElement innerHTML is now "hey howdy" */ appendText: function(text){ this.appendChild(document.createTextNode(text)); return this; }, /* Property: hasClass Tests the Element to see if it has the passed in className. Returns: true - the Element has the class false - it doesn't Arguments: className - string; the class name to test. Example: ><div id="myElement" class="testClass"></div> >$('myElement').hasClass('testClass'); //returns true */ hasClass: function(className){ return this.className.contains(className, ' '); }, /* Property: addClass Adds the passed in class to the Element, if the element doesnt already have it. Arguments: className - string; the class name to add Example: ><div id="myElement" class="testClass"></div> >$('myElement').addClass('newClass'); //<div id="myElement" class="testClass newClass"></div> */ addClass: function(className){ if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean(); return this; }, /* Property: removeClass Works like <Element.addClass>, but removes the class from the element. */ removeClass: function(className){ this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean(); return this; }, /* Property: toggleClass Adds or removes the passed in class name to the element, depending on if it's present or not. Arguments: className - the class to add or remove Example: ><div id="myElement" class="myClass"></div> >$('myElement').toggleClass('myClass'); ><div id="myElement" class=""></div> >$('myElement').toggleClass('myClass'); ><div id="myElement" class="myClass"></div> */ toggleClass: function(className){ return this.hasClass(className) ? this.removeClass(className) : this.addClass(className); }, /* Property: setStyle Sets a css property to the Element. Arguments: property - the property to set value - the value to which to set it; for numeric values that require "px" you can pass an integer Example: >$('myElement').setStyle('width', '300px'); //the width is now 300px >$('myElement').setStyle('width', 300); //the width is now 300px */ setStyle: function(property, value){ switch(property){ case 'opacity': return this.setOpacity(parseFloat(value)); case 'float': property = (window.ie) ? 'styleFloat' : 'cssFloat'; } property = property.camelCase(); switch($type(value)){ case 'number': if (!['zIndex', 'zoom'].contains(property)) value += 'px'; break; case 'array': value = 'rgb(' + value.join(',') + ')'; } this.style[property] = value; return this; }, /* Property: setStyles Applies a collection of styles to the Element. Arguments: source - an object or string containing all the styles to apply. When its a string it overrides old style. Examples: >$('myElement').setStyles({ > border: '1px solid #000', > width: 300, > height: 400 >}); OR >$('myElement').setStyles('border: 1px solid #000; width: 300px; height: 400px;'); */ setStyles: function(source){ switch($type(source)){ case 'object': Element.setMany(this, 'setStyle', source); break; case 'string': this.style.cssText = source; } return this; }, /* Property: setOpacity Sets the opacity of the Element, and sets also visibility == "hidden" if opacity == 0, and visibility = "visible" if opacity > 0. Arguments: opacity - float; Accepts values from 0 to 1. Example: >$('myElement').setOpacity(0.5) //make it 50% transparent */ setOpacity: function(opacity){ if (opacity == 0){ if (this.style.visibility != "hidden") this.style.visibility = "hidden"; } else { if (this.style.visibility != "visible") this.style.visibility = "visible"; } if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1; if (window.ie) this.style.filter = (opacity == 1) ? '' : "alpha(opacity=" + opacity * 100 + ")"; this.style.opacity = this.$tmp.opacity = opacity; return this; }, /* Property: getStyle Returns the style of the Element given the property passed in. Arguments: property - the css style property you want to retrieve Example: >$('myElement').getStyle('width'); //returns "400px" >//but you can also use >$('myElement').getStyle('width').toInt(); //returns 400 Returns: the style as a string */ getStyle: function(property){ property = property.camelCase(); var result = this.style[property]; if (!$chk(result)){ if (property == 'opacity') return this.$tmp.opacity; result = []; for (var style in Element.Styles){ if (property == style){ Element.Styles[style].each(function(s){ var style = this.getStyle(s); result.push(parseInt(style) ? style : '0px'); }, this); if (property == 'border'){ var every = result.every(function(bit){ return (bit == result[0]); }); return (every) ? result[0] : false; } return result.join(' '); } } if (property.contains('border')){ if (Element.Styles.border.contains(property)){ return ['Width', 'Style', 'Color'].map(function(p){ return this.getStyle(property + p); }, this).join(' '); } else if (Element.borderShort.contains(property)){ return ['Top', 'Right', 'Bottom', 'Left'].map(function(p){ return this.getStyle('border' + p + property.replace('border', '')); }, this).join(' '); } } if (document.defaultView) result = document.defaultView.getComputedStyle(this, null).getPropertyValue(property.hyphenate()); else if (this.currentStyle) result = this.currentStyle[property]; } if (window.ie) result = Element.fixStyle(property, result, this); if (result && property.test(/color/i) && result.contains('rgb')){ return result.split('rgb').splice(1,4).map(function(color){ return color.rgbToHex(); }).join(' '); } return result; }, /* Property: getStyles Returns an object of styles of the Element for each argument passed in. Arguments: properties - strings; any number of style properties Example: >$('myElement').getStyles('width','height','padding'); >//returns an object like: >{width: "10px", height: "10px", padding: "10px 0px 10px 0px"} */ getStyles: function(){ return Element.getMany(this, 'getStyle', arguments); }, walk: function(brother, start){ brother += 'Sibling'; var el = (start) ? this[start] : this[brother]; while (el && $type(el) != 'element') el = el[brother]; return $(el); }, /* Property: getPrevious Returns the previousSibling of the Element, excluding text nodes. Example: >$('myElement').getPrevious(); //get the previous DOM element from myElement Returns: the sibling element or undefined if none found. */ getPrevious: function(){ return this.walk('previous'); }, /* Property: getNext Works as Element.getPrevious, but tries to find the nextSibling. */ getNext: function(){ return this.walk('next'); }, /* Property: getFirst Works as <Element.getPrevious>, but tries to find the firstChild. */ getFirst: function(){ return this.walk('next', 'firstChild'); }, /* Property: getLast Works as <Element.getPrevious>, but tries to find the lastChild. */ getLast: function(){ return this.walk('previous', 'lastChild'); }, /* Property: getParent returns the $(element.parentNode) */ getParent: function(){ return $(this.parentNode); }, /* Property: getChildren returns all the $(element.childNodes), excluding text nodes. Returns as <Elements>. */ getChildren: function(){ return $$(this.childNodes); }, /* Property: hasChild returns true if the passed in element is a child of the $(element). */ hasChild: function(el){ return !!$A(this.getElementsByTagName('*')).contains(el); }, /* Property: getProperty Gets the an attribute of the Element. Arguments: property - string; the attribute to retrieve Example: >$('myImage').getProperty('src') // returns whatever.gif Returns: the value, or an empty string */ getProperty: function(property){ var index = Element.Properties[property]; if (index) return this[index]; var flag = Element.PropertiesIFlag[property] || 0; if (!window.ie || flag) return this.getAttribute(property, flag); var node = this.attributes[property]; return (node) ? node.nodeValue : null; }, /* Property: removeProperty Removes an attribute from the Element Arguments: property - string; the attribute to remove */ removeProperty: function(property){ var index = Element.Properties[property]; if (index) this[index] = ''; else this.removeAttribute(property); return this; }, /* Property: getProperties same as <Element.getStyles>, but for properties */ getProperties: function(){ return Element.getMany(this, 'getProperty', arguments); }, /* Property: setProperty Sets an attribute for the Element. Arguments: property - string; the property to assign the value passed in value - the value to assign to the property passed in Example: >$('myImage').setProperty('src', 'whatever.gif'); //myImage now points to whatever.gif for its source */ setProperty: function(property, value){ var index = Element.Properties[property]; if (index) this[index] = value; else this.setAttribute(property, value); return this; }, /* Property: setProperties Sets numerous attributes for the Element. Arguments: source - an object with key/value pairs. Example: (start code) $('myElement').setProperties({ src: 'whatever.gif', alt: 'whatever dude' }); <img src="whatever.gif" alt="whatever dude"> (end) */ setProperties: function(source){ return Element.setMany(this, 'setProperty', source); }, /* Property: setHTML Sets the innerHTML of the Element. Arguments: html - string; the new innerHTML for the element. Example: >$('myElement').setHTML(newHTML) //the innerHTML of myElement is now = newHTML */ setHTML: function(){ this.innerHTML = $A(arguments).join(''); return this; }, /* Property: setText Sets the inner text of the Element. Arguments: text - string; the new text content for the element. Example: >$('myElement').setText('some text') //the text of myElement is now = 'some text' */ setText: function(text){ var tag = this.getTag(); if (['style', 'script'].contains(tag)){ if (window.ie){ if (tag == 'style') this.styleSheet.cssText = text; else if (tag == 'script') this.setProperty('text', text); return this; } else { this.removeChild(this.firstChild); return this.appendText(text); } } this[$defined(this.innerText) ? 'innerText' : 'textContent'] = text; return this; }, /* Property: getText Gets the inner text of the Element. */ getText: function(){ var tag = this.getTag(); if (['style', 'script'].contains(tag)){ if (window.ie){ if (tag == 'style') return this.styleSheet.cssText; else if (tag == 'script') return this.getProperty('text'); } else { return this.innerHTML; } } return ($pick(this.innerText, this.textContent)); }, /* Property: getTag Returns the tagName of the element in lower case. Example: >$('myImage').getTag() // returns 'img' Returns: The tag name in lower case */ getTag: function(){ return this.tagName.toLowerCase(); }, /* Property: empty Empties an element of all its children. Example: >$('myDiv').empty() // empties the Div and returns it Returns: The element. */ empty: function(){ Garbage.trash(this.getElementsByTagName('*')); return this.setHTML(''); } }); Element.fixStyle = function(property, result, element){ if ($chk(parseInt(result))) return result; if (['height', 'width'].contains(property)){ var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom']; var size = 0; values.each(function(value){ size += element.getStyle('border-' + value + '-width').toInt() + element.getStyle('padding-' + value).toInt(); }); return element['offset' + property.capitalize()] - size + 'px'; } else if (property.test(/border(.+)Width|margin|padding/)){ return '0px'; } return result; }; Element.Styles = {'border': [], 'padding': [], 'margin': []}; ['Top', 'Right', 'Bottom', 'Left'].each(function(direction){ for (var style in Element.Styles) Element.Styles[style].push(style + direction); }); Element.borderShort = ['borderWidth', 'borderStyle', 'borderColor']; Element.getMany = function(el, method, keys){ var result = {}; $each(keys, function(key){ result[key] = el[method](key); }); return result; }; Element.setMany = function(el, method, pairs){ for (var key in pairs) el[method](key, pairs[key]); return el; }; Element.Properties = new Abstract({ 'class': 'className', 'for': 'htmlFor', 'colspan': 'colSpan', 'rowspan': 'rowSpan', 'accesskey': 'accessKey', 'tabindex': 'tabIndex', 'maxlength': 'maxLength', 'readonly': 'readOnly', 'frameborder': 'frameBorder', 'value': 'value', 'disabled': 'disabled', 'checked': 'checked', 'multiple': 'multiple', 'selected': 'selected' }); Element.PropertiesIFlag = { 'href': 2, 'src': 2 }; Element.Methods = { Listeners: { addListener: function(type, fn){ if (this.addEventListener) this.addEventListener(type, fn, false); else this.attachEvent('on' + type, fn); return this; }, removeListener: function(type, fn){ if (this.removeEventListener) this.removeEventListener(type, fn, false); else this.detachEvent('on' + type, fn); return this; } } }; window.extend(Element.Methods.Listeners); document.extend(Element.Methods.Listeners); Element.extend(Element.Methods.Listeners); var Garbage = { elements: [], collect: function(el){ if (!el.$tmp){ Garbage.elements.push(el); el.$tmp = {'opacity': 1}; } return el; }, trash: function(elements){ for (var i = 0, j = elements.length, el; i < j; i++){ if (!(el = elements[i]) || !el.$tmp) continue; if (el.$events) el.fireEvent('trash').removeEvents(); for (var p in el.$tmp) el.$tmp[p] = null; for (var d in Element.prototype) el[d] = null; Garbage.elements[Garbage.elements.indexOf(el)] = null; el.htmlElement = el.$tmp = el = null; } Garbage.elements.remove(null); }, empty: function(){ Garbage.collect(window); Garbage.collect(document); Garbage.trash(Garbage.elements); } }; window.addListener('beforeunload', function(){ window.addListener('unload', Garbage.empty); if (window.ie) window.addListener('unload', CollectGarbage); }); /* Script: Element.Event.js Contains the Event Class, Element methods to deal with Element events, custom Events, and the Function prototype bindWithEvent. License: MIT-style license. */ /* Class: Event Cross browser methods to manage events. Arguments: event - the event Properties: shift - true if the user pressed the shift control - true if the user pressed the control alt - true if the user pressed the alt meta - true if the user pressed the meta key wheel - the amount of third button scrolling code - the keycode of the key pressed page.x - the x position of the mouse, relative to the full window page.y - the y position of the mouse, relative to the full window client.x - the x position of the mouse, relative to the viewport client.y - the y position of the mouse, relative to the viewport key - the key pressed as a lowercase string. key also returns 'enter', 'up', 'down', 'left', 'right', 'space', 'backspace', 'delete', 'esc'. Handy for these special keys. target - the event target relatedTarget - the event related target Example: (start code) $('myLink').onkeydown = function(event){ var event = new Event(event); //event is now the Event class. alert(event.key); //returns the lowercase letter pressed alert(event.shift); //returns true if the key pressed is shift if (event.key == 's' && event.control) alert('document saved'); }; (end) */ var Event = new Class({ initialize: function(event){ if (event && event.$extended) return event; this.$extended = true; event = event || window.event; this.event = event; this.type = event.type; this.target = event.target || event.srcElement; if (this.target.nodeType == 3) this.target = this.target.parentNode; this.shift = event.shiftKey; this.control = event.ctrlKey; this.alt = event.altKey; this.meta = event.metaKey; if (['DOMMouseScroll', 'mousewheel'].contains(this.type)){ this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; } else if (this.type.contains('key')){ this.code = event.which || event.keyCode; for (var name in Event.keys){ if (Event.keys[name] == this.code){ this.key = name; break; } } if (this.type == 'keydown'){ var fKey = this.code - 111; if (fKey > 0 && fKey < 13) this.key = 'f' + fKey; } this.key = this.key || String.fromCharCode(this.code).toLowerCase(); } else if (this.type.test(/(click|mouse|menu)/)){ this.page = { 'x': event.pageX || event.clientX + document.documentElement.scrollLeft, 'y': event.pageY || event.clientY + document.documentElement.scrollTop }; this.client = { 'x': event.pageX ? event.pageX - window.pageXOffset : event.clientX, 'y': event.pageY ? event.pageY - window.pageYOffset : event.clientY }; this.rightClick = (event.which == 3) || (event.button == 2); switch(this.type){ case 'mouseover': this.relatedTarget = event.relatedTarget || event.fromElement; break; case 'mouseout': this.relatedTarget = event.relatedTarget || event.toElement; } this.fixRelatedTarget(); } return this; }, /* Property: stop cross browser method to stop an event */ stop: function(){ return this.stopPropagation().preventDefault(); }, /* Property: stopPropagation cross browser method to stop the propagation of an event */ stopPropagation: function(){ if (this.event.stopPropagation) this.event.stopPropagation(); else this.event.cancelBubble = true; return this; }, /* Property: preventDefault cross browser method to prevent the default action of the event */ preventDefault: function(){ if (this.event.preventDefault) this.event.preventDefault(); else this.event.returnValue = false; return this; } }); Event.fix = { relatedTarget: function(){ if (this.relatedTarget && this.relatedTarget.nodeType == 3) this.relatedTarget = this.relatedTarget.parentNode; }, relatedTargetGecko: function(){ try {Event.fix.relatedTarget.call(this);} catch(e){this.relatedTarget = this.target;} } }; Event.prototype.fixRelatedTarget = (window.gecko) ? Event.fix.relatedTargetGecko : Event.fix.relatedTarget; /* Property: keys you can add additional Event keys codes this way: Example: (start code) Event.keys.whatever = 80; $(myelement).addEvent(keydown, function(event){ event = new Event(event); if (event.key == 'whatever') console.log(whatever key clicked). }); (end) */ Event.keys = new Abstract({ 'enter': 13, 'up': 38, 'down': 40, 'left': 37, 'right': 39, 'esc': 27, 'space': 32, 'backspace': 8, 'tab': 9, 'delete': 46 }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.Methods.Events = { /* Property: addEvent Attaches an event listener to a DOM element. Arguments: type - the event to monitor ('click', 'load', etc) without the prefix 'on'. fn - the function to execute Example: >$('myElement').addEvent('click', function(){alert('clicked!')}); */ addEvent: function(type, fn){ this.$events = this.$events || {}; this.$events[type] = this.$events[type] || {'keys': [], 'values': []}; if (this.$events[type].keys.contains(fn)) return this; this.$events[type].keys.push(fn); var realType = type; var custom = Element.Events[type]; if (custom){ if (custom.add) custom.add.call(this, fn); if (custom.map) fn = custom.map; if (custom.type) realType = custom.type; } if (!this.addEventListener) fn = fn.create({'bind': this, 'event': true}); this.$events[type].values.push(fn); return (Element.NativeEvents.contains(realType)) ? this.addListener(realType, fn) : this; }, /* Property: removeEvent Works as Element.addEvent, but instead removes the previously added event listener. */ removeEvent: function(type, fn){ if (!this.$events || !this.$events[type]) return this; var pos = this.$events[type].keys.indexOf(fn); if (pos == -1) return this; var key = this.$events[type].keys.splice(pos,1)[0]; var value = this.$events[type].values.splice(pos,1)[0]; var custom = Element.Events[type]; if (custom){ if (custom.remove) custom.remove.call(this, fn); if (custom.type) type = custom.type; } return (Element.NativeEvents.contains(type)) ? this.removeListener(type, value) : this; }, /* Property: addEvents As <addEvent>, but accepts an object and add multiple events at once. */ addEvents: function(source){ return Element.setMany(this, 'addEvent', source); }, /* Property: removeEvents removes all events of a certain type from an element. if no argument is passed in, removes all events. Arguments: type - string; the event name (e.g. 'click') */ removeEvents: function(type){ if (!this.$events) return this; if (!type){ for (var evType in this.$events) this.removeEvents(evType); this.$events = null; } else if (this.$events[type]){ this.$events[type].keys.each(function(fn){ this.removeEvent(type, fn); }, this); this.$events[type] = null; } return this; }, /* Property: fireEvent executes all events of the specified type present in the element. Arguments: type - string; the event name (e.g. 'click') args - array or single object; arguments to pass to the function; if more than one argument, must be an array delay - (integer) delay (in ms) to wait to execute the event */ fireEvent: function(type, args, delay){ if (this.$events && this.$events[type]){ this.$events[type].keys.each(function(fn){ fn.create({'bind': this, 'delay': delay, 'arguments': args})(); }, this); } return this; }, /* Property: cloneEvents Clones all events from an element to this element. Arguments: from - element, copy all events from this element type - optional, copies only events of this type */ cloneEvents: function(from, type){ if (!from.$events) return this; if (!type){ for (var evType in from.$events) this.cloneEvents(from, evType); } else if (from.$events[type]){ from.$events[type].keys.each(function(fn){ this.addEvent(type, fn); }, this); } return this; } }; window.extend(Element.Methods.Events); document.extend(Element.Methods.Events); Element.extend(Element.Methods.Events); /* Section: Custom Events */ Element.Events = new Abstract({ /* Event: mouseenter In addition to the standard javascript events (load, mouseover, mouseout, click, etc.) <Event.js> contains two custom events this event fires when the mouse enters the area of the dom element; will not be fired again if the mouse crosses over children of the element (unlike mouseover) Example: >$(myElement).addEvent('mouseenter', myFunction); */ 'mouseenter': { type: 'mouseover', map: function(event){ event = new Event(event); if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseenter', event); } }, /* Event: mouseleave this event fires when the mouse exits the area of the dom element; will not be fired again if the mouse crosses over children of the element (unlike mouseout) Example: >$(myElement).addEvent('mouseleave', myFunction); */ 'mouseleave': { type: 'mouseout', map: function(event){ event = new Event(event); if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseleave', event); } }, 'mousewheel': { type: (window.gecko) ? 'DOMMouseScroll' : 'mousewheel' } }); Element.NativeEvents = [ 'click', 'dblclick', 'mouseup', 'mousedown', //mouse buttons 'mousewheel', 'DOMMouseScroll', //mouse wheel 'mouseover', 'mouseout', 'mousemove', //mouse movement 'keydown', 'keypress', 'keyup', //keys 'load', 'unload', 'beforeunload', 'resize', 'move', //window 'focus', 'blur', 'change', 'submit', 'reset', 'select', //forms elements 'error', 'abort', 'contextmenu', 'scroll' //misc ]; /* Class: Function A collection of The Function Object prototype methods. */ Function.extend({ /* Property: bindWithEvent automatically passes MooTools Event Class. Arguments: bind - optional, the object that the "this" of the function will refer to. args - optional, an argument to pass to the function; if more than one argument, it must be an array of arguments. Returns: a function with the parameter bind as its "this" and as a pre-passed argument event or window.event, depending on the browser. Example: >function myFunction(event){ > alert(event.client.x) //returns the coordinates of the mouse.. >}; >myElement.addEvent('click', myFunction.bindWithEvent(myElement)); */ bindWithEvent: function(bind, args){ return this.create({'bind': bind, 'arguments': args, 'event': Event}); } }); /* Script: Element.Filters.js add Filters capability to <Elements>. License: MIT-style license. */ /* Class: Elements A collection of methods to be used with <$$> elements collections. */ Elements.extend({ /* Property: filterByTag Filters the collection by a specified tag name. Returns a new Elements collection, while the original remains untouched. */ filterByTag: function(tag){ return new Elements(this.filter(function(el){ return (Element.getTag(el) == tag); })); }, /* Property: filterByClass Filters the collection by a specified class name. Returns a new Elements collection, while the original remains untouched. */ filterByClass: function(className, nocash){ var elements = this.filter(function(el){ return (el.className && el.className.contains(className, ' ')); }); return (nocash) ? elements : new Elements(elements); }, /* Property: filterById Filters the collection by a specified ID. Returns a new Elements collection, while the original remains untouched. */ filterById: function(id, nocash){ var elements = this.filter(function(el){ return (el.id == id); }); return (nocash) ? elements : new Elements(elements); }, /* Property: filterByAttribute Filters the collection by a specified attribute. Returns a new Elements collection, while the original remains untouched. Arguments: name - the attribute name. operator - optional, the attribute operator. value - optional, the attribute value, only valid if the operator is specified. */ filterByAttribute: function(name, operator, value, nocash){ var elements = this.filter(function(el){ var current = Element.getProperty(el, name); if (!current) return false; if (!operator) return true; switch(operator){ case '=': return (current == value); case '*=': return (current.contains(value)); case '^=': return (current.substr(0, value.length) == value); case '$=': return (current.substr(current.length - value.length) == value); case '!=': return (current != value); case '~=': return current.contains(value, ' '); } return false; }); return (nocash) ? elements : new Elements(elements); } }); /* Script: Element.Selectors.js Css Query related functions and <Element> extensions License: MIT-style license. */ /* Section: Utility Functions */ /* Function: $E Selects a single (i.e. the first found) Element based on the selector passed in and an optional filter element. Returns as <Element>. Arguments: selector - string; the css selector to match filter - optional; a DOM element to limit the scope of the selector match; defaults to document. Example: >$E('a', 'myElement') //find the first anchor tag inside the DOM element with id 'myElement' Returns: a DOM element - the first element that matches the selector */ function $E(selector, filter){ return ($(filter) || document).getElement(selector); }; /* Function: $ES Returns a collection of Elements that match the selector passed in limited to the scope of the optional filter. See Also: <Element.getElements> for an alternate syntax. Returns as <Elements>. Returns: an array of dom elements that match the selector within the filter Arguments: selector - string; css selector to match filter - optional; a DOM element to limit the scope of the selector match; defaults to document. Examples: >$ES("a") //gets all the anchor tags; synonymous with $$("a") >$ES('a','myElement') //get all the anchor tags within $('myElement') */ function $ES(selector, filter){ return ($(filter) || document).getElementsBySelector(selector); }; $$.shared = { 'regexp': /^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([!*^$]?=)["']?([^"'\]]*)["']?)?])?$/, 'xpath': { getParam: function(items, context, param, i){ var temp = [context.namespaceURI ? 'xhtml:' : '', param[1]]; if (param[2]) temp.push('[@id="', param[2], '"]'); if (param[3]) temp.push('[contains(concat(" ", @class, " "), " ', param[3], ' ")]'); if (param[4]){ if (param[5] && param[6]){ switch(param[5]){ case '*=': temp.push('[contains(@', param[4], ', "', param[6], '")]'); break; case '^=': temp.push('[starts-with(@', param[4], ', "', param[6], '")]'); break; case '$=': temp.push('[substring(@', param[4], ', string-length(@', param[4], ') - ', param[6].length, ' + 1) = "', param[6], '"]'); break; case '=': temp.push('[@', param[4], '="', param[6], '"]'); break; case '!=': temp.push('[@', param[4], '!="', param[6], '"]'); } } else { temp.push('[@', param[4], ']'); } } items.push(temp.join('')); return items; }, getItems: function(items, context, nocash){ var elements = []; var xpath = document.evaluate('.//' + items.join('//'), context, $$.shared.resolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0, j = xpath.snapshotLength; i < j; i++) elements.push(xpath.snapshotItem(i)); return (nocash) ? elements : new Elements(elements.map($)); } }, 'normal': { getParam: function(items, context, param, i){ if (i == 0){ if (param[2]){ var el = context.getElementById(param[2]); if (!el || ((param[1] != '*') && (Element.getTag(el) != param[1]))) return false; items = [el]; } else { items = $A(context.getElementsByTagName(param[1])); } } else { items = $$.shared.getElementsByTagName(items, param[1]); if (param[2]) items = Elements.filterById(items, param[2], true); } if (param[3]) items = Elements.filterByClass(items, param[3], true); if (param[4]) items = Elements.filterByAttribute(items, param[4], param[5], param[6], true); return items; }, getItems: function(items, context, nocash){ return (nocash) ? items : $$.unique(items); } }, resolver: function(prefix){ return (prefix == 'xhtml') ? 'http://www.w3.org/1999/xhtml' : false; }, getElementsByTagName: function(context, tagName){ var found = []; for (var i = 0, j = context.length; i < j; i++) found.extend(context[i].getElementsByTagName(tagName)); return found; } }; $$.shared.method = (window.xpath) ? 'xpath' : 'normal'; /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.Methods.Dom = { /* Property: getElements Gets all the elements within an element that match the given (single) selector. Returns as <Elements>. Arguments: selector - string; the css selector to match Examples: >$('myElement').getElements('a'); // get all anchors within myElement >$('myElement').getElements('input[name=dialog]') //get all input tags with name 'dialog' >$('myElement').getElements('input[name$=log]') //get all input tags with names ending with 'log' Notes: Supports these operators in attribute selectors: - = : is equal to - ^= : starts-with - $= : ends-with - != : is not equal to Xpath is used automatically for compliant browsers. */ getElements: function(selector, nocash){ var items = []; selector = selector.trim().split(' '); for (var i = 0, j = selector.length; i < j; i++){ var sel = selector[i]; var param = sel.match($$.shared.regexp); if (!param) break; param[1] = param[1] || '*'; var temp = $$.shared[$$.shared.method].getParam(items, this, param, i); if (!temp) break; items = temp; } return $$.shared[$$.shared.method].getItems(items, this, nocash); }, /* Property: getElement Same as <Element.getElements>, but returns only the first. Alternate syntax for <$E>, where filter is the Element. Returns as <Element>. Arguments: selector - string; css selector */ getElement: function(selector){ return $(this.getElements(selector, true)[0] || false); }, /* Property: getElementsBySelector Same as <Element.getElements>, but allows for comma separated selectors, as in css. Alternate syntax for <$$>, where filter is the Element. Returns as <Elements>. Arguments: selector - string; css selector */ getElementsBySelector: function(selector, nocash){ var elements = []; selector = selector.split(','); for (var i = 0, j = selector.length; i < j; i++) elements = elements.concat(this.getElements(selector[i], true)); return (nocash) ? elements : $$.unique(elements); } }; Element.extend({ /* Property: getElementById Targets an element with the specified id found inside the Element. Does not overwrite document.getElementById. Arguments: id - string; the id of the element to find. */ getElementById: function(id){ var el = document.getElementById(id); if (!el) return false; for (var parent = el.parentNode; parent != this; parent = parent.parentNode){ if (!parent) return false; } return el; }/*compatibility*/, getElementsByClassName: function(className){ return this.getElements('.' + className); } /*end compatibility*/ }); document.extend(Element.Methods.Dom); Element.extend(Element.Methods.Dom); /* Script: Element.Form.js Contains Element prototypes to deal with Forms and their elements. License: MIT-style license. */ /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: getValue Returns the value of the Element, if its tag is textarea, select or input. getValue called on a multiple select will return an array. */ getValue: function(){ switch(this.getTag()){ case 'select': var values = []; $each(this.options, function(option){ if (option.selected) values.push($pick(option.value, option.text)); }); return (this.multiple) ? values : values[0]; case 'input': if (!(this.checked && ['checkbox', 'radio'].contains(this.type)) && !['hidden', 'text', 'password'].contains(this.type)) break; case 'textarea': return this.value; } return false; }, getFormElements: function(){ return $$(this.getElementsByTagName('input'), this.getElementsByTagName('select'), this.getElementsByTagName('textarea')); }, /* Property: toQueryString Reads the children inputs of the Element and generates a query string, based on their values. Used internally in <Ajax> Example: (start code) <form id="myForm" action="submit.php"> <input name="email" value="bob@bob.com"> <input name="zipCode" value="90210"> </form> <script> $('myForm').toQueryString() </script> (end) Returns: email=bob@bob.com&zipCode=90210 */ toQueryString: function(){ var queryString = []; this.getFormElements().each(function(el){ var name = el.name; var value = el.getValue(); if (value === false || !name || el.disabled) return; var qs = function(val){ queryString.push(name + '=' + encodeURIComponent(val)); }; if ($type(value) == 'array') value.each(qs); else qs(value); }); return queryString.join('&'); } }); /* Script: Element.Dimensions.js Contains Element prototypes to deal with Element size and position in space. Note: The functions in this script require n XHTML doctype. License: MIT-style license. */ /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: scrollTo Scrolls the element to the specified coordinated (if the element has an overflow) Arguments: x - the x coordinate y - the y coordinate Example: >$('myElement').scrollTo(0, 100) */ scrollTo: function(x, y){ this.scrollLeft = x; this.scrollTop = y; }, /* Property: getSize Return an Object representing the size/scroll values of the element. Example: (start code) $('myElement').getSize(); (end) Returns: (start code) { 'scroll': {'x': 100, 'y': 100}, 'size': {'x': 200, 'y': 400}, 'scrollSize': {'x': 300, 'y': 500} } (end) */ getSize: function(){ return { 'scroll': {'x': this.scrollLeft, 'y': this.scrollTop}, 'size': {'x': this.offsetWidth, 'y': this.offsetHeight}, 'scrollSize': {'x': this.scrollWidth, 'y': this.scrollHeight} }; }, /* Property: getPosition Returns the real offsets of the element. Arguments: overflown - optional, an array of nested scrolling containers for scroll offset calculation, use this if your element is inside any element containing scrollbars Example: >$('element').getPosition(); Returns: >{x: 100, y:500}; */ getPosition: function(overflown){ overflown = overflown || []; var el = this, left = 0, top = 0; do { left += el.offsetLeft || 0; top += el.offsetTop || 0; el = el.offsetParent; } while (el); overflown.each(function(element){ left -= element.scrollLeft || 0; top -= element.scrollTop || 0; }); return {'x': left, 'y': top}; }, /* Property: getTop Returns the distance from the top of the window to the Element. Arguments: overflown - optional, an array of nested scrolling containers, see Element::getPosition */ getTop: function(overflown){ return this.getPosition(overflown).y; }, /* Property: getLeft Returns the distance from the left of the window to the Element. Arguments: overflown - optional, an array of nested scrolling containers, see Element::getPosition */ getLeft: function(overflown){ return this.getPosition(overflown).x; }, /* Property: getCoordinates Returns an object with width, height, left, right, top, and bottom, representing the values of the Element Arguments: overflown - optional, an array of nested scrolling containers, see Element::getPosition Example: (start code) var myValues = $('myElement').getCoordinates(); (end) Returns: (start code) { width: 200, height: 300, left: 100, top: 50, right: 300, bottom: 350 } (end) */ getCoordinates: function(overflown){ var position = this.getPosition(overflown); var obj = { 'width': this.offsetWidth, 'height': this.offsetHeight, 'left': position.x, 'top': position.y }; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; } }); /* Script: Window.DomReady.js Contains the custom event domready, for window. License: MIT-style license. */ /* Section: Custom Events */ /* Event: domready executes a function when the dom tree is loaded, without waiting for images. Only works when called from window. Credits: (c) Dean Edwards/Matthias Miller/John Resig, remastered for MooTools. Arguments: fn - the function to execute when the DOM is ready Example: > window.addEvent('domready', function(){ > alert('the dom is ready'); > }); */ Element.Events.domready = { add: function(fn){ if (window.loaded){ fn.call(this); return; } var domReady = function(){ if (window.loaded) return; window.loaded = true; window.timer = $clear(window.timer); this.fireEvent('domready'); }.bind(this); if (document.readyState && window.webkit){ window.timer = function(){ if (['loaded','complete'].contains(document.readyState)) domReady(); }.periodical(50); } else if (document.readyState && window.ie){ if (!$('ie_ready')){ var src = (window.location.protocol == 'https:') ? '://0' : 'javascript:void(0)'; document.write('<script id="ie_ready" defer src="' + src + '"><\/script>'); $('ie_ready').onreadystatechange = function(){ if (this.readyState == 'complete') domReady(); }; } } else { window.addListener("load", domReady); document.addListener("DOMContentLoaded", domReady); } } }; /*compatibility*/ window.onDomReady = function(fn){ return this.addEvent('domready', fn); }; /*end compatibility*/ /* Script: Window.Size.js Window cross-browser dimensions methods. Note: The Functions in this script require an XHTML doctype. License: MIT-style license. */ /* Class: window Cross browser methods to get various window dimensions. Warning: All these methods require that the browser operates in strict mode, not quirks mode. */ window.extend({ /* Property: getWidth Returns an integer representing the width of the browser window (without the scrollbar). */ getWidth: function(){ if (this.webkit419) return this.innerWidth; if (this.opera) return document.body.clientWidth; return document.documentElement.clientWidth; }, /* Property: getHeight Returns an integer representing the height of the browser window (without the scrollbar). */ getHeight: function(){ if (this.webkit419) return this.innerHeight; if (this.opera) return document.body.clientHeight; return document.documentElement.clientHeight; }, /* Property: getScrollWidth Returns an integer representing the scrollWidth of the window. This value is equal to or bigger than <getWidth>. See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollWidth> */ getScrollWidth: function(){ if (this.ie) return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth); if (this.webkit) return document.body.scrollWidth; return document.documentElement.scrollWidth; }, /* Property: getScrollHeight Returns an integer representing the scrollHeight of the window. This value is equal to or bigger than <getHeight>. See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollHeight> */ getScrollHeight: function(){ if (this.ie) return Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight); if (this.webkit) return document.body.scrollHeight; return document.documentElement.scrollHeight; }, /* Property: getScrollLeft Returns an integer representing the scrollLeft of the window (the number of pixels the window has scrolled from the left). See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollLeft> */ getScrollLeft: function(){ return this.pageXOffset || document.documentElement.scrollLeft; }, /* Property: getScrollTop Returns an integer representing the scrollTop of the window (the number of pixels the window has scrolled from the top). See Also: <http://developer.mozilla.org/en/docs/DOM:element.scrollTop> */ getScrollTop: function(){ return this.pageYOffset || document.documentElement.scrollTop; }, /* Property: getSize Same as <Element.getSize> */ getSize: function(){ return { 'size': {'x': this.getWidth(), 'y': this.getHeight()}, 'scrollSize': {'x': this.getScrollWidth(), 'y': this.getScrollHeight()}, 'scroll': {'x': this.getScrollLeft(), 'y': this.getScrollTop()} }; }, //ignore getPosition: function(){return {'x': 0, 'y': 0};} }); /* Script: Fx.Base.js Contains <Fx.Base>, the foundamentals of the MooTools Effects. License: MIT-style license. */ var Fx = {}; /* Class: Fx.Base Base class for the Effects. Options: transition - the equation to use for the effect see <Fx.Transitions>; default is <Fx.Transitions.Sine.easeInOut> duration - the duration of the effect in ms; 500 is the default. unit - the unit is 'px' by default (other values include things like 'em' for fonts or '%'). wait - boolean: to wait or not to wait for a current transition to end before running another of the same instance. defaults to true. fps - the frames per second for the transition; default is 50 Events: onStart - the function to execute as the effect begins; nothing (<Class.empty>) by default. onComplete - the function to execute after the effect has processed; nothing (<Class.empty>) by default. onCancel - the function to execute when you manually stop the effect. */ Fx.Base = new Class({ options: { onStart: Class.empty, onComplete: Class.empty, onCancel: Class.empty, transition: function(p){ return -(Math.cos(Math.PI * p) - 1) / 2; }, duration: 500, unit: 'px', wait: true, fps: 50 }, initialize: function(options){ this.element = this.element || null; this.setOptions(options); if (this.options.initialize) this.options.initialize.call(this); }, step: function(){ var time = $time(); if (time < this.time + this.options.duration){ this.delta = this.options.transition((time - this.time) / this.options.duration); this.setNow(); this.increase(); } else { this.stop(true); this.set(this.to); this.fireEvent('onComplete', this.element, 10); this.callChain(); } }, /* Property: set Immediately sets the value with no transition. Arguments: to - the point to jump to Example: >var myFx = new Fx.Style('myElement', 'opacity').set(0); //will make it immediately transparent */ set: function(to){ this.now = to; this.increase(); return this; }, setNow: function(){ this.now = this.compute(this.from, this.to); }, compute: function(from, to){ return (to - from) * this.delta + from; }, /* Property: start Executes an effect from one position to the other. Arguments: from - integer: staring value to - integer: the ending value Examples: >var myFx = new Fx.Style('myElement', 'opacity').start(0,1); //display a transition from transparent to opaque. */ start: function(from, to){ if (!this.options.wait) this.stop(); else if (this.timer) return this; this.from = from; this.to = to; this.change = this.to - this.from; this.time = $time(); this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this); this.fireEvent('onStart', this.element); return this; }, /* Property: stop Stops the transition. */ stop: function(end){ if (!this.timer) return this; this.timer = $clear(this.timer); if (!end) this.fireEvent('onCancel', this.element); return this; }/*compatibility*/, custom: function(from, to){ return this.start(from, to); }, clearTimer: function(end){ return this.stop(end); } /*end compatibility*/ }); Fx.Base.implement(new Chain, new Events, new Options); /* Script: Fx.CSS.js Css parsing class for effects. Required by <Fx.Style>, <Fx.Styles>, <Fx.Elements>. No documentation needed, as its used internally. License: MIT-style license. */ Fx.CSS = { select: function(property, to){ if (property.test(/color/i)) return this.Color; var type = $type(to); if ((type == 'array') || (type == 'string' && to.contains(' '))) return this.Multi; return this.Single; }, parse: function(el, property, fromTo){ if (!fromTo.push) fromTo = [fromTo]; var from = fromTo[0], to = fromTo[1]; if (!$chk(to)){ to = from; from = el.getStyle(property); } var css = this.select(property, to); return {'from': css.parse(from), 'to': css.parse(to), 'css': css}; } }; Fx.CSS.Single = { parse: function(value){ return parseFloat(value); }, getNow: function(from, to, fx){ return fx.compute(from, to); }, getValue: function(value, unit, property){ if (unit == 'px' && property != 'opacity') value = Math.round(value); return value + unit; } }; Fx.CSS.Multi = { parse: function(value){ return value.push ? value : value.split(' ').map(function(v){ return parseFloat(v); }); }, getNow: function(from, to, fx){ var now = []; for (var i = 0; i < from.length; i++) now[i] = fx.compute(from[i], to[i]); return now; }, getValue: function(value, unit, property){ if (unit == 'px' && property != 'opacity') value = value.map(Math.round); return value.join(unit + ' ') + unit; } }; Fx.CSS.Color = { parse: function(value){ return value.push ? value : value.hexToRgb(true); }, getNow: function(from, to, fx){ var now = []; for (var i = 0; i < from.length; i++) now[i] = Math.round(fx.compute(from[i], to[i])); return now; }, getValue: function(value){ return 'rgb(' + value.join(',') + ')'; } }; /* Script: Fx.Style.js Contains <Fx.Style> License: MIT-style license. */ /* Class: Fx.Style The Style effect, used to transition any css property from one value to another. Includes colors. Colors must be in hex format. Inherits methods, properties, options and events from <Fx.Base>. Arguments: el - the $(element) to apply the style transition to property - the property to transition options - the Fx.Base options (see: <Fx.Base>) Example: >var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500}); >marginChange.start(10, 100); */ Fx.Style = Fx.Base.extend({ initialize: function(el, property, options){ this.element = $(el); this.property = property; this.parent(options); }, /* Property: hide Same as <Fx.Base.set> (0); hides the element immediately without transition. */ hide: function(){ return this.set(0); }, setNow: function(){ this.now = this.css.getNow(this.from, this.to, this); }, /* Property: set Sets the element's css property (specified at instantiation) to the specified value immediately. Example: (start code) var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500}); marginChange.set(10); //margin-top is set to 10px immediately (end) */ set: function(to){ this.css = Fx.CSS.select(this.property, to); return this.parent(this.css.parse(to)); }, /* Property: start Displays the transition to the value/values passed in Arguments: from - (integer; optional) the starting position for the transition to - (integer) the ending position for the transition Note: If you provide only one argument, the transition will use the current css value for its starting value. Example: (start code) var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500}); marginChange.start(10); //tries to read current margin top value and goes from current to 10 (end) */ start: function(from, to){ if (this.timer && this.options.wait) return this; var parsed = Fx.CSS.parse(this.element, this.property, [from, to]); this.css = parsed.css; return this.parent(parsed.from, parsed.to); }, increase: function(){ this.element.setStyle(this.property, this.css.getValue(this.now, this.options.unit, this.property)); } }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: effect Applies an <Fx.Style> to the Element; This a shortcut for <Fx.Style>. Arguments: property - (string) the css property to alter options - (object; optional) key/value set of options (see <Fx.Style>) Example: >var myEffect = $('myElement').effect('height', {duration: 1000, transition: Fx.Transitions.linear}); >myEffect.start(10, 100); >//OR >$('myElement').effect('height', {duration: 1000, transition: Fx.Transitions.linear}).start(10,100); */ effect: function(property, options){ return new Fx.Style(this, property, options); } }); /* Script: Fx.Styles.js Contains <Fx.Styles> License: MIT-style license. */ /* Class: Fx.Styles Allows you to animate multiple css properties at once; Colors must be in hex format. Inherits methods, properties, options and events from <Fx.Base>. Arguments: el - the $(element) to apply the styles transition to options - the fx options (see: <Fx.Base>) Example: (start code) var myEffects = new Fx.Styles('myElement', {duration: 1000, transition: Fx.Transitions.linear}); //height from 10 to 100 and width from 900 to 300 myEffects.start({ 'height': [10, 100], 'width': [900, 300] }); //or height from current height to 100 and width from current width to 300 myEffects.start({ 'height': 100, 'width': 300 }); (end) */ Fx.Styles = Fx.Base.extend({ initialize: function(el, options){ this.element = $(el); this.parent(options); }, setNow: function(){ for (var p in this.from) this.now[p] = this.css[p].getNow(this.from[p], this.to[p], this); }, set: function(to){ var parsed = {}; this.css = {}; for (var p in to){ this.css[p] = Fx.CSS.select(p, to[p]); parsed[p] = this.css[p].parse(to[p]); } return this.parent(parsed); }, /* Property: start Executes a transition for any number of css properties in tandem. Arguments: obj - an object containing keys that specify css properties to alter and values that specify either the from/to values (as an array) or just the end value (an integer). Example: see <Fx.Styles> */ start: function(obj){ if (this.timer && this.options.wait) return this; this.now = {}; this.css = {}; var from = {}, to = {}; for (var p in obj){ var parsed = Fx.CSS.parse(this.element, p, obj[p]); from[p] = parsed.from; to[p] = parsed.to; this.css[p] = parsed.css; } return this.parent(from, to); }, increase: function(){ for (var p in this.now) this.element.setStyle(p, this.css[p].getValue(this.now[p], this.options.unit, p)); } }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: effects Applies an <Fx.Styles> to the Element; This a shortcut for <Fx.Styles>. Example: >var myEffects = $(myElement).effects({duration: 1000, transition: Fx.Transitions.Sine.easeInOut}); >myEffects.start({'height': [10, 100], 'width': [900, 300]}); */ effects: function(options){ return new Fx.Styles(this, options); } }); /* Script: Fx.Elements.js Contains <Fx.Elements> License: MIT-style license. */ /* Class: Fx.Elements Fx.Elements allows you to apply any number of styles transitions to a selection of elements. Includes colors (must be in hex format). Inherits methods, properties, options and events from <Fx.Base>. Arguments: elements - a collection of elements the effects will be applied to. options - same as <Fx.Base> options. */ Fx.Elements = Fx.Base.extend({ initialize: function(elements, options){ this.elements = $$(elements); this.parent(options); }, setNow: function(){ for (var i in this.from){ var iFrom = this.from[i], iTo = this.to[i], iCss = this.css[i], iNow = this.now[i] = {}; for (var p in iFrom) iNow[p] = iCss[p].getNow(iFrom[p], iTo[p], this); } }, set: function(to){ var parsed = {}; this.css = {}; for (var i in to){ var iTo = to[i], iCss = this.css[i] = {}, iParsed = parsed[i] = {}; for (var p in iTo){ iCss[p] = Fx.CSS.select(p, iTo[p]); iParsed[p] = iCss[p].parse(iTo[p]); } } return this.parent(parsed); }, /* Property: start Applies the passed in style transitions to each object named (see example). Each item in the collection is refered to as a numerical string ("1" for instance). The first item is "0", the second "1", etc. Example: (start code) var myElementsEffects = new Fx.Elements($$('a')); myElementsEffects.start({ '0': { //let's change the first element's opacity and width 'opacity': [0,1], 'width': [100,200] }, '4': { //and the fifth one's opacity 'opacity': [0.2, 0.5] } }); (end) */ start: function(obj){ if (this.timer && this.options.wait) return this; this.now = {}; this.css = {}; var from = {}, to = {}; for (var i in obj){ var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {}, iCss = this.css[i] = {}; for (var p in iProps){ var parsed = Fx.CSS.parse(this.elements[i], p, iProps[p]); iFrom[p] = parsed.from; iTo[p] = parsed.to; iCss[p] = parsed.css; } } return this.parent(from, to); }, increase: function(){ for (var i in this.now){ var iNow = this.now[i], iCss = this.css[i]; for (var p in iNow) this.elements[i].setStyle(p, iCss[p].getValue(iNow[p], this.options.unit, p)); } } }); /* Script: Fx.Scroll.js Contains <Fx.Scroll> License: MIT-style license. */ /* Class: Fx.Scroll Scroll any element with an overflow, including the window element. Inherits methods, properties, options and events from <Fx.Base>. Note: Fx.Scroll requires an XHTML doctype. Arguments: element - the element to scroll options - optional, see Options below. Options: all the Fx.Base options and events, plus: offset - the distance for the scrollTo point/element. an Object with x/y properties. overflown - an array of nested scrolling containers, see <Element.getPosition> */ Fx.Scroll = Fx.Base.extend({ options: { overflown: [], offset: {'x': 0, 'y': 0}, wheelStops: true }, initialize: function(element, options){ this.now = []; this.element = $(element); this.bound = {'stop': this.stop.bind(this, false)}; this.parent(options); if (this.options.wheelStops){ this.addEvent('onStart', function(){ document.addEvent('mousewheel', this.bound.stop); }.bind(this)); this.addEvent('onComplete', function(){ document.removeEvent('mousewheel', this.bound.stop); }.bind(this)); } }, setNow: function(){ for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]); }, /* Property: scrollTo Scrolls the chosen element to the x/y coordinates. Arguments: x - the x coordinate to scroll the element to y - the y coordinate to scroll the element to */ scrollTo: function(x, y){ if (this.timer && this.options.wait) return this; var el = this.element.getSize(); var values = {'x': x, 'y': y}; for (var z in el.size){ var max = el.scrollSize[z] - el.size[z]; if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z].limit(0, max) : max; else values[z] = el.scroll[z]; values[z] += this.options.offset[z]; } return this.start([el.scroll.x, el.scroll.y], [values.x, values.y]); }, /* Property: toTop Scrolls the chosen element to its maximum top. */ toTop: function(){ return this.scrollTo(false, 0); }, /* Property: toBottom Scrolls the chosen element to its maximum bottom. */ toBottom: function(){ return this.scrollTo(false, 'full'); }, /* Property: toLeft Scrolls the chosen element to its maximum left. */ toLeft: function(){ return this.scrollTo(0, false); }, /* Property: toRight Scrolls the chosen element to its maximum right. */ toRight: function(){ return this.scrollTo('full', false); }, /* Property: toElement Scrolls the specified element to the position the passed in element is found. Arguments: el - the $(element) to scroll the window to */ toElement: function(el){ var parent = this.element.getPosition(this.options.overflown); var target = $(el).getPosition(this.options.overflown); return this.scrollTo(target.x - parent.x, target.y - parent.y); }, increase: function(){ this.element.scrollTo(this.now[0], this.now[1]); } }); /* Script: Fx.Slide.js Contains <Fx.Slide> License: MIT-style license. */ /* Class: Fx.Slide The slide effect; slides an element in horizontally or vertically, the contents will fold inside. Inherits methods, properties, options and events from <Fx.Base>. Note: Fx.Slide requires an XHTML doctype. Options: mode - set it to vertical or horizontal. Defaults to vertical. options - all the <Fx.Base> options Example: (start code) var mySlider = new Fx.Slide('myElement', {duration: 500}); mySlider.toggle() //toggle the slider up and down. (end) */ Fx.Slide = Fx.Base.extend({ options: { mode: 'vertical' }, initialize: function(el, options){ this.element = $(el); this.wrapper = new Element('div', {'styles': $extend(this.element.getStyles('margin'), {'overflow': 'hidden'})}).injectAfter(this.element).adopt(this.element); this.element.setStyle('margin', 0); this.setOptions(options); this.now = []; this.parent(this.options); this.open = true; this.addEvent('onComplete', function(){ this.open = (this.now[0] === 0); }); if (window.webkit419) this.addEvent('onComplete', function(){ if (this.open) this.element.remove().inject(this.wrapper); }); }, setNow: function(){ for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]); }, vertical: function(){ this.margin = 'margin-top'; this.layout = 'height'; this.offset = this.element.offsetHeight; }, horizontal: function(){ this.margin = 'margin-left'; this.layout = 'width'; this.offset = this.element.offsetWidth; }, /* Property: slideIn Slides the elements in view horizontally or vertically. Arguments: mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode. */ slideIn: function(mode){ this[mode || this.options.mode](); return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [0, this.offset]); }, /* Property: slideOut Sides the elements out of view horizontally or vertically. Arguments: mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode. */ slideOut: function(mode){ this[mode || this.options.mode](); return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [-this.offset, 0]); }, /* Property: hide Hides the element without a transition. Arguments: mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode. */ hide: function(mode){ this[mode || this.options.mode](); this.open = false; return this.set([-this.offset, 0]); }, /* Property: show Shows the element without a transition. Arguments: mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode. */ show: function(mode){ this[mode || this.options.mode](); this.open = true; return this.set([0, this.offset]); }, /* Property: toggle Slides in or Out the element, depending on its state Arguments: mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode. */ toggle: function(mode){ if (this.wrapper.offsetHeight == 0 || this.wrapper.offsetWidth == 0) return this.slideIn(mode); return this.slideOut(mode); }, increase: function(){ this.element.setStyle(this.margin, this.now[0] + this.options.unit); this.wrapper.setStyle(this.layout, this.now[1] + this.options.unit); } }); /* Script: Fx.Transitions.js Effects transitions, to be used with all the effects. License: MIT-style license. Credits: Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified & optimized to be used with mootools. */ /* Class: Fx.Transitions A collection of tweening transitions for use with the <Fx.Base> classes. Example: >//Elastic.easeOut with default values: >new Fx.Style('margin', {transition: Fx.Transitions.Elastic.easeOut}); >//Elastic.easeOut with user-defined value for elasticity. > var myTransition = new Fx.Transition(Fx.Transitions.Elastic, 3); >new Fx.Style('margin', {transition: myTransition.easeOut}); See also: http://www.robertpenner.com/easing/ */ Fx.Transition = function(transition, params){ params = params || []; if ($type(params) != 'array') params = [params]; return $extend(transition, { easeIn: function(pos){ return transition(pos, params); }, easeOut: function(pos){ return 1 - transition(1 - pos, params); }, easeInOut: function(pos){ return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2; } }); }; Fx.Transitions = new Abstract({ /* Property: linear displays a linear transition. Graph: (see Linear.png) */ linear: function(p){ return p; } }); Fx.Transitions.extend = function(transitions){ for (var transition in transitions){ Fx.Transitions[transition] = new Fx.Transition(transitions[transition]); /*compatibility*/ Fx.Transitions.compat(transition); /*end compatibility*/ } }; /*compatibility*/ Fx.Transitions.compat = function(transition){ ['In', 'Out', 'InOut'].each(function(easeType){ Fx.Transitions[transition.toLowerCase() + easeType] = Fx.Transitions[transition]['ease' + easeType]; }); }; /*end compatibility*/ Fx.Transitions.extend({ /* Property: Quad displays a quadratic transition. Must be used as Quad.easeIn or Quad.easeOut or Quad.easeInOut Graph: (see Quad.png) */ //auto generated /* Property: Cubic displays a cubicular transition. Must be used as Cubic.easeIn or Cubic.easeOut or Cubic.easeInOut Graph: (see Cubic.png) */ //auto generated /* Property: Quart displays a quartetic transition. Must be used as Quart.easeIn or Quart.easeOut or Quart.easeInOut Graph: (see Quart.png) */ //auto generated /* Property: Quint displays a quintic transition. Must be used as Quint.easeIn or Quint.easeOut or Quint.easeInOut Graph: (see Quint.png) */ //auto generated /* Property: Pow Used to generate Quad, Cubic, Quart and Quint. By default is p^6. Graph: (see Pow.png) */ Pow: function(p, x){ return Math.pow(p, x[0] || 6); }, /* Property: Expo displays a exponential transition. Must be used as Expo.easeIn or Expo.easeOut or Expo.easeInOut Graph: (see Expo.png) */ Expo: function(p){ return Math.pow(2, 8 * (p - 1)); }, /* Property: Circ displays a circular transition. Must be used as Circ.easeIn or Circ.easeOut or Circ.easeInOut Graph: (see Circ.png) */ Circ: function(p){ return 1 - Math.sin(Math.acos(p)); }, /* Property: Sine displays a sineousidal transition. Must be used as Sine.easeIn or Sine.easeOut or Sine.easeInOut Graph: (see Sine.png) */ Sine: function(p){ return 1 - Math.sin((1 - p) * Math.PI / 2); }, /* Property: Back makes the transition go back, then all forth. Must be used as Back.easeIn or Back.easeOut or Back.easeInOut Graph: (see Back.png) */ Back: function(p, x){ x = x[0] || 1.618; return Math.pow(p, 2) * ((x + 1) * p - x); }, /* Property: Bounce makes the transition bouncy. Must be used as Bounce.easeIn or Bounce.easeOut or Bounce.easeInOut Graph: (see Bounce.png) */ Bounce: function(p){ var value; for (var a = 0, b = 1; 1; a += b, b /= 2){ if (p >= (7 - 4 * a) / 11){ value = - Math.pow((11 - 6 * a - 11 * p) / 4, 2) + b * b; break; } } return value; }, /* Property: Elastic Elastic curve. Must be used as Elastic.easeIn or Elastic.easeOut or Elastic.easeInOut Graph: (see Elastic.png) */ Elastic: function(p, x){ return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3); } }); ['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){ Fx.Transitions[transition] = new Fx.Transition(function(p){ return Math.pow(p, [i + 2]); }); /*compatibility*/ Fx.Transitions.compat(transition); /*end compatibility*/ }); /* Script: Drag.Base.js Contains <Drag.Base>, <Element.makeResizable> License: MIT-style license. */ var Drag = {}; /* Class: Drag.Base Modify two css properties of an element based on the position of the mouse. Note: Drag.Base requires an XHTML doctype. Arguments: el - the $(element) to apply the transformations to. options - optional. The options object. Options: handle - the $(element) to act as the handle for the draggable element. defaults to the $(element) itself. modifiers - an object. see Modifiers Below. limit - an object, see Limit below. grid - optional, distance in px for snap-to-grid dragging snap - optional, the distance you have to drag before the element starts to respond to the drag. defaults to false modifiers: x - string, the style you want to modify when the mouse moves in an horizontal direction. defaults to 'left' y - string, the style you want to modify when the mouse moves in a vertical direction. defaults to 'top' limit: x - array with start and end limit relative to modifiers.x y - array with start and end limit relative to modifiers.y Events: onStart - optional, function to execute when the user starts to drag (on mousedown); onComplete - optional, function to execute when the user completes the drag. onDrag - optional, function to execute at every step of the drag */ Drag.Base = new Class({ options: { handle: false, unit: 'px', onStart: Class.empty, onBeforeStart: Class.empty, onComplete: Class.empty, onSnap: Class.empty, onDrag: Class.empty, limit: false, modifiers: {x: 'left', y: 'top'}, grid: false, snap: 6 }, initialize: function(el, options){ this.setOptions(options); this.element = $(el); this.handle = $(this.options.handle) || this.element; this.mouse = {'now': {}, 'pos': {}}; this.value = {'start': {}, 'now': {}}; this.bound = { 'start': this.start.bindWithEvent(this), 'check': this.check.bindWithEvent(this), 'drag': this.drag.bindWithEvent(this), 'stop': this.stop.bind(this) }; this.attach(); if (this.options.initialize) this.options.initialize.call(this); }, attach: function(){ this.handle.addEvent('mousedown', this.bound.start); return this; }, detach: function(){ this.handle.removeEvent('mousedown', this.bound.start); return this; }, start: function(event){ this.fireEvent('onBeforeStart', this.element); this.mouse.start = event.page; var limit = this.options.limit; this.limit = {'x': [], 'y': []}; for (var z in this.options.modifiers){ if (!this.options.modifiers[z]) continue; this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt(); this.mouse.pos[z] = event.page[z] - this.value.now[z]; if (limit && limit[z]){ for (var i = 0; i < 2; i++){ if ($chk(limit[z][i])) this.limit[z][i] = ($type(limit[z][i]) == 'function') ? limit[z][i]() : limit[z][i]; } } } if ($type(this.options.grid) == 'number') this.options.grid = {'x': this.options.grid, 'y': this.options.grid}; document.addListener('mousemove', this.bound.check); document.addListener('mouseup', this.bound.stop); this.fireEvent('onStart', this.element); event.stop(); }, check: function(event){ var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2))); if (distance > this.options.snap){ document.removeListener('mousemove', this.bound.check); document.addListener('mousemove', this.bound.drag); this.drag(event); this.fireEvent('onSnap', this.element); } event.stop(); }, drag: function(event){ this.out = false; this.mouse.now = event.page; for (var z in this.options.modifiers){ if (!this.options.modifiers[z]) continue; this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z]; if (this.limit[z]){ if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){ this.value.now[z] = this.limit[z][1]; this.out = true; } else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){ this.value.now[z] = this.limit[z][0]; this.out = true; } } if (this.options.grid[z]) this.value.now[z] -= (this.value.now[z] % this.options.grid[z]); this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit); } this.fireEvent('onDrag', this.element); event.stop(); }, stop: function(){ document.removeListener('mousemove', this.bound.check); document.removeListener('mousemove', this.bound.drag); document.removeListener('mouseup', this.bound.stop); this.fireEvent('onComplete', this.element); } }); Drag.Base.implement(new Events, new Options); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: makeResizable Makes an element resizable (by dragging) with the supplied options. Arguments: options - see <Drag.Base> for acceptable options. */ makeResizable: function(options){ return new Drag.Base(this, $merge({modifiers: {x: 'width', y: 'height'}}, options)); } }); /* Script: Drag.Move.js Contains <Drag.Move>, <Element.makeDraggable> License: MIT-style license. */ /* Class: Drag.Move Extends <Drag.Base>, has additional functionality for dragging an element, support snapping and droppables. Drag.move supports either position absolute or relative. If no position is found, absolute will be set. Inherits methods, properties, options and events from <Drag.Base>. Note: Drag.Move requires an XHTML doctype. Arguments: el - the $(element) to apply the drag to. options - optional. see Options below. Options: all the drag.Base options, plus: container - an element, will fill automatically limiting options based on the $(element) size and position. defaults to false (no limiting) droppables - an array of elements you can drop your draggable to. overflown - an array of nested scrolling containers, see Element::getPosition */ Drag.Move = Drag.Base.extend({ options: { droppables: [], container: false, overflown: [] }, initialize: function(el, options){ this.setOptions(options); this.element = $(el); this.droppables = $$(this.options.droppables); this.container = $(this.options.container); this.position = {'element': this.element.getStyle('position'), 'container': false}; if (this.container) this.position.container = this.container.getStyle('position'); if (!['relative', 'absolute', 'fixed'].contains(this.position.element)) this.position.element = 'absolute'; var top = this.element.getStyle('top').toInt(); var left = this.element.getStyle('left').toInt(); if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){ top = $chk(top) ? top : this.element.getTop(this.options.overflown); left = $chk(left) ? left : this.element.getLeft(this.options.overflown); } else { top = $chk(top) ? top : 0; left = $chk(left) ? left : 0; } this.element.setStyles({'top': top, 'left': left, 'position': this.position.element}); this.parent(this.element); }, start: function(event){ this.overed = null; if (this.container){ var cont = this.container.getCoordinates(); var el = this.element.getCoordinates(); if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){ this.options.limit = { 'x': [cont.left, cont.right - el.width], 'y': [cont.top, cont.bottom - el.height] }; } else { this.options.limit = { 'y': [0, cont.height - el.height], 'x': [0, cont.width - el.width] }; } } this.parent(event); }, drag: function(event){ this.parent(event); var overed = this.out ? false : this.droppables.filter(this.checkAgainst, this).getLast(); if (this.overed != overed){ if (this.overed) this.overed.fireEvent('leave', [this.element, this]); this.overed = overed ? overed.fireEvent('over', [this.element, this]) : null; } return this; }, checkAgainst: function(el){ el = el.getCoordinates(this.options.overflown); var now = this.mouse.now; return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top); }, stop: function(){ if (this.overed && !this.out) this.overed.fireEvent('drop', [this.element, this]); else this.element.fireEvent('emptydrop', this); this.parent(); return this; } }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: makeDraggable Makes an element draggable with the supplied options. Arguments: options - see <Drag.Move> and <Drag.Base> for acceptable options. */ makeDraggable: function(options){ return new Drag.Move(this, options); } }); /* Script: XHR.js Contains the basic XMLHttpRequest Class Wrapper. License: MIT-style license. */ /* Class: XHR Basic XMLHttpRequest Wrapper. Arguments: options - an object with options names as keys. See options below. Options: method - 'post' or 'get' - the protocol for the request; optional, defaults to 'post'. async - boolean: asynchronous option; true uses asynchronous requests. Defaults to true. encoding - the encoding, defaults to utf-8. autoCancel - cancels the already running request if another one is sent. defaults to false. headers - accepts an object, that will be set to request headers. Events: onRequest - function to execute when the XHR request is fired. onSuccess - function to execute when the XHR request completes. onStateChange - function to execute when the state of the XMLHttpRequest changes. onFailure - function to execute when the state of the XMLHttpRequest changes. Properties: running - true if the request is running. response - object, text and xml as keys. You can access this property in the onSuccess event. Example: >var myXHR = new XHR({method: 'get'}).send('http://site.com/requestHandler.php', 'name=john&lastname=dorian'); */ var XHR = new Class({ options: { method: 'post', async: true, onRequest: Class.empty, onSuccess: Class.empty, onFailure: Class.empty, urlEncoded: true, encoding: 'utf-8', autoCancel: false, headers: {} }, setTransport: function(){ this.transport = (window.XMLHttpRequest) ? new XMLHttpRequest() : (window.ie ? new ActiveXObject('Microsoft.XMLHTTP') : false); return this; }, initialize: function(options){ this.setTransport().setOptions(options); this.options.isSuccess = this.options.isSuccess || this.isSuccess; this.headers = {}; if (this.options.urlEncoded && this.options.method == 'post'){ var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; this.setHeader('Content-type', 'application/x-www-form-urlencoded' + encoding); } if (this.options.initialize) this.options.initialize.call(this); }, onStateChange: function(){ if (this.transport.readyState != 4 || !this.running) return; this.running = false; var status = 0; try {status = this.transport.status;} catch(e){}; if (this.options.isSuccess.call(this, status)) this.onSuccess(); else this.onFailure(); this.transport.onreadystatechange = Class.empty; }, isSuccess: function(status){ return ((status >= 200) && (status < 300)); }, onSuccess: function(){ this.response = { 'text': this.transport.responseText, 'xml': this.transport.responseXML }; this.fireEvent('onSuccess', [this.response.text, this.response.xml]); this.callChain(); }, onFailure: function(){ this.fireEvent('onFailure', this.transport); }, /* Property: setHeader Add/modify an header for the request. It will not override headers from the options. Example: >var myXhr = new XHR(url, {method: 'get', headers: {'X-Request': 'JSON'}}); >myXhr.setHeader('Last-Modified','Sat, 1 Jan 2005 05:00:00 GMT'); */ setHeader: function(name, value){ this.headers[name] = value; return this; }, /* Property: send Opens the XHR connection and sends the data. Data has to be null or a string. Example: >var myXhr = new XHR({method: 'post'}); >myXhr.send(url, querystring); > >var syncXhr = new XHR({async: false, method: 'post'}); >syncXhr.send(url, null); > */ send: function(url, data){ if (this.options.autoCancel) this.cancel(); else if (this.running) return this; this.running = true; if (data && this.options.method == 'get'){ url = url + (url.contains('?') ? '&' : '?') + data; data = null; } this.transport.open(this.options.method.toUpperCase(), url, this.options.async); this.transport.onreadystatechange = this.onStateChange.bind(this); if ((this.options.method == 'post') && this.transport.overrideMimeType) this.setHeader('Connection', 'close'); $extend(this.headers, this.options.headers); for (var type in this.headers) try {this.transport.setRequestHeader(type, this.headers[type]);} catch(e){}; this.fireEvent('onRequest'); this.transport.send($pick(data, null)); return this; }, /* Property: cancel Cancels the running request. No effect if the request is not running. Example: >var myXhr = new XHR({method: 'get'}).send(url); >myXhr.cancel(); */ cancel: function(){ if (!this.running) return this; this.running = false; this.transport.abort(); this.transport.onreadystatechange = Class.empty; this.setTransport(); this.fireEvent('onCancel'); return this; } }); XHR.implement(new Chain, new Events, new Options); /* Script: Ajax.js Contains the <Ajax> class. Also contains methods to generate querystings from forms and Objects. Credits: Loosely based on the version from prototype.js <http://prototype.conio.net> License: MIT-style license. */ /* Class: Ajax An Ajax class, For all your asynchronous needs. Inherits methods, properties, options and events from <XHR>. Arguments: url - the url pointing to the server-side script. options - optional, an object containing options. Options: data - you can write parameters here. Can be a querystring, an object or a Form element. update - $(element) to insert the response text of the XHR into, upon completion of the request. evalScripts - boolean; default is false. Execute scripts in the response text onComplete. When the response is javascript the whole response is evaluated. evalResponse - boolean; default is false. Force global evalulation of the whole response, no matter what content-type it is. Events: onComplete - function to execute when the ajax request completes. Example: >var myAjax = new Ajax(url, {method: 'get'}).request(); */ var Ajax = XHR.extend({ options: { data: null, update: null, onComplete: Class.empty, evalScripts: false, evalResponse: false }, initialize: function(url, options){ this.addEvent('onSuccess', this.onComplete); this.setOptions(options); /*compatibility*/ this.options.data = this.options.data || this.options.postBody; /*end compatibility*/ if (!['post', 'get'].contains(this.options.method)){ this._method = '_method=' + this.options.method; this.options.method = 'post'; } this.parent(); this.setHeader('X-Requested-With', 'XMLHttpRequest'); this.setHeader('Accept', 'text/javascript, text/html, application/xml, text/xml, */*'); this.url = url; }, onComplete: function(){ if (this.options.update) $(this.options.update).empty().setHTML(this.response.text); if (this.options.evalScripts || this.options.evalResponse) this.evalScripts(); this.fireEvent('onComplete', [this.response.text, this.response.xml], 20); }, /* Property: request Executes the ajax request. Example: >var myAjax = new Ajax(url, {method: 'get'}); >myAjax.request(); OR >new Ajax(url, {method: 'get'}).request(); */ request: function(data){ data = data || this.options.data; switch($type(data)){ case 'element': data = $(data).toQueryString(); break; case 'object': data = Object.toQueryString(data); } if (this._method) data = (data) ? [this._method, data].join('&') : this._method; return this.send(this.url, data); }, /* Property: evalScripts Executes scripts in the response text */ evalScripts: function(){ var script, scripts; if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) scripts = this.response.text; else { scripts = []; var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi; while ((script = regexp.exec(this.response.text))) scripts.push(script[1]); scripts = scripts.join('\n'); } if (scripts) (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0); }, /* Property: getHeader Returns the given response header or null */ getHeader: function(name){ try {return this.transport.getResponseHeader(name);} catch(e){}; return null; } }); /* Section: Object related Functions */ /* Function: Object.toQueryString Generates a querystring from key/pair values in an object Arguments: source - the object to generate the querystring from. Returns: the query string. Example: >Object.toQueryString({apple: "red", lemon: "yellow"}); //returns "apple=red&lemon=yellow" */ Object.toQueryString = function(source){ var queryString = []; for (var property in source) queryString.push(encodeURIComponent(property) + '=' + encodeURIComponent(source[property])); return queryString.join('&'); }; /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: send Sends a form with an ajax post request Arguments: options - option collection for ajax request. See <Ajax> for the options list. Returns: The Ajax Class Instance Example: (start code) <form id="myForm" action="submit.php"> <input name="email" value="bob@bob.com"> <input name="zipCode" value="90210"> </form> <script> $('myForm').send() </script> (end) */ send: function(options){ return new Ajax(this.getProperty('action'), $merge({data: this.toQueryString()}, options, {method: 'post'})).request(); } }); /* Script: Cookie.js A cookie reader/creator Credits: based on the functions by Peter-Paul Koch (http://quirksmode.org) */ /* Class: Cookie Class for creating, getting, and removing cookies. */ var Cookie = new Abstract({ options: { domain: false, path: false, duration: false, secure: false }, /* Property: set Sets a cookie in the browser. Arguments: key - the key (name) for the cookie value - the value to set, cannot contain semicolons options - an object representing the Cookie options. See Options below. Default values are stored in Cookie.options. Options: domain - the domain the Cookie belongs to. If you want to share the cookie with pages located on a different domain, you have to set this value. Defaults to the current domain. path - the path the Cookie belongs to. If you want to share the cookie with pages located in a different path, you have to set this value, for example to "/" to share the cookie with all pages on the domain. Defaults to the current path. duration - the duration of the Cookie before it expires, in days. If set to false or 0, the cookie will be a session cookie that expires when the browser is closed. This is default. secure - Stored cookie information can be accessed only from a secure environment. Returns: An object with the options, the key and the value. You can give it as first parameter to Cookie.remove. Example: >Cookie.set('username', 'Harald'); // session cookie (duration is false), or ... >Cookie.set('username', 'JackBauer', {duration: 1}); // save this for 1 day */ set: function(key, value, options){ options = $merge(this.options, options); value = encodeURIComponent(value); if (options.domain) value += '; domain=' + options.domain; if (options.path) value += '; path=' + options.path; if (options.duration){ var date = new Date(); date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000); value += '; expires=' + date.toGMTString(); } if (options.secure) value += '; secure'; document.cookie = key + '=' + value; return $extend(options, {'key': key, 'value': value}); }, /* Property: get Gets the value of a cookie. Arguments: key - the name of the cookie you wish to retrieve. Returns: The cookie string value, or false if not found. Example: >Cookie.get("username") //returns JackBauer */ get: function(key){ var value = document.cookie.match('(?:^|;)\\s*' + key.escapeRegExp() + '=([^;]*)'); return value ? decodeURIComponent(value[1]) : false; }, /* Property: remove Removes a cookie from the browser. Arguments: cookie - the name of the cookie to remove or a previous cookie (for domains) options - optional. you can also pass the domain and path here. Same as options in <Cookie.set> Examples: >Cookie.remove('username') //bye-bye JackBauer, cya in 24 hours > >var myCookie = Cookie.set('username', 'Aaron', {domain: 'mootools.net'}); // Cookie.set returns an object with all values need to remove the cookie >Cookie.remove(myCookie); */ remove: function(cookie, options){ if ($type(cookie) == 'object') this.set(cookie.key, '', $merge(cookie, {duration: -1})); else this.set(cookie, '', $merge(options, {duration: -1})); } }); /* Script: Json.js Simple Json parser and Stringyfier, See: <http://www.json.org/> License: MIT-style license. */ /* Class: Json Simple Json parser and Stringyfier, See: <http://www.json.org/> */ var Json = { /* Property: toString Converts an object to a string, to be passed in server-side scripts as a parameter. Although its not normal usage for this class, this method can also be used to convert functions and arrays to strings. Arguments: obj - the object to convert to string Returns: A json string Example: (start code) Json.toString({apple: 'red', lemon: 'yellow'}); '{"apple":"red","lemon":"yellow"}' (end) */ toString: function(obj){ switch($type(obj)){ case 'string': return '"' + obj.replace(/(["\\])/g, '\\$1') + '"'; case 'array': return '[' + obj.map(Json.toString).join(',') + ']'; case 'object': var string = []; for (var property in obj) string.push(Json.toString(property) + ':' + Json.toString(obj[property])); return '{' + string.join(',') + '}'; case 'number': if (isFinite(obj)) break; case false: return 'null'; } return String(obj); }, /* Property: evaluate converts a json string to an javascript Object. Arguments: str - the string to evaluate. if its not a string, it returns false. secure - optionally, performs syntax check on json string. Defaults to false. Credits: Json test regexp is by Douglas Crockford <http://crockford.org>. Example: >var myObject = Json.evaluate('{"apple":"red","lemon":"yellow"}'); >//myObject will become {apple: 'red', lemon: 'yellow'} */ evaluate: function(str, secure){ return (($type(str) != 'string') || (secure && !str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/))) ? null : eval('(' + str + ')'); } }; /* Script: Json.Remote.js Contains <Json.Remote>. License: MIT-style license. */ /* Class: Json.Remote Wrapped XHR with automated sending and receiving of Javascript Objects in Json Format. Inherits methods, properties, options and events from <XHR>. Arguments: url - the url you want to send your object to. options - see <XHR> options Example: this code will send user information based on name/last name (start code) var jSonRequest = new Json.Remote("http://site.com/tellMeAge.php", {onComplete: function(person){ alert(person.age); //is 25 years alert(person.height); //is 170 cm alert(person.weight); //is 120 kg }}).send({'name': 'John', 'lastName': 'Doe'}); (end) */ Json.Remote = XHR.extend({ initialize: function(url, options){ this.url = url; this.addEvent('onSuccess', this.onComplete); this.parent(options); this.setHeader('X-Request', 'JSON'); }, send: function(obj){ return this.parent(this.url, 'json=' + Json.toString(obj)); }, onComplete: function(){ this.fireEvent('onComplete', [Json.evaluate(this.response.text, this.options.secure)]); } }); /* Script: Assets.js provides dynamic loading for images, css and javascript files. License: MIT-style license. */ var Asset = new Abstract({ /* Property: javascript Injects a javascript file in the page. Arguments: source - the path of the javascript file properties - some additional attributes you might want to add to the script element Example: > new Asset.javascript('/scripts/myScript.js', {id: 'myScript'}); */ javascript: function(source, properties){ properties = $merge({ 'onload': Class.empty }, properties); var script = new Element('script', {'src': source}).addEvents({ 'load': properties.onload, 'readystatechange': function(){ if (this.readyState == 'complete') this.fireEvent('load'); } }); delete properties.onload; return script.setProperties(properties).inject(document.head); }, /* Property: css Injects a css file in the page. Arguments: source - the path of the css file properties - some additional attributes you might want to add to the link element Example: > new Asset.css('/css/myStyle.css', {id: 'myStyle', title: 'myStyle'}); */ css: function(source, properties){ return new Element('link', $merge({ 'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': source }, properties)).inject(document.head); }, /* Property: image Preloads an image and returns the img element. does not inject it to the page. Arguments: source - the path of the image file properties - some additional attributes you might want to add to the img element Example: > new Asset.image('/images/myImage.png', {id: 'myImage', title: 'myImage', onload: myFunction}); Returns: the img element. you can inject it anywhere you want with <Element.injectInside>/<Element.injectAfter>/<Element.injectBefore> */ image: function(source, properties){ properties = $merge({ 'onload': Class.empty, 'onabort': Class.empty, 'onerror': Class.empty }, properties); var image = new Image(); image.src = source; var element = new Element('img', {'src': source}); ['load', 'abort', 'error'].each(function(type){ var event = properties['on' + type]; delete properties['on' + type]; element.addEvent(type, function(){ this.removeEvent(type, arguments.callee); event.call(this); }); }); if (image.width && image.height) element.fireEvent('load', element, 1); return element.setProperties(properties); }, /* Property: images Preloads an array of images (as strings) and returns an array of img elements. does not inject them to the page. Arguments: sources - array, the paths of the image files options - object, see below Options: onComplete - a function to execute when all image files are loaded in the browser's cache onProgress - a function to execute when one image file is loaded in the browser's cache Example: (start code) new Asset.images(['/images/myImage.png', '/images/myImage2.gif'], { onComplete: function(){ alert('all images loaded!'); } }); (end) Returns: the img elements as $$. you can inject them anywhere you want with <Element.injectInside>/<Element.injectAfter>/<Element.injectBefore> */ images: function(sources, options){ options = $merge({ onComplete: Class.empty, onProgress: Class.empty }, options); if (!sources.push) sources = [sources]; var images = []; var counter = 0; sources.each(function(source){ var img = new Asset.image(source, { 'onload': function(){ options.onProgress.call(this, counter); counter++; if (counter == sources.length) options.onComplete(); } }); images.push(img); }); return new Elements(images); } }); /* Script: Hash.js Contains the class Hash. License: MIT-style license. */ /* Class: Hash It wraps an object that it uses internally as a map. The user must use set(), get(), and remove() to add/change, retrieve and remove values, it must not access the internal object directly. null/undefined values are allowed. Note: Each hash instance has the length property. Arguments: obj - an object to convert into a Hash instance. Example: (start code) var hash = new Hash({a: 'hi', b: 'world', c: 'howdy'}); hash.remove('b'); // b is removed. hash.set('c', 'hello'); hash.get('c'); // returns 'hello' hash.length // returns 2 (a and c) (end) */ var Hash = new Class({ length: 0, initialize: function(object){ this.obj = object || {}; this.setLength(); }, /* Property: get Retrieves a value from the hash. Arguments: key - The key Returns: The value */ get: function(key){ return (this.hasKey(key)) ? this.obj[key] : null; }, /* Property: hasKey Check the presence of a specified key-value pair in the hash. Arguments: key - The key Returns: True if the Hash contains a value for the specified key, otherwise false */ hasKey: function(key){ return (key in this.obj); }, /* Property: set Adds a key-value pair to the hash or replaces a previous value associated with the key. Arguments: key - The key value - The value */ set: function(key, value){ if (!this.hasKey(key)) this.length++; this.obj[key] = value; return this; }, setLength: function(){ this.length = 0; for (var p in this.obj) this.length++; return this; }, /* Property: remove Removes a key-value pair from the hash. Arguments: key - The key */ remove: function(key){ if (this.hasKey(key)){ delete this.obj[key]; this.length--; } return this; }, /* Property: each Calls a function for each key-value pair. The first argument passed to the function will be the value, the second one will be the key, like $each. Arguments: fn - The function to call for each key-value pair bind - Optional, the object that will be referred to as "this" in the function */ each: function(fn, bind){ $each(this.obj, fn, bind); }, /* Property: extend Extends the current hash with an object containing key-value pairs. Values for duplicate keys will be replaced by the new ones. Arguments: obj - An object containing key-value pairs */ extend: function(obj){ $extend(this.obj, obj); return this.setLength(); }, /* Property: merge Merges the current hash with multiple objects. */ merge: function(){ this.obj = $merge.apply(null, [this.obj].extend(arguments)); return this.setLength(); }, /* Property: empty Empties all hash values properties and values. */ empty: function(){ this.obj = {}; this.length = 0; return this; }, /* Property: keys Returns an array containing all the keys, in the same order as the values returned by <Hash.values>. Returns: An array containing all the keys of the hash */ keys: function(){ var keys = []; for (var property in this.obj) keys.push(property); return keys; }, /* Property: values Returns an array containing all the values, in the same order as the keys returned by <Hash.keys>. Returns: An array containing all the values of the hash */ values: function(){ var values = []; for (var property in this.obj) values.push(this.obj[property]); return values; } }); /* Section: Utility Functions */ /* Function: $H Shortcut to create a Hash from an Object. */ function $H(obj){ return new Hash(obj); }; /* Script: Hash.Cookie.js Stores and loads an Hash as a cookie using Json format. */ /* Class: Hash.Cookie Inherits all the methods from <Hash>, additional methods are save and load. Hash json string has a limit of 4kb (4096byte), so be careful with your Hash size. Creating a new instance automatically loads the data from the Cookie into the Hash. If the Hash is emptied, the cookie is also removed. Arguments: name - the key (name) for the cookie options - options are identical to <Cookie> and are simply passed along to it. In addition, it has the autoSave option, to save the cookie at every operation. defaults to true. Example: (start code) var fruits = new Hash.Cookie('myCookieName', {duration: 3600}); fruits.extend({ 'lemon': 'yellow', 'apple': 'red' }); fruits.set('melon', 'green'); fruits.get('lemon'); // yellow // ... on another page ... values load automatically var fruits = new Hash.Cookie('myCookieName', {duration: 365}); fruits.get('melon'); // green fruits.erase(); // delete cookie (end) */ Hash.Cookie = Hash.extend({ initialize: function(name, options){ this.name = name; this.options = $extend({'autoSave': true}, options || {}); this.load(); }, /* Property: save Saves the Hash to the cookie. If the hash is empty, removes the cookie. Returns: Returns false when the JSON string cookie is too long (4kb), otherwise true. Example: (start code) var login = new Hash.Cookie('userstatus', {autoSave: false}); login.extend({ 'username': 'John', 'credentials': [4, 7, 9] }); login.set('last_message', 'User logged in!'); login.save(); // finally save the Hash (end) */ save: function(){ if (this.length == 0){ Cookie.remove(this.name, this.options); return true; } var str = Json.toString(this.obj); if (str.length > 4096) return false; //cookie would be truncated! Cookie.set(this.name, str, this.options); return true; }, /* Property: load Loads the cookie and assigns it to the Hash. */ load: function(){ this.obj = Json.evaluate(Cookie.get(this.name), true) || {}; this.setLength(); } }); Hash.Cookie.Methods = {}; ['extend', 'set', 'merge', 'empty', 'remove'].each(function(method){ Hash.Cookie.Methods[method] = function(){ Hash.prototype[method].apply(this, arguments); if (this.options.autoSave) this.save(); return this; }; }); Hash.Cookie.implement(Hash.Cookie.Methods); /* Script: Color.js Contains the Color class. License: MIT-style license. */ /* Class: Color Creates a new Color Object, which is an array with some color specific methods. Arguments: color - the hex, the RGB array or the HSB array of the color to create. For HSB colors, you need to specify the second argument. type - a string representing the type of the color to create. needs to be specified if you intend to create the color with HSB values, or an array of HEX values. Can be 'rgb', 'hsb' or 'hex'. Example: (start code) var black = new Color('#000'); var purple = new Color([255,0,255]); // mix black with white and purple, each time at 10% of the new color var darkpurple = black.mix('#fff', purple, 10); $('myDiv').setStyle('background-color', darkpurple); (end) */ var Color = new Class({ initialize: function(color, type){ type = type || (color.push ? 'rgb' : 'hex'); var rgb, hsb; switch(type){ case 'rgb': rgb = color; hsb = rgb.rgbToHsb(); break; case 'hsb': rgb = color.hsbToRgb(); hsb = color; break; default: rgb = color.hexToRgb(true); hsb = rgb.rgbToHsb(); } rgb.hsb = hsb; rgb.hex = rgb.rgbToHex(); return $extend(rgb, Color.prototype); }, /* Property: mix Mixes two or more colors with the Color. Arguments: color - a color to mix. you can use as arguments how many colors as you want to mix with the original one. alpha - if you use a number as the last argument, it will be threated as the amount of the color to mix. */ mix: function(){ var colors = $A(arguments); var alpha = ($type(colors[colors.length - 1]) == 'number') ? colors.pop() : 50; var rgb = this.copy(); colors.each(function(color){ color = new Color(color); for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha)); }); return new Color(rgb, 'rgb'); }, /* Property: invert Inverts the Color. */ invert: function(){ return new Color(this.map(function(value){ return 255 - value; })); }, /* Property: setHue Modifies the hue of the Color, and returns a new one. Arguments: value - the hue to set */ setHue: function(value){ return new Color([value, this.hsb[1], this.hsb[2]], 'hsb'); }, /* Property: setSaturation Changes the saturation of the Color, and returns a new one. Arguments: percent - the percentage of the saturation to set */ setSaturation: function(percent){ return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb'); }, /* Property: setBrightness Changes the brightness of the Color, and returns a new one. Arguments: percent - the percentage of the brightness to set */ setBrightness: function(percent){ return new Color([this.hsb[0], this.hsb[1], percent], 'hsb'); } }); /* Section: Utility Functions */ /* Function: $RGB Shortcut to create a new color, based on red, green, blue values. Arguments: r - (integer) red value (0-255) g - (integer) green value (0-255) b - (integer) blue value (0-255) */ function $RGB(r, g, b){ return new Color([r, g, b], 'rgb'); }; /* Function: $HSB Shortcut to create a new color, based on hue, saturation, brightness values. Arguments: h - (integer) hue value (0-100) s - (integer) saturation value (0-100) b - (integer) brightness value (0-100) */ function $HSB(h, s, b){ return new Color([h, s, b], 'hsb'); }; /* Class: Array A collection of The Array Object prototype methods. */ Array.extend({ /* Property: rgbToHsb Converts a RGB array to an HSB array. Returns: the HSB array. */ rgbToHsb: function(){ var red = this[0], green = this[1], blue = this[2]; var hue, saturation, brightness; var max = Math.max(red, green, blue), min = Math.min(red, green, blue); var delta = max - min; brightness = max / 255; saturation = (max != 0) ? delta / max : 0; if (saturation == 0){ hue = 0; } else { var rr = (max - red) / delta; var gr = (max - green) / delta; var br = (max - blue) / delta; if (red == max) hue = br - gr; else if (green == max) hue = 2 + rr - br; else hue = 4 + gr - rr; hue /= 6; if (hue < 0) hue++; } return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)]; }, /* Property: hsbToRgb Converts an HSB array to an RGB array. Returns: the RGB array. */ hsbToRgb: function(){ var br = Math.round(this[2] / 100 * 255); if (this[1] == 0){ return [br, br, br]; } else { var hue = this[0] % 360; var f = hue % 60; var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255); var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255); var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255); switch(Math.floor(hue / 60)){ case 0: return [br, t, p]; case 1: return [q, br, p]; case 2: return [p, br, t]; case 3: return [p, q, br]; case 4: return [t, p, br]; case 5: return [br, p, q]; } } return false; } }); /* Script: Scroller.js Contains the <Scroller>. License: MIT-style license. */ /* Class: Scroller The Scroller is a class to scroll any element with an overflow (including the window) when the mouse cursor reaches certain buondaries of that element. You must call its start method to start listening to mouse movements. Note: The Scroller requires an XHTML doctype. Arguments: element - required, the element to scroll. options - optional, see options below, and <Fx.Base> options. Options: area - integer, the necessary boundaries to make the element scroll. velocity - integer, velocity ratio, the modifier for the window scrolling speed. Events: onChange - optionally, when the mouse reaches some boundaries, you can choose to alter some other values, instead of the scrolling offsets. Automatically passes as parameters x and y values. */ var Scroller = new Class({ options: { area: 20, velocity: 1, onChange: function(x, y){ this.element.scrollTo(x, y); } }, initialize: function(element, options){ this.setOptions(options); this.element = $(element); this.mousemover = ([window, document].contains(element)) ? $(document.body) : this.element; }, /* Property: start The scroller starts listening to mouse movements. */ start: function(){ this.coord = this.getCoords.bindWithEvent(this); this.mousemover.addListener('mousemove', this.coord); }, /* Property: stop The scroller stops listening to mouse movements. */ stop: function(){ this.mousemover.removeListener('mousemove', this.coord); this.timer = $clear(this.timer); }, getCoords: function(event){ this.page = (this.element == window) ? event.client : event.page; if (!this.timer) this.timer = this.scroll.periodical(50, this); }, scroll: function(){ var el = this.element.getSize(); var pos = this.element.getPosition(); var change = {'x': 0, 'y': 0}; for (var z in this.page){ if (this.page[z] < (this.options.area + pos[z]) && el.scroll[z] != 0) change[z] = (this.page[z] - this.options.area - pos[z]) * this.options.velocity; else if (this.page[z] + this.options.area > (el.size[z] + pos[z]) && el.scroll[z] + el.size[z] != el.scrollSize[z]) change[z] = (this.page[z] - el.size[z] + this.options.area - pos[z]) * this.options.velocity; } if (change.y || change.x) this.fireEvent('onChange', [el.scroll.x + change.x, el.scroll.y + change.y]); } }); Scroller.implement(new Events, new Options); /* Script: Slider.js Contains <Slider> License: MIT-style license. */ /* Class: Slider Creates a slider with two elements: a knob and a container. Returns the values. Note: The Slider requires an XHTML doctype. Arguments: element - the knob container knob - the handle options - see Options below Options: steps - the number of steps for your slider. mode - either 'horizontal' or 'vertical'. defaults to horizontal. offset - relative offset for knob position. default to 0. Events: onChange - a function to fire when the value changes. onComplete - a function to fire when you're done dragging. onTick - optionally, you can alter the onTick behavior, for example displaying an effect of the knob moving to the desired position. Passes as parameter the new position. */ var Slider = new Class({ options: { onChange: Class.empty, onComplete: Class.empty, onTick: function(pos){ this.knob.setStyle(this.p, pos); }, mode: 'horizontal', steps: 100, offset: 0 }, initialize: function(el, knob, options){ this.element = $(el); this.knob = $(knob); this.setOptions(options); this.previousChange = -1; this.previousEnd = -1; this.step = -1; this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this)); var mod, offset; switch(this.options.mode){ case 'horizontal': this.z = 'x'; this.p = 'left'; mod = {'x': 'left', 'y': false}; offset = 'offsetWidth'; break; case 'vertical': this.z = 'y'; this.p = 'top'; mod = {'x': false, 'y': 'top'}; offset = 'offsetHeight'; } this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2); this.half = this.knob[offset]/2; this.getPos = this.element['get' + this.p.capitalize()].bind(this.element); this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset); var lim = {}; lim[this.z] = [- this.options.offset, this.max - this.options.offset]; this.drag = new Drag.Base(this.knob, { limit: lim, modifiers: mod, snap: 0, onStart: function(){ this.draggedKnob(); }.bind(this), onDrag: function(){ this.draggedKnob(); }.bind(this), onComplete: function(){ this.draggedKnob(); this.end(); }.bind(this) }); if (this.options.initialize) this.options.initialize.call(this); }, /* Property: set The slider will get the step you pass. Arguments: step - one integer */ set: function(step){ this.step = step.limit(0, this.options.steps); this.checkStep(); this.end(); this.fireEvent('onTick', this.toPosition(this.step)); return this; }, clickedElement: function(event){ var position = event.page[this.z] - this.getPos() - this.half; position = position.limit(-this.options.offset, this.max -this.options.offset); this.step = this.toStep(position); this.checkStep(); this.end(); this.fireEvent('onTick', position); }, draggedKnob: function(){ this.step = this.toStep(this.drag.value.now[this.z]); this.checkStep(); }, checkStep: function(){ if (this.previousChange != this.step){ this.previousChange = this.step; this.fireEvent('onChange', this.step); } }, end: function(){ if (this.previousEnd !== this.step){ this.previousEnd = this.step; this.fireEvent('onComplete', this.step + ''); } }, toStep: function(position){ return Math.round((position + this.options.offset) / this.max * this.options.steps); }, toPosition: function(step){ return this.max * step / this.options.steps; } }); Slider.implement(new Events); Slider.implement(new Options); /* Script: SmoothScroll.js Contains <SmoothScroll> License: MIT-style license. */ /* Class: SmoothScroll Auto targets all the anchors in a page and display a smooth scrolling effect upon clicking them. Inherits methods, properties, options and events from <Fx.Scroll>. Note: SmoothScroll requires an XHTML doctype. Arguments: options - the Fx.Scroll options (see: <Fx.Scroll>) plus links, a collection of elements you want your smoothscroll on. Defaults to document.links. Example: >new SmoothScroll(); */ var SmoothScroll = Fx.Scroll.extend({ initialize: function(options){ this.parent(window, options); this.links = (this.options.links) ? $$(this.options.links) : $$(document.links); var location = window.location.href.match(/^[^#]*/)[0] + '#'; this.links.each(function(link){ if (link.href.indexOf(location) != 0) return; var anchor = link.href.substr(location.length); if (anchor && $(anchor)) this.useLink(link, anchor); }, this); if (!window.webkit419) this.addEvent('onComplete', function(){ window.location.hash = this.anchor; }); }, useLink: function(link, anchor){ link.addEvent('click', function(event){ this.anchor = anchor; this.toElement(anchor); event.stop(); }.bindWithEvent(this)); } }); /* Script: Sortables.js Contains <Sortables> Class. License: MIT-style license. */ /* Class: Sortables Creates an interface for <Drag.Base> and drop, resorting of a list. Note: The Sortables require an XHTML doctype. Arguments: list - required, the list that will become sortable. options - an Object, see options below. Options: handles - a collection of elements to be used for drag handles. defaults to the elements. Events: onStart - function executed when the item starts dragging onComplete - function executed when the item ends dragging */ var Sortables = new Class({ options: { handles: false, onStart: Class.empty, onComplete: Class.empty, ghost: true, snap: 3, onDragStart: function(element, ghost){ ghost.setStyle('opacity', 0.7); element.setStyle('opacity', 0.7); }, onDragComplete: function(element, ghost){ element.setStyle('opacity', 1); ghost.remove(); this.trash.remove(); } }, initialize: function(list, options){ this.setOptions(options); this.list = $(list); this.elements = this.list.getChildren(); this.handles = (this.options.handles) ? $$(this.options.handles) : this.elements; this.bound = { 'start': [], 'moveGhost': this.moveGhost.bindWithEvent(this) }; for (var i = 0, l = this.handles.length; i < l; i++){ this.bound.start[i] = this.start.bindWithEvent(this, this.elements[i]); } this.attach(); if (this.options.initialize) this.options.initialize.call(this); this.bound.move = this.move.bindWithEvent(this); this.bound.end = this.end.bind(this); }, attach: function(){ this.handles.each(function(handle, i){ handle.addEvent('mousedown', this.bound.start[i]); }, this); }, detach: function(){ this.handles.each(function(handle, i){ handle.removeEvent('mousedown', this.bound.start[i]); }, this); }, start: function(event, el){ this.active = el; this.coordinates = this.list.getCoordinates(); if (this.options.ghost){ var position = el.getPosition(); this.offset = event.page.y - position.y; this.trash = new Element('div').inject(document.body); this.ghost = el.clone().inject(this.trash).setStyles({ 'position': 'absolute', 'left': position.x, 'top': event.page.y - this.offset }); document.addListener('mousemove', this.bound.moveGhost); this.fireEvent('onDragStart', [el, this.ghost]); } document.addListener('mousemove', this.bound.move); document.addListener('mouseup', this.bound.end); this.fireEvent('onStart', el); event.stop(); }, moveGhost: function(event){ var value = event.page.y - this.offset; value = value.limit(this.coordinates.top, this.coordinates.bottom - this.ghost.offsetHeight); this.ghost.setStyle('top', value); event.stop(); }, move: function(event){ var now = event.page.y; this.previous = this.previous || now; var up = ((this.previous - now) > 0); var prev = this.active.getPrevious(); var next = this.active.getNext(); if (prev && up && now < prev.getCoordinates().bottom) this.active.injectBefore(prev); if (next && !up && now > next.getCoordinates().top) this.active.injectAfter(next); this.previous = now; }, serialize: function(converter){ return this.list.getChildren().map(converter || function(el){ return this.elements.indexOf(el); }, this); }, end: function(){ this.previous = null; document.removeListener('mousemove', this.bound.move); document.removeListener('mouseup', this.bound.end); if (this.options.ghost){ document.removeListener('mousemove', this.bound.moveGhost); this.fireEvent('onDragComplete', [this.active, this.ghost]); } this.fireEvent('onComplete', this.active); } }); Sortables.implement(new Events, new Options); /* Script: Tips.js Tooltips, BubbleTips, whatever they are, they will appear on mouseover License: MIT-style license. Credits: The idea behind Tips.js is based on Bubble Tooltips (<http://web-graphics.com/mtarchive/001717.php>) by Alessandro Fulcitiniti <http://web-graphics.com> */ /* Class: Tips Display a tip on any element with a title and/or href. Note: Tips requires an XHTML doctype. Arguments: elements - a collection of elements to apply the tooltips to on mouseover. options - an object. See options Below. Options: maxTitleChars - the maximum number of characters to display in the title of the tip. defaults to 30. showDelay - the delay the onShow method is called. (defaults to 100 ms) hideDelay - the delay the onHide method is called. (defaults to 100 ms) className - the prefix for your tooltip classNames. defaults to 'tool'. the whole tooltip will have as classname: tool-tip the title will have as classname: tool-title the text will have as classname: tool-text offsets - the distance of your tooltip from the mouse. an Object with x/y properties. fixed - if set to true, the toolTip will not follow the mouse. Events: onShow - optionally you can alter the default onShow behaviour with this option (like displaying a fade in effect); onHide - optionally you can alter the default onHide behaviour with this option (like displaying a fade out effect); Example: (start code) <img src="/images/i.png" title="The body of the tooltip is stored in the title" class="toolTipImg"/> <script> var myTips = new Tips($$('.toolTipImg'), { maxTitleChars: 50 //I like my captions a little long }); </script> (end) Note: The title of the element will always be used as the tooltip body. If you put :: on your title, the text before :: will become the tooltip title. */ var Tips = new Class({ options: { onShow: function(tip){ tip.setStyle('visibility', 'visible'); }, onHide: function(tip){ tip.setStyle('visibility', 'hidden'); }, maxTitleChars: 30, showDelay: 100, hideDelay: 100, className: 'tool', offsets: {'x': 16, 'y': 16}, fixed: false }, initialize: function(elements, options){ this.setOptions(options); this.toolTip = new Element('div', { 'class': this.options.className + '-tip', 'styles': { 'position': 'absolute', 'top': '0', 'left': '0', 'visibility': 'hidden' } }).inject(document.body); this.wrapper = new Element('div').inject(this.toolTip); $$(elements).each(this.build, this); if (this.options.initialize) this.options.initialize.call(this); }, build: function(el){ el.$tmp.myTitle = (el.href && el.getTag() == 'a') ? el.href.replace('http://', '') : (el.rel || false); if (el.title){ var dual = el.title.split('::'); if (dual.length > 1){ el.$tmp.myTitle = dual[0].trim(); el.$tmp.myText = dual[1].trim(); } else { el.$tmp.myText = el.title; } el.removeAttribute('title'); } else { el.$tmp.myText = false; } if (el.$tmp.myTitle && el.$tmp.myTitle.length > this.options.maxTitleChars) el.$tmp.myTitle = el.$tmp.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;"; el.addEvent('mouseenter', function(event){ this.start(el); if (!this.options.fixed) this.locate(event); else this.position(el); }.bind(this)); if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this)); var end = this.end.bind(this); el.addEvent('mouseleave', end); el.addEvent('trash', end); }, start: function(el){ this.wrapper.empty(); if (el.$tmp.myTitle){ this.title = new Element('span').inject(new Element('div', {'class': this.options.className + '-title'}).inject(this.wrapper)).setHTML(el.$tmp.myTitle); } if (el.$tmp.myText){ this.text = new Element('span').inject(new Element('div', {'class': this.options.className + '-text'}).inject(this.wrapper)).setHTML(el.$tmp.myText); } $clear(this.timer); this.timer = this.show.delay(this.options.showDelay, this); }, end: function(event){ $clear(this.timer); this.timer = this.hide.delay(this.options.hideDelay, this); }, position: function(element){ var pos = element.getPosition(); this.toolTip.setStyles({ 'left': pos.x + this.options.offsets.x, 'top': pos.y + this.options.offsets.y }); }, locate: function(event){ var win = {'x': window.getWidth(), 'y': window.getHeight()}; var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()}; var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight}; var prop = {'x': 'left', 'y': 'top'}; for (var z in prop){ var pos = event.page[z] + this.options.offsets[z]; if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z]; this.toolTip.setStyle(prop[z], pos); }; }, show: function(){ if (this.options.timeout) this.timer = this.hide.delay(this.options.timeout, this); this.fireEvent('onShow', [this.toolTip]); }, hide: function(){ this.fireEvent('onHide', [this.toolTip]); } }); Tips.implement(new Events, new Options); /* Script: Group.js For Grouping Classes or Elements Events. The Event added to the Group will fire when all of the events of the items of the group are fired. License: MIT-style license. */ /* Class: Group An "Utility" Class. Arguments: List of Class instances Example: (start code) xhr1 = new Ajax('data.js', {evalScript: true}); xhr2 = new Ajax('abstraction.js', {evalScript: true}); xhr3 = new Ajax('template.js', {evalScript: true}); var group = new Group(xhr1, xhr2, xhr3); group.addEvent('onComplete', function(){ alert('All Scripts loaded'); }); xhr1.request(); xhr2.request(); xhr3.request(); (end) */ var Group = new Class({ initialize: function(){ this.instances = $A(arguments); this.events = {}; this.checker = {}; }, /* Property: addEvent adds an event to the stack of events of the Class instances. Arguments: type - string; the event name (e.g. 'onComplete') fn - function to execute when all instances fired this event */ addEvent: function(type, fn){ this.checker[type] = this.checker[type] || {}; this.events[type] = this.events[type] || []; if (this.events[type].contains(fn)) return false; else this.events[type].push(fn); this.instances.each(function(instance, i){ instance.addEvent(type, this.check.bind(this, [type, instance, i])); }, this); return this; }, check: function(type, instance, i){ this.checker[type][i] = true; var every = this.instances.every(function(current, j){ return this.checker[type][j] || false; }, this); if (!every) return; this.checker[type] = {}; this.events[type].each(function(event){ event.call(this, this.instances, instance); }, this); } }); /* Script: Accordion.js Contains <Accordion> License: MIT-style license. */ /* Class: Accordion The Accordion class creates a group of elements that are toggled when their handles are clicked. When one elements toggles in, the others toggles back. Inherits methods, properties, options and events from <Fx.Elements>. Note: The Accordion requires an XHTML doctype. Arguments: togglers - required, a collection of elements, the elements handlers that will be clickable. elements - required, a collection of elements the transitions will be applied to. options - optional, see options below, and <Fx.Base> options and events. Options: show - integer, the Index of the element to show at start. display - integer, the Index of the element to show at start (with a transition). defaults to 0. fixedHeight - integer, if you want the elements to have a fixed height. defaults to false. fixedWidth - integer, if you want the elements to have a fixed width. defaults to false. height - boolean, will add a height transition to the accordion if true. defaults to true. opacity - boolean, will add an opacity transition to the accordion if true. defaults to true. width - boolean, will add a width transition to the accordion if true. defaults to false, css mastery is required to make this work! alwaysHide - boolean, will allow to hide all elements if true, instead of always keeping one element shown. defaults to false. Events: onActive - function to execute when an element starts to show onBackground - function to execute when an element starts to hide */ var Accordion = Fx.Elements.extend({ options: { onActive: Class.empty, onBackground: Class.empty, display: 0, show: false, height: true, width: false, opacity: true, fixedHeight: false, fixedWidth: false, wait: false, alwaysHide: false }, initialize: function(){ var options, togglers, elements, container; $each(arguments, function(argument, i){ switch($type(argument)){ case 'object': options = argument; break; case 'element': container = $(argument); break; default: var temp = $$(argument); if (!togglers) togglers = temp; else elements = temp; } }); this.togglers = togglers || []; this.elements = elements || []; this.container = $(container); this.setOptions(options); this.previous = -1; if (this.options.alwaysHide) this.options.wait = true; if ($chk(this.options.show)){ this.options.display = false; this.previous = this.options.show; } if (this.options.start){ this.options.display = false; this.options.show = false; } this.effects = {}; if (this.options.opacity) this.effects.opacity = 'fullOpacity'; if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth'; if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight'; for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]); this.elements.each(function(el, i){ if (this.options.show === i){ this.fireEvent('onActive', [this.togglers[i], el]); } else { for (var fx in this.effects) el.setStyle(fx, 0); } }, this); this.parent(this.elements); if ($chk(this.options.display)) this.display(this.options.display); }, /* Property: addSection Dynamically adds a new section into the accordion at the specified position. Arguments: toggler - (dom element) the element that toggles the accordion section open. element - (dom element) the element that stretches open when the toggler is clicked. pos - (integer) the index where these objects are to be inserted within the accordion. */ addSection: function(toggler, element, pos){ toggler = $(toggler); element = $(element); var test = this.togglers.contains(toggler); var len = this.togglers.length; this.togglers.include(toggler); this.elements.include(element); if (len && (!test || pos)){ pos = $pick(pos, len - 1); toggler.injectBefore(this.togglers[pos]); element.injectAfter(toggler); } else if (this.container && !test){ toggler.inject(this.container); element.inject(this.container); } var idx = this.togglers.indexOf(toggler); toggler.addEvent('click', this.display.bind(this, idx)); if (this.options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'}); if (this.options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'}); element.fullOpacity = 1; if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth; if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight; element.setStyle('overflow', 'hidden'); if (!test){ for (var fx in this.effects) element.setStyle(fx, 0); } return this; }, /* Property: display Shows a specific section and hides all others. Useful when triggering an accordion from outside. Arguments: index - integer, the index of the item to show, or the actual element to show. */ display: function(index){ index = ($type(index) == 'element') ? this.elements.indexOf(index) : index; if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this; this.previous = index; var obj = {}; this.elements.each(function(el, i){ obj[i] = {}; var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0)); this.fireEvent(hide ? 'onBackground' : 'onActive', [this.togglers[i], el]); for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]]; }, this); return this.start(obj); }, showThisHideOpen: function(index){return this.display(index);} }); Fx.Accordion = Accordion;
JavaScript
/** * @version $Id: switcher.js 10708 2008-08-21 09:58:05Z eddieajau $ * @package Joomla * @subpackage Config * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * Switcher behavior for configuration component * * @package Joomla.Extensions * @subpackage Config * @since 1.5 */ var JSwitcher = new Class({ toggler : null, //holds the active toggler page : null, //holds the active page options : { cookieName: 'switcher' }, initialize: function(toggler, element, options) { this.setOptions(options); var self = this; togglers = $ES('a', toggler); for (i=0; i < togglers.length; i++) { togglers[i].addEvent( 'click', function() { self.switchTo(this); } ); } //hide all elements = element.getElements('div[id^=page-]'); for (i=0; i < elements.length; i++) { this.hide(elements[i]) } this.toggler = $E('a.active', toggler); this.page = $('page-'+ this.toggler.id); this.show(this.page); if (this.options.cookieName) { if((page = Cookie.get(this.options.cookieName))) { this.switchTo($(page)); } } }, switchTo: function(toggler) { page = $chk(toggler) ? $('page-'+toggler.id) : null; if(page && page != this.page) { //hide old element if(this.page) { this.hide(this.page); } //show new element this.show(page); toggler.addClass('active'); if (this.toggler) { this.toggler.removeClass('active'); } this.page = page; this.toggler = toggler; Cookie.set(this.options.cookieName, toggler.id); } }, hide: function(element) { element.setStyle('display', 'none'); }, show: function (element) { element.setStyle('display', 'block'); } }); JSwitcher.implement(new Options); document.switcher = null; window.addEvent('domready', function(){ toggler = $('submenu') element = $('config-document') if(element) { document.switcher = new JSwitcher(toggler, element, {cookieName: toggler.getAttribute('class')}); } });
JavaScript
/* Script: Swiff.Base.js Contains <Swiff>, <Swiff.getVersion>, <Swiff.remote> Author: Valerio Proietti, <http://mad4milk.net> enhanced by Harald Kirschner <http://digitarald.de> Credits: Flash detection 'borrowed' from SWFObject. License: MIT-style license. */ /* Function: Swiff creates a flash object with supplied parameters. Arguments: source - the swf path. properties - an object with key/value pairs. all options are optional. see below. where - the $(element) to inject the flash object. Properties: width - int, the width of the flash object. defaults to 0. height - int, the height of the flash object. defaults to 0. id - string, the id of the flash object. defaults to 'Swiff-Object-num_of_object_inserted'. wmode - string, transparent or opaque. bgcolor - string, hex value for the movie background color. vars - an object of variables (functions, anything) you want to pass to your flash movie Returns: the object element, to be injected somewhere. Important: the $ function on the OBJECT element wont extend it, will just target the movie by its id/reference. So its not possible to use the <Element> methods on it. This is why it has to be injected using $('myFlashContainer').adopt(myObj) instead of $(myObj).injectInside('myFlashContainer'); Example: (start code) var obj = new Swiff('myMovie.swf', { width: 500, height: 400, id: 'myBeautifulMovie', wmode: 'opaque', bgcolor: '#ff3300', vars: { onLoad: myOnloadFunc, myVariable: myJsVar, myVariableString: 'hello' } }); $('myElement').adopt(obj); (end) */ var Swiff = function(source, props){ if (!Swiff.fixed) Swiff.fix(); var instance = Swiff.nextInstance(); Swiff.vars[instance] = {}; props = $merge({ width: 1, height: 1, id: instance, wmode: 'transparent', bgcolor: '#ffffff', allowScriptAccess: 'sameDomain', callBacks: {'onLoad': Class.empty}, params: false }, props || {}); var append = []; for (var p in props.callBacks){ Swiff.vars[instance][p] = props.callBacks[p]; append.push(p + '=Swiff.vars.' + instance + '.' + p); } if (props.params) append.push(Object.toQueryString(props.params)); var swf = source + '?' + append.join('&'); return new Element('div').setHTML( '<object width="', props.width, '" height="', props.height, '" id="', props.id, '" type="application/x-shockwave-flash" data="', swf, '">' ,'<param name="allowScriptAccess" value="', props.allowScriptAccess, '" />' ,'<param name="movie" value="', swf, '" />' ,'<param name="bgcolor" value="', props.bgcolor, '" />' ,'<param name="scale" value="noscale" />' ,'<param name="salign" value="lt" />' ,'<param name="wmode" value="', props.wmode, '" />' ,'</object>').firstChild; }; Swiff.extend = $extend; Swiff.extend({ count: 0, callBacks: {}, vars: {}, nextInstance: function(){ return 'Swiff' + Swiff.count++; }, //from swfObject, fixes bugs in ie+fp9 fix: function(){ Swiff.fixed = true; window.addEvent('beforeunload', function(){ __flash_unloadHandler = __flash_savedUnloadHandler = Class.empty; }); if (!window.ie) return; window.addEvent('unload', function(){ $each(document.getElementsByTagName("object"), function(swf){ swf.style.display = 'none'; for (var p in swf){ if (typeof swf[p] == 'function') swf[p] = Class.empty; } }); }); }, /* Function: Swiff.getVersion gets the major version of the flash player installed. Returns: a number representing the flash version installed, or 0 if no player is installed. */ getVersion: function(){ if (!Swiff.pluginVersion) { var x; if(navigator.plugins && navigator.mimeTypes.length){ x = navigator.plugins["Shockwave Flash"]; if(x && x.description) x = x.description; } else if (window.ie){ try { x = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); x = x.GetVariable("$version"); } catch(e){} } Swiff.pluginVersion = ($type(x) == 'string') ? parseInt(x.match(/\d+/)[0]) : 0; } return Swiff.pluginVersion; }, /* Function: Swiff.remote Calls an ActionScript function from javascript. Requires ExternalInterface. Returns: Whatever the ActionScript Returns */ remote: function(obj, fn){ var rs = obj.CallFunction("<invoke name=\"" + fn + "\" returntype=\"javascript\">" + __flash__argumentsToXML(arguments, 2) + "</invoke>"); return eval(rs); } }); /* Script: Swiff.Uploader.js Contains <Swiff.Uploader> Author: Valerio Proietti, <http://mad4milk.net>, Harald Kirschner, <http://digitarald.de> License: MIT-style license. */ /* Class: Swiff.Uploader creates an uploader instance. Requires an existing Swiff.Uploader.swf instance. Arguments: callBacks - an object, containing key/value pairs, representing the possible callbacks. See below. onLoaded - Callback when the swf is initialized options - types, multiple, queued, swf, url, container callBacks: onOpen - a function to fire when the user opens a file. onProgress - a function to fire when the file is uploading. passes the name, the current uploaded size and the full size. onSelect - a function to fire when the user selects a file. onComplete - a function to fire when the file finishes uploading onError - a function to fire when there is an error. onCancel - a function to fire when the user cancels the file uploading. */ Swiff.Uploader = new Class({ options: { types: false, multiple: true, queued: true, swf: null, url: null, container: null }, callBacks: { onOpen: Class.empty, onProgress: Class.empty, onSelect: Class.empty, onComplete: Class.empty, onError: Class.empty, onCancel: Class.empty }, initialize: function(callBacks, onLoaded, options){ if (Swiff.getVersion() < 8) return false; this.setOptions(options); this.onLoaded = onLoaded; var calls = $extend($merge(this.callBacks), callBacks || {}); for (p in calls) calls[p] = calls[p].bind(this); this.instance = Swiff.nextInstance(); Swiff.callBacks[this.instance] = calls; this.object = Swiff.Uploader.register(this.loaded.bind(this), this.options.swf, this.options.container); return this; }, loaded: function(){ Swiff.remote(this.object, 'create', this.instance, this.options.types, this.options.multiple, this.options.queued, this.options.url); this.onLoaded.delay(10); }, browse: function(){ Swiff.remote(this.object, 'browse', this.instance); }, send: function(url){ Swiff.remote(this.object, 'upload', this.instance, url); }, remove: function(name, size){ Swiff.remote(this.object, 'remove', this.instance, name, size); }, fileIndex: function(name, size){ return Swiff.remote(this.object, 'fileIndex', this.instance, name, size); }, fileList: function(){ return Swiff.remote(this.object, 'filelist', this.instance); } }); Swiff.Uploader.implement(new Options); Swiff.Uploader.extend = $extend; Swiff.Uploader.extend({ swf: 'Swiff.Uploader.swf', callBacks: [], register: function(callBack, url, container){ if (!Swiff.Uploader.object || !Swiff.Uploader.loaded) { Swiff.Uploader.callBacks.push(callBack); if (!Swiff.Uploader.object) { Swiff.Uploader.object = new Swiff(url || Swiff.Uploader.swf, {callBacks: {'onLoad': Swiff.Uploader.onLoad}}); (container || document.body).appendChild(Swiff.Uploader.object); } } else callBack.delay(10); return Swiff.Uploader.object; }, onLoad: function(){ Swiff.Uploader.loaded = true; Swiff.Uploader.callBacks.each(function(fn){ fn.delay(10); }); Swiff.Uploader.callBacks.length = 0; } });
JavaScript
/** * FancyUpload - Flash meets Ajax for beauty uploads * * Based on Swiff.Base and Swiff.Uploader. * * Its intended that you edit this class to add your * own queue layout/text/effects. This is NO include * and forget class. If you want custom effects or * more output, use Swiff.Uploader as interface * for your new class or change this class. * * USAGE: * var inputElement = $E('input[type="file"]'); * new FancyUpload(inputElement, { * swf: '../swf/Swiff.Uploader.swf' * // more options * }) * * The target element has to be in an form, the upload starts onsubmit * by default. * * OPTIONS: * * url: Upload target URL, default is form-action if given, otherwise current page * swf: Path & filename of the swf file, default: Swiff.Uploader.swf * multiple: Multiple files selection, default: true * queued: Queued upload, default: true * types: Object with (description: extension) pairs, default: Images (*.jpg; *.jpeg; *.gif; *.png) * limitSize: Maximum size for one added file, bigger files are ignored, default: false * limitFiles: Maximum files in the queue, default: false * createReplacement: Function that creates the replacement for the input-file, default: false, so a button with "Browse Files" is created * instantStart: Upload starts instantly after selecting a file, default: false * allowDuplicates: Allow duplicate filenames in the queue, default: true * container: Container element for the swf, default: document.body, used only for the first FancyUpload instance, see QUIRKS * optionFxDuration: Fx duration for highlight, default: 250 * queueList: The Element or ID for the queue list * onComplete: Event fired when one file is completed * onAllComplete: Event fired when all files uploaded * * NOTE: * * Flash FileReference is stupid, the request will have no cookies * or additional post data. Only the file is send in $_FILES['Filedata'], * with a wrong content-type (application/octet-stream). * When u have sessions, append them as get-data to the the url. * * * @version 1.0rc1 * * @license MIT License * * @author Harald Kirschner <mail [at] digitarald [dot] de> * @copyright Authors */ var FancyUpload = new Class({ options: { url: false, swf: 'Swiff.Uploader.swf', multiple: true, queued: true, types: {'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'}, limitSize: false, limitFiles: false, createReplacement: null, instantStart: false, allowDuplicates: false, optionFxDuration: 250, container: null, queueList: 'photoupload-queue', onComplete: Class.empty, onError: Class.empty, onCancel: Class.empty, onAllComplete: Class.empty }, initialize: function(el, options){ this.element = $(el); this.form = this.element.form; this.setOptions(options); this.fileList = []; this.uploader = new Swiff.Uploader({ onOpen: this.onOpen.bind(this), onProgress: this.onProgress.bind(this), onComplete: this.onComplete.bind(this), onError: this.onError.bind(this), onSelect: this.onSelect.bind(this) }, this.initializeFlash.bind(this), { swf: this.options.swf, types: this.options.types, multiple: this.options.multiple, queued: this.options.queued, container: this.options.container }); }, initializeFlash: function() { this.queue = $(this.options.queueList); $(this.element.form).addEvent('submit', this.upload.bindWithEvent(this)); if (this.options.createReplacement) this.options.createReplacement(this.element); else { new Element('input', { type: 'button', value: sBrowseCaption, events: { click: this.browse.bind(this) } }).injectBefore(this.element); this.element.remove(); } }, browse: function() { this.uploader.browse(); }, upload: function(e) { if (e) e.stop(); url = this.options.url || this.form.action || location.href; this.uploader.send(url+'&format=json'); }, onSelect: function(name, size) { if (this.uploadTimer) this.uploadTimer = $clear(this.uploadTimer); if ((this.options.limitSize && (size > this.options.limitSize)) || (this.options.limitFiles && (this.fileList.length >= this.options.limitFiles)) || (!this.options.allowDuplicates && this.findFile(name, size) != -1)) return false; this.addFile(name, size); if (this.options.instantStart) this.uploadTimer = this.upload.delay(250, this); return true; }, onOpen: function(name, size) { var index = this.findFile(name, size); this.fileList[index].status = 1; if (this.fileList[index].fx) return; this.fileList[index].fx = new Element('div', {'class': 'queue-subloader'}).injectInside( new Element('div', {'class': 'queue-loader'}).setHTML('Uploading').injectInside(this.fileList[index].element) ).effect('width', { duration: 200, wait: false, unit: '%', transition: Fx.Transitions.linear }).set(0); }, onProgress: function(name, bytes, total, percentage) { this.uploadStatus(name, total, percentage); }, onComplete: function(name, size) { var index = this.uploadStatus(name, size, 100); this.fileList[index].fx.element.setHTML('Completed'); this.fileList[index].status = 2; this.highlight(index, 'e1ff80'); this.checkComplete(name, size, 'onComplete'); }, /** * Error codes are just examples, customize them according to your server-errorhandling * */ onError: function(name, size, error) { var msg = "Upload failed (" + error + ")"; switch(error.toInt()) { case 500: msg = "Internal server error, please contact Administrator!"; break; case 400: msg = "Upload failed, please check your filesize!"; break; case 409: msg = "File already exists."; break; case 415: msg = "Unsupported media type."; break; case 412: msg = "Invalid target, please reload page and try again!"; break; case 417: msg = "Photo too small, please keep our photo manifest in mind!"; break; } var index = this.uploadStatus(name, size, 100); this.fileList[index].fx.element.setStyle('background-color', '#ffd780').setHTML(msg); this.fileList[index].status = 2; this.highlight(index, 'ffd780'); this.checkComplete(name, size, 'onError'); }, checkComplete: function(name, size, fire) { this.fireEvent(fire, [name, size]); if (this.nextFile() == -1) this.fireEvent('onAllComplete'); }, addFile: function(name, size) { if (!this.options.multiple && this.fileList.length) this.remove(this.fileList[0].name, this.fileList[0].size); this.fileList.push({ name: name, size: size, status: 0, percentage: 0, element: new Element('li').setHTML('<span class="queue-file">'+ name +'</span><span class="queue-size" title="'+ size +' byte">~'+ Math.ceil(size / 1000) +' kb</span>').injectInside(this.queue) }); new Element('a', { href: 'javascript:void(0)', 'class': 'input-delete', title: sRemoveToolTip, events: { click: this.cancelFile.bindWithEvent(this, [name, size]) } }).injectBefore(this.fileList.getLast().element.getFirst()); this.highlight(this.fileList.length - 1, 'e1ff80'); }, uploadStatus: function(name, size, percentage) { var index = this.findFile(name, size); this.fileList[index].fx.start(percentage).element.setHTML(percentage +'%'); this.fileList[index].percentage = percentage; return index; }, uploadOverview: function() { var l = this.fileList.length, i = -1, percentage = 0; while (++i < l) percentage += this.fileList[i].percentage; return Math.ceil(percentage / l); }, highlight: function(index, color) { return this.fileList[index].element.effect('background-color', {duration: this.options.optionFxDuration}).start(color, 'fff'); }, cancelFile: function(e, name, size) { e.stop(); this.remove(name, size); }, remove: function(name, size, index) { if (name) index = this.findFile(name, size); if (index == -1) return; if (this.fileList[index].status < 2) { this.uploader.remove(name, size); this.checkComplete(name, size, 'onCancel'); } this.fileList[index].element.effect('opacity', {duration: this.options.optionFxDuration}).start(1, 0).chain(Element.remove.pass([this.fileList[index].element], Element)); this.fileList.splice(index, 1); return; }, findFile: function(name, size) { var l = this.fileList.length, i = -1; while (++i < l) if (this.fileList[i].name == name && this.fileList[i].size == size) return i; return -1; }, nextFile: function() { var l = this.fileList.length, i = -1; while (++i < l) if (this.fileList[i].status != 2) return i; return -1; }, clearList: function(complete) { var i = -1; while (++i < this.fileList.length) if (complete || this.fileList[i].status == 2) this.remove(0, 0, 0, i--); } }); FancyUpload.implement(new Events, new Options);
JavaScript
/** * @version $Id: popup-imagemanager.js 8656 2007-08-30 22:40:39Z louis $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JImageManager behavior for media component * * @package Joomla.Extensions * @subpackage Media * @since 1.5 */ var ImageManager = { initialize: function() { o = this._getUriObject(window.self.location.href); //console.log(o); q = $H(this._getQueryObject(o.query)); this.editor = decodeURIComponent(q.get('e_name')); // Setup image manager fields object this.fields = new Object(); this.fields.url = $("f_url"); this.fields.alt = $("f_alt"); this.fields.align = $("f_align"); this.fields.title = $("f_title"); this.fields.caption = $("f_caption"); // Setup image listing objects this.folderlist = $('folderlist'); this.frame = window.frames['imageframe']; this.frameurl = this.frame.location.href; // Setup imave listing frame this.imageframe = $('imageframe'); this.imageframe.manager = this; this.imageframe.addEvent('load', function(){ ImageManager.onloadimageview(); }); // Setup folder up button this.upbutton = $('upbutton'); this.upbutton.removeEvents('click'); this.upbutton.addEvent('click', function(){ ImageManager.upFolder(); }); }, onloadimageview: function() { // Update the frame url this.frameurl = this.frame.location.href; var folder = this.getImageFolder(); for(var i = 0; i < this.folderlist.length; i++) { if(folder == this.folderlist.options[i].value) { this.folderlist.selectedIndex = i; break; } } a = this._getUriObject($('uploadForm').getProperty('action')); //console.log(a); q = $H(this._getQueryObject(a.query)); q.set('folder', folder); var query = []; q.each(function(v, k){ if ($chk(v)) { this.push(k+'='+v); } }, query); a.query = query.join('&'); $('uploadForm').setProperty('action', a.scheme+'://'+a.domain+a.path+'?'+a.query); }, getImageFolder: function() { var url = this.frame.location.search.substring(1); var args = this.parseQuery(url); return args['folder']; }, onok: function() { extra = ''; // Get the image tag field information var url = this.fields.url.getValue(); var alt = this.fields.alt.getValue(); var align = this.fields.align.getValue(); var title = this.fields.title.getValue(); var caption = this.fields.caption.getValue(); if (url != '') { // Set alt attribute if (alt != '') { extra = extra + 'alt="'+alt+'" '; } else { extra = extra + 'alt="" '; } // Set align attribute if (align != '') { extra = extra + 'align="'+align+'" '; } // Set align attribute if (title != '') { extra = extra + 'title="'+title+'" '; } // Set align attribute if (caption != '') { extra = extra + 'class="caption" '; } var tag = "<img src=\""+url+"\" "+extra+"/>"; } window.parent.jInsertEditorText(tag, this.editor); return false; }, setFolder: function(folder) { //this.showMessage('Loading'); for(var i = 0; i < this.folderlist.length; i++) { if(folder == this.folderlist.options[i].value) { this.folderlist.selectedIndex = i; break; } } this.frame.location.href='index.php?option=com_media&view=imagesList&tmpl=component&folder=' + folder; }, getFolder: function() { return this.folderlist.getValue(); }, upFolder: function() { var currentFolder = this.getFolder(); if(currentFolder.length < 2) { return false; } var folders = currentFolder.split('/'); var search = ''; for(var i = 0; i < folders.length - 1; i++) { search += folders[i]; search += '/'; } // remove the trailing slash search = search.substring(0, search.length - 1); for(var i = 0; i < this.folderlist.length; i++) { var thisFolder = this.folderlist.options[i].value; if(thisFolder == search) { this.folderlist.selectedIndex = i; var newFolder = this.folderlist.options[i].value; this.setFolder(newFolder); break; } } }, populateFields: function(file) { $("f_url").value = image_base_path+file; }, showMessage: function(text) { var message = $('message'); var messages = $('messages'); if(message.firstChild) message.removeChild(message.firstChild); message.appendChild(document.createTextNode(text)); messages.style.display = "block"; }, parseQuery: function(query) { var params = new Object(); if (!query) { return params; } var pairs = query.split(/[;&]/); for ( var i = 0; i < pairs.length; i++ ) { var KeyVal = pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) { continue; } var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ).replace(/\+ /g, ' '); params[key] = val; } return params; }, refreshFrame: function() { this._setFrameUrl(); }, _setFrameUrl: function(url) { if ($chk(url)) { this.frameurl = url; } this.frame.location.href = this.frameurl; }, _getQueryObject: function(q) { var vars = q.split(/[&;]/); var rs = {}; if (vars.length) vars.each(function(val) { var keys = val.split('='); if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]); }); return rs; }, _getUriObject: function(u){ var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/); return (bits) ? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment']) : null; } }; window.addEvent('domready', function(){ ImageManager.initialize(); });
JavaScript
// directory of where all the images are var cmThemeOfficeBase = 'includes/js/ThemeOffice/'; var cmThemeOffice = { // main menu display attributes // // Note. When the menu bar is horizontal, // mainFolderLeft and mainFolderRight are // put in <span></span>. When the menu // bar is vertical, they would be put in // a separate TD cell. // HTML code to the left of the folder item mainFolderLeft: '&nbsp;', // HTML code to the right of the folder item mainFolderRight: '&nbsp;', // HTML code to the left of the regular item mainItemLeft: '&nbsp;', // HTML code to the right of the regular item mainItemRight: '&nbsp;', // sub menu display attributes // 0, HTML code to the left of the folder item folderLeft: '<img alt="" src="' + cmThemeOfficeBase + 'spacer.png">', // 1, HTML code to the right of the folder item folderRight: '<img alt="" src="' + cmThemeOfficeBase + 'arrow.png">', // 2, HTML code to the left of the regular item itemLeft: '<img alt="" src="' + cmThemeOfficeBase + 'spacer.png">', // 3, HTML code to the right of the regular item itemRight: '<img alt="" src="' + cmThemeOfficeBase + 'blank.png">', // 4, cell spacing for main menu mainSpacing: 0, // 5, cell spacing for sub menus subSpacing: 0, // 6, auto dispear time for submenus in milli-seconds delay: 500 }; // for horizontal menu split var cmThemeOfficeHSplit = [_cmNoAction, '<td class="ThemeOfficeMenuItemLeft"></td><td colspan="2"><div class="ThemeOfficeMenuSplit"></div></td>']; var cmThemeOfficeMainHSplit = [_cmNoAction, '<td class="ThemeOfficeMainItemLeft"></td><td colspan="2"><div class="ThemeOfficeMenuSplit"></div></td>']; var cmThemeOfficeMainVSplit = [_cmNoAction, '&nbsp;'];
JavaScript
/* Copyright Mihai Bazon, 2002 | http://students.infoiasi.ro/~mishoo * --------------------------------------------------------------------- * * The DHTML Calendar, version 0.9.2 "The art of date selection" * * Details and latest version at: * http://students.infoiasi.ro/~mishoo/site/calendar.epl * * Feel free to use this script under the terms of the GNU Lesser General * Public License, as long as you do not remove or alter this notice. */ // $Id: calendar.js 10389 2008-06-03 11:27:38Z pasamio $ /** The Calendar object constructor. */ Calendar = function (mondayFirst, dateStr, onSelected, onClose) { // member variables this.activeDiv = null; this.currentDateEl = null; this.checkDisabled = null; this.timeout = null; this.onSelected = onSelected || null; this.onClose = onClose || null; this.dragging = false; this.hidden = false; this.minYear = 1970; this.maxYear = 2050; this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"]; this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"]; this.isPopup = true; this.weekNumbers = true; this.mondayFirst = mondayFirst; this.dateStr = dateStr; this.ar_days = null; // HTML elements this.table = null; this.element = null; this.tbody = null; this.firstdayname = null; // Combo boxes this.monthsCombo = null; this.yearsCombo = null; this.hilitedMonth = null; this.activeMonth = null; this.hilitedYear = null; this.activeYear = null; // one-time initializations if (!Calendar._DN3) { // table of short day names var ar = new Array(); for (var i = 8; i > 0;) { ar[--i] = Calendar._DN[i].substr(0, 3); } Calendar._DN3 = ar; // table of short month names ar = new Array(); for (var i = 12; i > 0;) { ar[--i] = Calendar._MN[i].substr(0, 3); } Calendar._MN3 = ar; } }; // ** constants /// "static", needed for event handlers. Calendar._C = null; /// detect a special case of "web browser" Calendar.is_ie = ( (navigator.userAgent.toLowerCase().indexOf("msie") != -1) && (navigator.userAgent.toLowerCase().indexOf("opera") == -1) ); // short day names array (initialized at first constructor call) Calendar._DN3 = null; // short month names array (initialized at first constructor call) Calendar._MN3 = null; // BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate // library, at some point. Calendar.getAbsolutePos = function(el) { var r = { x: el.offsetLeft, y: el.offsetTop }; if (el.offsetParent) { var tmp = Calendar.getAbsolutePos(el.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }; Calendar.isRelated = function (el, evt) { var related = evt.relatedTarget; if (!related) { var type = evt.type; if (type == "mouseover") { related = evt.fromElement; } else if (type == "mouseout") { related = evt.toElement; } } while (related) { if (related == el) { return true; } related = related.parentNode; } return false; }; Calendar.removeClass = function(el, className) { if (!(el && el.className)) { return; } var cls = el.className.split(" "); var ar = new Array(); for (var i = cls.length; i > 0;) { if (cls[--i] != className) { ar[ar.length] = cls[i]; } } el.className = ar.join(" "); }; Calendar.addClass = function(el, className) { Calendar.removeClass(el, className); el.className += " " + className; }; Calendar.getElement = function(ev) { if (Calendar.is_ie) { return window.event.srcElement; } else { return ev.currentTarget; } }; Calendar.getTargetElement = function(ev) { if (Calendar.is_ie) { return window.event.srcElement; } else { return ev.target; } }; Calendar.stopEvent = function(ev) { if (Calendar.is_ie) { window.event.cancelBubble = true; window.event.returnValue = false; } else { ev.preventDefault(); ev.stopPropagation(); } }; Calendar.addEvent = function(el, evname, func) { if (Calendar.is_ie) { el.attachEvent("on" + evname, func); } else { el.addEventListener(evname, func, true); } }; Calendar.removeEvent = function(el, evname, func) { if (Calendar.is_ie) { el.detachEvent("on" + evname, func); } else { el.removeEventListener(evname, func, true); } }; Calendar.createElement = function(type, parent) { var el = null; if (document.createElementNS) { // use the XHTML namespace; IE won't normally get here unless // _they_ "fix" the DOM2 implementation. el = document.createElementNS("http://www.w3.org/1999/xhtml", type); } else { el = document.createElement(type); } if (typeof parent != "undefined") { parent.appendChild(el); } return el; }; // END: UTILITY FUNCTIONS // BEGIN: CALENDAR STATIC FUNCTIONS /** Internal -- adds a set of events to make some element behave like a button. */ Calendar._add_evs = function(el) { with (Calendar) { addEvent(el, "mouseover", dayMouseOver); addEvent(el, "mousedown", dayMouseDown); addEvent(el, "mouseout", dayMouseOut); if (is_ie) { addEvent(el, "dblclick", dayMouseDblClick); el.setAttribute("unselectable", true); } } }; Calendar.findMonth = function(el) { if (typeof el.month != "undefined") { return el; } else if (typeof el.parentNode.month != "undefined") { return el.parentNode; } return null; }; Calendar.findYear = function(el) { if (typeof el.year != "undefined") { return el; } else if (typeof el.parentNode.year != "undefined") { return el.parentNode; } return null; }; Calendar.showMonthsCombo = function () { var cal = Calendar._C; if (!cal) { return false; } var cal = cal; var cd = cal.activeDiv; var mc = cal.monthsCombo; if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } if (cal.activeMonth) { Calendar.removeClass(cal.activeMonth, "active"); } var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()]; Calendar.addClass(mon, "active"); cal.activeMonth = mon; mc.style.left = cd.offsetLeft + "px"; mc.style.top = (cd.offsetTop + cd.offsetHeight) + "px"; mc.style.display = "block"; }; Calendar.showYearsCombo = function (fwd) { var cal = Calendar._C; if (!cal) { return false; } var cal = cal; var cd = cal.activeDiv; var yc = cal.yearsCombo; if (cal.hilitedYear) { Calendar.removeClass(cal.hilitedYear, "hilite"); } if (cal.activeYear) { Calendar.removeClass(cal.activeYear, "active"); } cal.activeYear = null; var Y = cal.date.getFullYear() + (fwd ? 1 : -1); var yr = yc.firstChild; var show = false; for (var i = 12; i > 0; --i) { if (Y >= cal.minYear && Y <= cal.maxYear) { yr.firstChild.data = Y; yr.year = Y; yr.style.display = "block"; show = true; } else { yr.style.display = "none"; } yr = yr.nextSibling; Y += fwd ? 2 : -2; } if (show) { yc.style.left = cd.offsetLeft + "px"; yc.style.top = (cd.offsetTop + cd.offsetHeight) + "px"; yc.style.display = "block"; } }; // event handlers Calendar.tableMouseUp = function(ev) { var cal = Calendar._C; if (!cal) { return false; } if (cal.timeout) { clearTimeout(cal.timeout); } var el = cal.activeDiv; if (!el) { return false; } var target = Calendar.getTargetElement(ev); Calendar.removeClass(el, "active"); if (target == el || target.parentNode == el) { Calendar.cellClick(el); } var mon = Calendar.findMonth(target); var date = null; if (mon) { date = new Date(cal.date); if (mon.month != date.getMonth()) { date.setMonth(mon.month); cal.setDate(date); } } else { var year = Calendar.findYear(target); if (year) { date = new Date(cal.date); if (year.year != date.getFullYear()) { date.setFullYear(year.year); cal.setDate(date); } } } with (Calendar) { removeEvent(document, "mouseup", tableMouseUp); removeEvent(document, "mouseover", tableMouseOver); removeEvent(document, "mousemove", tableMouseOver); cal._hideCombos(); stopEvent(ev); _C = null; } }; Calendar.tableMouseOver = function (ev) { var cal = Calendar._C; if (!cal) { return; } var el = cal.activeDiv; var target = Calendar.getTargetElement(ev); if (target == el || target.parentNode == el) { Calendar.addClass(el, "hilite active"); Calendar.addClass(el.parentNode, "rowhilite"); } else { Calendar.removeClass(el, "active"); Calendar.removeClass(el, "hilite"); Calendar.removeClass(el.parentNode, "rowhilite"); } var mon = Calendar.findMonth(target); if (mon) { if (mon.month != cal.date.getMonth()) { if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } Calendar.addClass(mon, "hilite"); cal.hilitedMonth = mon; } else if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } } else { var year = Calendar.findYear(target); if (year) { if (year.year != cal.date.getFullYear()) { if (cal.hilitedYear) { Calendar.removeClass(cal.hilitedYear, "hilite"); } Calendar.addClass(year, "hilite"); cal.hilitedYear = year; } else if (cal.hilitedYear) { Calendar.removeClass(cal.hilitedYear, "hilite"); } } } Calendar.stopEvent(ev); }; Calendar.tableMouseDown = function (ev) { if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) { Calendar.stopEvent(ev); } }; Calendar.calDragIt = function (ev) { var cal = Calendar._C; if (!(cal && cal.dragging)) { return false; } var posX; var posY; if (Calendar.is_ie) { posY = window.event.clientY + document.body.scrollTop; posX = window.event.clientX + document.body.scrollLeft; } else { posX = ev.pageX; posY = ev.pageY; } cal.hideShowCovered(); var st = cal.element.style; st.left = (posX - cal.xOffs) + "px"; st.top = (posY - cal.yOffs) + "px"; Calendar.stopEvent(ev); }; Calendar.calDragEnd = function (ev) { var cal = Calendar._C; if (!cal) { return false; } cal.dragging = false; with (Calendar) { removeEvent(document, "mousemove", calDragIt); removeEvent(document, "mouseover", stopEvent); removeEvent(document, "mouseup", calDragEnd); tableMouseUp(ev); } cal.hideShowCovered(); }; Calendar.dayMouseDown = function(ev) { var el = Calendar.getElement(ev); if (el.disabled) { return false; } var cal = el.calendar; cal.activeDiv = el; Calendar._C = cal; if (el.navtype != 300) with (Calendar) { addClass(el, "hilite active"); addEvent(document, "mouseover", tableMouseOver); addEvent(document, "mousemove", tableMouseOver); addEvent(document, "mouseup", tableMouseUp); } else if (cal.isPopup) { cal._dragStart(ev); } Calendar.stopEvent(ev); if (el.navtype == -1 || el.navtype == 1) { cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250); } else if (el.navtype == -2 || el.navtype == 2) { cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250); } else { cal.timeout = null; } }; Calendar.dayMouseDblClick = function(ev) { Calendar.cellClick(Calendar.getElement(ev)); if (Calendar.is_ie) { document.selection.empty(); } }; Calendar.dayMouseOver = function(ev) { var el = Calendar.getElement(ev); if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) { return false; } if (el.ttip) { if (el.ttip.substr(0, 1) == "_") { var date = null; with (el.calendar.date) { date = new Date(getFullYear(), getMonth(), el.caldate); } el.ttip = date.print(el.calendar.ttDateFormat) + el.ttip.substr(1); } el.calendar.tooltips.firstChild.data = el.ttip; } if (el.navtype != 300) { Calendar.addClass(el, "hilite"); if (el.caldate) { Calendar.addClass(el.parentNode, "rowhilite"); } } Calendar.stopEvent(ev); }; Calendar.dayMouseOut = function(ev) { with (Calendar) { var el = getElement(ev); if (isRelated(el, ev) || _C || el.disabled) { return false; } removeClass(el, "hilite"); if (el.caldate) { removeClass(el.parentNode, "rowhilite"); } el.calendar.tooltips.firstChild.data = _TT["SEL_DATE"]; stopEvent(ev); } }; /** * A generic "click" handler :) handles all types of buttons defined in this * calendar. */ Calendar.cellClick = function(el) { var cal = el.calendar; var closing = false; var newdate = false; var date = null; if (typeof el.navtype == "undefined") { Calendar.removeClass(cal.currentDateEl, "selected"); Calendar.addClass(el, "selected"); closing = (cal.currentDateEl == el); if (!closing) { cal.currentDateEl = el; } cal.date.setDate(el.caldate); date = cal.date; newdate = true; } else { if (el.navtype == 200) { Calendar.removeClass(el, "hilite"); cal.callCloseHandler(); return; } date = (el.navtype == 0) ? new Date() : new Date(cal.date); var year = date.getFullYear(); var mon = date.getMonth(); function setMonth(m) { var day = date.getDate(); var max = date.getMonthDays(m); if (day > max) { date.setDate(max); } date.setMonth(m); }; switch (el.navtype) { case -2: if (year > cal.minYear) { date.setFullYear(year - 1); } break; case -1: if (mon > 0) { setMonth(mon - 1); } else if (year-- > cal.minYear) { date.setFullYear(year); setMonth(11); } break; case 1: if (mon < 11) { setMonth(mon + 1); } else if (year < cal.maxYear) { date.setFullYear(year + 1); setMonth(0); } break; case 2: if (year < cal.maxYear) { date.setFullYear(year + 1); } break; case 100: cal.setMondayFirst(!cal.mondayFirst); return; } if (!date.equalsTo(cal.date)) { cal.setDate(date); newdate = el.navtype == 0; } } if (newdate) { cal.callHandler(); } if (closing) { Calendar.removeClass(el, "hilite"); cal.callCloseHandler(); } }; // END: CALENDAR STATIC FUNCTIONS // BEGIN: CALENDAR OBJECT FUNCTIONS /** * This function creates the calendar inside the given parent. If _par is * null than it creates a popup calendar inside the BODY element. If _par is * an element, be it BODY, then it creates a non-popup calendar (still * hidden). Some properties need to be set before calling this function. */ Calendar.prototype.create = function (_par) { var parent = null; if (! _par) { // default parent is the document body, in which case we create // a popup calendar. parent = document.getElementsByTagName("body")[0]; this.isPopup = true; } else { parent = _par; this.isPopup = false; } this.date = this.dateStr ? new Date(this.dateStr) : new Date(); var table = Calendar.createElement("table"); this.table = table; table.cellSpacing = 0; table.cellPadding = 0; table.calendar = this; Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown); var div = Calendar.createElement("div"); this.element = div; div.className = "calendar"; if (this.isPopup) { div.style.position = "absolute"; div.style.display = "none"; } div.appendChild(table); var thead = Calendar.createElement("thead", table); var cell = null; var row = null; var cal = this; var hh = function (text, cs, navtype) { cell = Calendar.createElement("td", row); cell.colSpan = cs; cell.className = "button"; Calendar._add_evs(cell); cell.calendar = cal; cell.navtype = navtype; if (text.substr(0, 1) != "&") { cell.appendChild(document.createTextNode(text)); } else { // FIXME: dirty hack for entities cell.innerHTML = text; } return cell; }; row = Calendar.createElement("tr", thead); var title_length = 6; (this.isPopup) && --title_length; (this.weekNumbers) && ++title_length; hh("-", 1, 100).ttip = Calendar._TT["TOGGLE"]; this.title = hh("", title_length, 300); this.title.className = "title"; if (this.isPopup) { this.title.ttip = Calendar._TT["DRAG_TO_MOVE"]; this.title.style.cursor = "move"; hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"]; } row = Calendar.createElement("tr", thead); row.className = "headrow"; this._nav_py = hh("&#x00ab;", 1, -2); this._nav_py.ttip = Calendar._TT["PREV_YEAR"]; this._nav_pm = hh("&#x2039;", 1, -1); this._nav_pm.ttip = Calendar._TT["PREV_MONTH"]; this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0); this._nav_now.ttip = Calendar._TT["GO_TODAY"]; this._nav_nm = hh("&#x203a;", 1, 1); this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"]; this._nav_ny = hh("&#x00bb;", 1, 2); this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"] // day names row = Calendar.createElement("tr", thead); row.className = "daynames"; if (this.weekNumbers) { cell = Calendar.createElement("td", row); cell.className = "name wn"; cell.appendChild(document.createTextNode(Calendar._TT["WK"])); } for (var i = 7; i > 0; --i) { cell = Calendar.createElement("td", row); cell.appendChild(document.createTextNode("")); if (!i) { cell.navtype = 100; cell.calendar = this; Calendar._add_evs(cell); } } this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild; this._displayWeekdays(); var tbody = Calendar.createElement("tbody", table); this.tbody = tbody; for (i = 6; i > 0; --i) { row = Calendar.createElement("tr", tbody); if (this.weekNumbers) { cell = Calendar.createElement("td", row); cell.appendChild(document.createTextNode("")); } for (var j = 7; j > 0; --j) { cell = Calendar.createElement("td", row); cell.appendChild(document.createTextNode("")); cell.calendar = this; Calendar._add_evs(cell); } } var tfoot = Calendar.createElement("tfoot", table); row = Calendar.createElement("tr", tfoot); row.className = "footrow"; cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300); cell.className = "ttip"; if (this.isPopup) { cell.ttip = Calendar._TT["DRAG_TO_MOVE"]; cell.style.cursor = "move"; } this.tooltips = cell; div = Calendar.createElement("div", this.element); this.monthsCombo = div; div.className = "combo"; for (i = 0; i < Calendar._MN.length; ++i) { var mn = Calendar.createElement("div"); mn.className = "label"; mn.month = i; mn.appendChild(document.createTextNode(Calendar._MN3[i])); div.appendChild(mn); } div = Calendar.createElement("div", this.element); this.yearsCombo = div; div.className = "combo"; for (i = 12; i > 0; --i) { var yr = Calendar.createElement("div"); yr.className = "label"; yr.appendChild(document.createTextNode("")); div.appendChild(yr); } this._init(this.mondayFirst, this.date); parent.appendChild(this.element); }; /** keyboard navigation, only for popup calendars */ Calendar._keyEvent = function(ev) { if (!window.calendar) { return false; } (Calendar.is_ie) && (ev = window.event); var cal = window.calendar; var act = (Calendar.is_ie || ev.type == "keypress"); if (ev.ctrlKey) { switch (ev.keyCode) { case 37: // KEY left act && Calendar.cellClick(cal._nav_pm); break; case 38: // KEY up act && Calendar.cellClick(cal._nav_py); break; case 39: // KEY right act && Calendar.cellClick(cal._nav_nm); break; case 40: // KEY down act && Calendar.cellClick(cal._nav_ny); break; default: return false; } } else switch (ev.keyCode) { case 32: // KEY space (now) Calendar.cellClick(cal._nav_now); break; case 27: // KEY esc act && cal.hide(); break; case 37: // KEY left case 38: // KEY up case 39: // KEY right case 40: // KEY down if (act) { var date = cal.date.getDate() - 1; var el = cal.currentDateEl; var ne = null; var prev = (ev.keyCode == 37) || (ev.keyCode == 38); switch (ev.keyCode) { case 37: // KEY left (--date >= 0) && (ne = cal.ar_days[date]); break; case 38: // KEY up date -= 7; (date >= 0) && (ne = cal.ar_days[date]); break; case 39: // KEY right (++date < cal.ar_days.length) && (ne = cal.ar_days[date]); break; case 40: // KEY down date += 7; (date < cal.ar_days.length) && (ne = cal.ar_days[date]); break; } if (!ne) { if (prev) { Calendar.cellClick(cal._nav_pm); } else { Calendar.cellClick(cal._nav_nm); } date = (prev) ? cal.date.getMonthDays() : 1; el = cal.currentDateEl; ne = cal.ar_days[date - 1]; } Calendar.removeClass(el, "selected"); Calendar.addClass(ne, "selected"); cal.date.setDate(ne.caldate); cal.currentDateEl = ne; } break; case 13: // KEY enter if (act) { cal.callHandler(); cal.hide(); } break; default: return false; } Calendar.stopEvent(ev); }; /** * (RE)Initializes the calendar to the given date and style (if mondayFirst is * true it makes Monday the first day of week, otherwise the weeks start on * Sunday. */ Calendar.prototype._init = function (mondayFirst, date) { var today = new Date(); var year = date.getFullYear(); if (year < this.minYear) { year = this.minYear; date.setFullYear(year); } else if (year > this.maxYear) { year = this.maxYear; date.setFullYear(year); } this.mondayFirst = mondayFirst; this.date = new Date(date); var month = date.getMonth(); var mday = date.getDate(); var no_days = date.getMonthDays(); date.setDate(1); var wday = date.getDay(); var MON = mondayFirst ? 1 : 0; var SAT = mondayFirst ? 5 : 6; var SUN = mondayFirst ? 6 : 0; if (mondayFirst) { wday = (wday > 0) ? (wday - 1) : 6; } var iday = 1; var row = this.tbody.firstChild; var MN = Calendar._MN3[month]; var hasToday = ((today.getFullYear() == year) && (today.getMonth() == month)); var todayDate = today.getDate(); var week_number = date.getWeekNumber(); var ar_days = new Array(); for (var i = 0; i < 6; ++i) { if (iday > no_days) { row.className = "emptyrow"; row = row.nextSibling; continue; } var cell = row.firstChild; if (this.weekNumbers) { cell.className = "day wn"; cell.firstChild.data = week_number; cell = cell.nextSibling; } ++week_number; row.className = "daysrow"; for (var j = 0; j < 7; ++j) { cell.className = "day"; if ((!i && j < wday) || iday > no_days) { // cell.className = "emptycell"; cell.innerHTML = "&nbsp;"; cell.disabled = true; cell = cell.nextSibling; continue; } cell.disabled = false; cell.firstChild.data = iday; if (typeof this.checkDisabled == "function") { date.setDate(iday); if (this.checkDisabled(date)) { cell.className += " disabled"; cell.disabled = true; } } if (!cell.disabled) { ar_days[ar_days.length] = cell; cell.caldate = iday; cell.ttip = "_"; if (iday == mday) { cell.className += " selected"; this.currentDateEl = cell; } if (hasToday && (iday == todayDate)) { cell.className += " today"; cell.ttip += Calendar._TT["PART_TODAY"]; } if (wday == SAT || wday == SUN) { cell.className += " weekend"; } } ++iday; ((++wday) ^ 7) || (wday = 0); cell = cell.nextSibling; } row = row.nextSibling; } this.ar_days = ar_days; this.title.firstChild.data = Calendar._MN[month] + ", " + year; // PROFILE // this.tooltips.firstChild.data = "Generated in " + ((new Date()) - today) + " ms"; }; /** * Calls _init function above for going to a certain date (but only if the * date is different than the currently selected one). */ Calendar.prototype.setDate = function (date) { if (!date.equalsTo(this.date)) { this._init(this.mondayFirst, date); } }; /** Modifies the "mondayFirst" parameter (EU/US style). */ Calendar.prototype.setMondayFirst = function (mondayFirst) { this._init(mondayFirst, this.date); this._displayWeekdays(); }; /** * Allows customization of what dates are enabled. The "unaryFunction" * parameter must be a function object that receives the date (as a JS Date * object) and returns a boolean value. If the returned value is true then * the passed date will be marked as disabled. */ Calendar.prototype.setDisabledHandler = function (unaryFunction) { this.checkDisabled = unaryFunction; }; /** Customization of allowed year range for the calendar. */ Calendar.prototype.setRange = function (a, z) { this.minYear = a; this.maxYear = z; }; /** Calls the first user handler (selectedHandler). */ Calendar.prototype.callHandler = function () { if (this.onSelected) { this.onSelected(this, this.date.print(this.dateFormat)); } }; /** Calls the second user handler (closeHandler). */ Calendar.prototype.callCloseHandler = function () { if (this.onClose) { this.onClose(this); } this.hideShowCovered(); }; /** Removes the calendar object from the DOM tree and destroys it. */ Calendar.prototype.destroy = function () { var el = this.element.parentNode; el.removeChild(this.element); Calendar._C = null; delete el; }; /** * Moves the calendar element to a different section in the DOM tree (changes * its parent). */ Calendar.prototype.reparent = function (new_parent) { var el = this.element; el.parentNode.removeChild(el); new_parent.appendChild(el); }; // This gets called when the user presses a mouse button anywhere in the // document, if the calendar is shown. If the click was outside the open // calendar this function closes it. Calendar._checkCalendar = function(ev) { if (!window.calendar) { return false; } var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev); for (; el != null && el != calendar.element; el = el.parentNode); if (el == null) { // calls closeHandler which should hide the calendar. window.calendar.callCloseHandler(); Calendar.stopEvent(ev); } }; /** Shows the calendar. */ Calendar.prototype.show = function () { var rows = this.table.getElementsByTagName("tr"); for (var i = rows.length; i > 0;) { var row = rows[--i]; Calendar.removeClass(row, "rowhilite"); var cells = row.getElementsByTagName("td"); for (var j = cells.length; j > 0;) { var cell = cells[--j]; Calendar.removeClass(cell, "hilite"); Calendar.removeClass(cell, "active"); } } this.element.style.display = "block"; this.hidden = false; if (this.isPopup) { window.calendar = this; Calendar.addEvent(document, "keydown", Calendar._keyEvent); Calendar.addEvent(document, "keypress", Calendar._keyEvent); Calendar.addEvent(document, "mousedown", Calendar._checkCalendar); } this.hideShowCovered(); }; /** * Hides the calendar. Also removes any "hilite" from the class of any TD * element. */ Calendar.prototype.hide = function () { if (this.isPopup) { Calendar.removeEvent(document, "keydown", Calendar._keyEvent); Calendar.removeEvent(document, "keypress", Calendar._keyEvent); Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar); } this.element.style.display = "none"; this.hidden = true; this.hideShowCovered(); }; /** * Shows the calendar at a given absolute position (beware that, depending on * the calendar element style -- position property -- this might be relative * to the parent's containing rectangle). */ Calendar.prototype.showAt = function (x, y) { var s = this.element.style; s.left = x + "px"; s.top = y + "px"; this.show(); }; /** Shows the calendar near a given element. */ Calendar.prototype.showAtElement = function (el) { var p = Calendar.getAbsolutePos(el); this.showAt(p.x, p.y + el.offsetHeight); }; /** Customizes the date format. */ Calendar.prototype.setDateFormat = function (str) { this.dateFormat = str; }; /** Customizes the tooltip date format. */ Calendar.prototype.setTtDateFormat = function (str) { this.ttDateFormat = str; }; /** * Tries to identify the date represented in a string. If successful it also * calls this.setDate which moves the calendar to the given date. */ Calendar.prototype.parseDate = function (str, fmt) { var y = 0; var m = -1; var d = 0; var a = str.split(/\W+/); if (!fmt) { fmt = this.dateFormat; } var b = fmt.split(/\W+/); var i = 0, j = 0; for (i = 0; i < a.length; ++i) { if (b[i] == "D" || b[i] == "DD") { continue; } if (b[i] == "d" || b[i] == "dd") { d = parseInt(a[i], 10); } if (b[i] == "m" || b[i] == "mm") { m = parseInt(a[i], 10) - 1; } if (b[i] == "y") { y = parseInt(a[i], 10); } if (b[i] == "yy") { y = parseInt(a[i], 10) + 1900; } if (b[i] == "M" || b[i] == "MM") { for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; } } } } if (y != 0 && m != -1 && d != 0) { this.setDate(new Date(y, m, d)); return; } y = 0; m = -1; d = 0; for (i = 0; i < a.length; ++i) { if (a[i].search(/[a-zA-Z]+/) != -1) { var t = -1; for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; } } if (t != -1) { if (m != -1) { d = m+1; } m = t; } } else if (parseInt(a[i], 10) <= 12 && m == -1) { m = a[i]-1; } else if (parseInt(a[i], 10) > 31 && y == 0) { y = a[i]; } else if (d == 0) { d = a[i]; } } if (y == 0) { var today = new Date(); y = today.getFullYear(); } if (m != -1 && d != 0) { this.setDate(new Date(y, m, d)); } }; Calendar.prototype.hideShowCovered = function () { var tags = new Array("applet", "iframe", "select"); var el = this.element; var p = Calendar.getAbsolutePos(el); var EX1 = p.x; var EX2 = el.offsetWidth + EX1; var EY1 = p.y; var EY2 = el.offsetHeight + EY1; for (var k = tags.length; k > 0; ) { var ar = document.getElementsByTagName(tags[--k]); var cc = null; for (var i = ar.length; i > 0;) { cc = ar[--i]; p = Calendar.getAbsolutePos(cc); var CX1 = p.x; var CX2 = cc.offsetWidth + CX1; var CY1 = p.y; var CY2 = cc.offsetHeight + CY1; if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) { cc.style.visibility = "visible"; } else { cc.style.visibility = "hidden"; } } } }; /** Internal function; it displays the bar with the names of the weekday. */ Calendar.prototype._displayWeekdays = function () { var MON = this.mondayFirst ? 0 : 1; var SUN = this.mondayFirst ? 6 : 0; var SAT = this.mondayFirst ? 5 : 6; var cell = this.firstdayname; for (var i = 0; i < 7; ++i) { cell.className = "day name"; if (!i) { cell.ttip = this.mondayFirst ? Calendar._TT["SUN_FIRST"] : Calendar._TT["MON_FIRST"]; cell.navtype = 100; cell.calendar = this; Calendar._add_evs(cell); } if (i == SUN || i == SAT) { Calendar.addClass(cell, "weekend"); } cell.firstChild.data = Calendar._DN3[i + 1 - MON]; cell = cell.nextSibling; } }; /** Internal function. Hides all combo boxes that might be displayed. */ Calendar.prototype._hideCombos = function () { this.monthsCombo.style.display = "none"; this.yearsCombo.style.display = "none"; }; /** Internal function. Starts dragging the element. */ Calendar.prototype._dragStart = function (ev) { if (this.dragging) { return; } this.dragging = true; var posX; var posY; if (Calendar.is_ie) { posY = window.event.clientY + document.body.scrollTop; posX = window.event.clientX + document.body.scrollLeft; } else { posY = ev.clientY + window.scrollY; posX = ev.clientX + window.scrollX; } var st = this.element.style; this.xOffs = posX - parseInt(st.left); this.yOffs = posY - parseInt(st.top); with (Calendar) { addEvent(document, "mousemove", calDragIt); addEvent(document, "mouseover", stopEvent); addEvent(document, "mouseup", calDragEnd); } }; // BEGIN: DATE OBJECT PATCHES /** Adds the number of days array to the Date object. */ Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31); /** Constants used for time computations */ Date.SECOND = 1000 /* milliseconds */; Date.MINUTE = 60 * Date.SECOND; Date.HOUR = 60 * Date.MINUTE; Date.DAY = 24 * Date.HOUR; Date.WEEK = 7 * Date.DAY; /** Returns the number of days in the current month */ Date.prototype.getMonthDays = function(month) { var year = this.getFullYear(); if (typeof month == "undefined") { month = this.getMonth(); } if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) { return 29; } else { return Date._MD[month]; } }; /** Returns the number of the week. The algorithm was "stolen" from PPK's * website, hope it's correct :) http://www.xs4all.nl/~ppk/js/week.html */ Date.prototype.getWeekNumber = function() { var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var then = new Date(this.getFullYear(), 0, 1, 0, 0, 0); var time = now - then; var day = then.getDay(); (day > 3) && (day -= 4) || (day += 3); return Math.round(((time / Date.DAY) + day) / 7); }; /** Checks dates equality (ignores time) */ Date.prototype.equalsTo = function(date) { return ((this.getFullYear() == date.getFullYear()) && (this.getMonth() == date.getMonth()) && (this.getDate() == date.getDate())); }; /** Prints the date in a string according to the given format. */ Date.prototype.print = function (frm) { var str = new String(frm); var m = this.getMonth(); var d = this.getDate(); var y = this.getFullYear(); var wn = this.getWeekNumber(); var w = this.getDay(); var s = new Array(); s["d"] = d; s["dd"] = (d < 10) ? ("0" + d) : d; s["m"] = 1+m; s["mm"] = (m < 9) ? ("0" + (1+m)) : (1+m); s["y"] = y; s["yy"] = new String(y).substr(2, 2); s["w"] = wn; s["ww"] = (wn < 10) ? ("0" + wn) : wn; with (Calendar) { s["D"] = _DN3[w]; s["DD"] = _DN[w]; s["M"] = _MN3[m]; s["MM"] = _MN[m]; } var re = /(.*)(\W|^)(d|dd|m|mm|y|yy|MM|M|DD|D|w|ww)(\W|$)(.*)/; while (re.exec(str) != null) { str = RegExp.$1 + RegExp.$2 + s[RegExp.$3] + RegExp.$4 + RegExp.$5; } return str; }; // END: DATE OBJECT PATCHES // global object that remembers the calendar window.calendar = null;
JavaScript
// ** I18N Calendar._DN = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); Calendar._MN = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); // tooltips Calendar._TT = {}; Calendar._TT["TOGGLE"] = "Toggle first day of week"; Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)"; Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)"; Calendar._TT["GO_TODAY"] = "Go Today"; Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)"; Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)"; Calendar._TT["SEL_DATE"] = "Select date"; Calendar._TT["DRAG_TO_MOVE"] = "Drag to move"; Calendar._TT["PART_TODAY"] = "(Today)"; Calendar._TT["MON_FIRST"] = "Display Monday first"; Calendar._TT["SUN_FIRST"] = "Display Sunday first"; Calendar._TT["CLOSE"] = "Close"; Calendar._TT["TODAY"] = "Today"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "y-mm-dd"; Calendar._TT["TT_DATE_FORMAT"] = "D, M d"; Calendar._TT["WK"] = "wk";
JavaScript
//\///// //\ overLIB Hide Form Plugin //\ //\ Uses an iframe shim to mask system controls for IE v5.5 or higher as suggested in //\ http://dotnetjunkies.com/weblog/jking/posts/488.aspx //\ This file requires overLIB 4.10 or later. //\ //\ overLIB 4.05 - You may not remove or change this notice. //\ Copyright Erik Bosrup 1998-2004. All rights reserved. //\ Contributors are listed on the homepage. //\ See http://www.bosrup.com/web/overlib/ for details. //\///// //\ THIS IS A VERY MODIFIED VERSION. DO NOT EDIT OR PUBLISH. GET THE ORIGINAL! if(typeof olInfo=='undefined'||typeof olInfo.meets=='undefined'||!olInfo.meets(4.10))alert('overLIB 4.10 or later is required for the HideForm Plugin.');else{ function generatePopUp(content){if(!olIe4||olOp||!olIe55||(typeof o3_shadow!='undefined'&&o3_shadow)||(typeof o3_bubble!='undefined'&&o3_bubble))return; var wd,ht,txt,zIdx=0; wd=parseInt(o3_width);ht=over.offsetHeight;txt=backDropSource(wd,ht,zIdx++);txt+='<div style="position: absolute;top: 0;left: 0;width: '+wd+'px;z-index: '+zIdx+';">'+content+'</div>';layerWrite(txt);} function backDropSource(width,height,Z){return '<iframe frameborder="0" scrolling="no" src="javascript:false;" width="'+width+'" height="'+height+'" style="z-index: '+Z+';filter: Beta(Style=0,Opacity=0);"></iframe>';} function hideSelectBox(){if(olNs4||olOp||olIe55)return;var px,py,pw,ph,sx,sw,sy,sh,selEl,v; if(olIe4)v=0;else{v=navigator.userAgent.match(/Gecko\/(\d{8})/i);if(!v)return;v=parseInt(v[1]);} if(v<20030624){px=parseInt(over.style.left);py=parseInt(over.style.top);pw=o3_width;ph=(o3_aboveheight?parseInt(o3_aboveheight):over.offsetHeight);selEl=(olIe4)?o3_frame.document.all.tags("SELECT"):o3_frame.document.getElementsByTagName("SELECT");for(var i=0;i<selEl.length;i++){if(!olIe4&&selEl[i].size<2)continue;sx=pageLocation(selEl[i],'Left');sy=pageLocation(selEl[i],'Top');sw=selEl[i].offsetWidth;sh=selEl[i].offsetHeight;if((px+pw)<sx||px>(sx+sw)||(py+ph)<sy||py>(sy+sh))continue;selEl[i].isHidden=1;selEl[i].style.visibility='hidden';}}} function showSelectBox(){if(olNs4||olOp||olIe55)return;var selEl,v; if(olIe4)v=0;else{v=navigator.userAgent.match(/Gecko\/(\d{8})/i);if(!v)return;v=parseInt(v[1]);} if(v<20030624){selEl=(olIe4)?o3_frame.document.all.tags("SELECT"):o3_frame.document.getElementsByTagName("SELECT");for(var i=0;i<selEl.length;i++){if(typeof selEl[i].isHidden!='undefined'&&selEl[i].isHidden){selEl[i].isHidden=0;selEl[i].style.visibility='visible';}}}} function pageLocation(o,t){var x=0 while(o.offsetParent){x+=o['offset'+t] o=o.offsetParent} x+=o['offset'+t] return x} if(!(olNs4||olOp||olIe55||navigator.userAgent.indexOf('Netscape6')!=-1)){var MMStr=olMouseMove.toString();var strRe=/(if\s*\(o3_allowmove\s*==\s*1.*\)\s*)/;var f=MMStr.match(strRe); if(f){var ls=MMStr.search(strRe);ls+=f[1].length;var le=MMStr.substring(ls).search(/[;|}]\n/);MMStr=MMStr.substring(0,ls)+' {runHook("placeLayer",FREPLACE);if(olHideForm)hideSelectBox();'+MMStr.substring(ls+(le!=-1?le+3:0));document.writeln('<script type="text/javascript">\n<!--\n'+MMStr+'\n//-->\n</'+'script>');} f=capExtent.onmousemove.toString().match(/function[ ]+(\w*)\(/);if(f&&f[1]!='anonymous')capExtent.onmousemove=olMouseMove;} registerHook("createPopup",generatePopUp,FAFTER);registerHook("hideObject",showSelectBox,FAFTER);olHideForm=1;}
JavaScript
/* JSCookMenu v1.4.3. (c) Copyright 2002-2005 by Heng Yuan 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, ITNESS 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. */ // Globals var _cmIDCount = 0; var _cmIDName = 'cmSubMenuID'; // for creating submenu id var _cmTimeOut = null; // how long the menu would stay var _cmCurrentItem = null; // the current menu item being selected; var _cmNoAction = new Object (); // indicate that the item cannot be hovered. var _cmNoClick = new Object (); // similar to _cmNoAction but does not respond to mouseup/mousedown events var _cmSplit = new Object (); // indicate that the item is a menu split var _cmItemList = new Array (); // a simple list of items // default node properties var _cmNodeProperties = { // main menu display attributes // // Note. When the menu bar is horizontal, // mainFolderLeft and mainFolderRight are // put in <span></span>. When the menu // bar is vertical, they would be put in // a separate TD cell. // HTML code to the left of the folder item mainFolderLeft: '', // HTML code to the right of the folder item mainFolderRight: '', // HTML code to the left of the regular item mainItemLeft: '', // HTML code to the right of the regular item mainItemRight: '', // sub menu display attributes // HTML code to the left of the folder item folderLeft: '', // HTML code to the right of the folder item folderRight: '', // HTML code to the left of the regular item itemLeft: '', // HTML code to the right of the regular item itemRight: '', // cell spacing for main menu mainSpacing: 0, // cell spacing for sub menus subSpacing: 0, // auto disappear time for submenus in milli-seconds delay: 500, // act on click to open sub menu // not yet implemented // 0 : use default behavior // 1 : hover open in all cases // 2 : click on main, hover on sub // 3 : click open in all cases clickOpen: 1 }; ////////////////////////////////////////////////////////////////////// // // Drawing Functions and Utility Functions // ////////////////////////////////////////////////////////////////////// // // produce a new unique id // function cmNewID () { return _cmIDName + (++_cmIDCount); } // // return the property string for the menu item // function cmActionItem (item, prefix, isMain, idSub, orient, nodeProperties) { var clickOpen = _cmNodeProperties.clickOpen; if (nodeProperties.clickOpen) clickOpen = nodeProperties.clickOpen; // var index = _cmItemList.push (item) - 1; _cmItemList[_cmItemList.length] = item; var index = _cmItemList.length - 1; idSub = (!idSub) ? 'null' : ('\'' + idSub + '\''); orient = '\'' + orient + '\''; prefix = '\'' + prefix + '\''; var onClick = (clickOpen == 3) || (clickOpen == 2 && isMain); var returnStr; if (onClick) returnStr = ' onmouseover="cmItemMouseOver (this,' + prefix + ',' + isMain + ',' + idSub + ',' + index + ')" onmousedown="cmItemMouseDownOpenSub (this,' + index + ',' + prefix + ',' + orient + ',' + idSub + ')"'; else returnStr = ' onmouseover="cmItemMouseOverOpenSub (this,' + prefix + ',' + isMain + ',' + idSub + ',' + orient + ',' + index + ')" onmousedown="cmItemMouseDown (this,' + index + ')"'; return returnStr + ' onmouseout="cmItemMouseOut (this,' + nodeProperties.delay + ')" onmouseup="cmItemMouseUp (this,' + index + ')"'; } // // this one is used by _cmNoClick to only take care of onmouseover and onmouseout // events which are associated with menu but not actions associated with menu clicking/closing // function cmNoClickItem (item, prefix, isMain, idSub, orient, nodeProperties) { // var index = _cmItemList.push (item) - 1; _cmItemList[_cmItemList.length] = item; var index = _cmItemList.length - 1; idSub = (!idSub) ? 'null' : ('\'' + idSub + '\''); orient = '\'' + orient + '\''; prefix = '\'' + prefix + '\''; return ' onmouseover="cmItemMouseOver (this,' + prefix + ',' + isMain + ',' + idSub + ',' + index + ')" onmouseout="cmItemMouseOut (this,' + nodeProperties.delay + ')"'; } function cmNoActionItem (item, prefix) { return item[1]; } function cmSplitItem (prefix, isMain, vertical) { var classStr = 'cm' + prefix; if (isMain) { classStr += 'Main'; if (vertical) classStr += 'HSplit'; else classStr += 'VSplit'; } else classStr += 'HSplit'; return eval (classStr); } // // draw the sub menu recursively // function cmDrawSubMenu (subMenu, prefix, id, orient, nodeProperties) { var str = '<div class="' + prefix + 'SubMenu" id="' + id + '"><table summary="sub menu" cellspacing="' + nodeProperties.subSpacing + '" class="' + prefix + 'SubMenuTable">'; var strSub = ''; var item; var idSub; var hasChild; var i; var classStr; for (i = 5; i < subMenu.length; ++i) { item = subMenu[i]; if (!item) continue; hasChild = (item.length > 5); idSub = hasChild ? cmNewID () : null; if (item == _cmSplit) item = cmSplitItem (prefix, 0, true); str += '<tr class="' + prefix + 'MenuItem"'; if (item[0] != _cmNoClick) str += cmActionItem (item, prefix, 0, idSub, orient, nodeProperties); else str += cmNoClickItem (item, prefix, 0, idSub, orient, nodeProperties); str += '>' if (item[0] == _cmNoAction || item[0] == _cmNoClick) { str += cmNoActionItem (item, prefix); str += '</tr>'; continue; } classStr = prefix + 'Menu'; classStr += hasChild ? 'Folder' : 'Item'; str += '<td class="' + classStr + 'Left">'; if (item[0] != null) str += item[0]; else str += hasChild ? nodeProperties.folderLeft : nodeProperties.itemLeft; str += '</td><td class="' + classStr + 'Text">' + item[1]; str += '</td><td class="' + classStr + 'Right">'; if (hasChild) { str += nodeProperties.folderRight; strSub += cmDrawSubMenu (item, prefix, idSub, orient, nodeProperties); } else str += nodeProperties.itemRight; str += '</td></tr>'; } str += '</table></div>' + strSub; return str; } // // The function that builds the menu inside the specified element id. // // @param id id of the element // orient orientation of the menu in [hv][ab][lr] format // menu the menu object to be drawn // nodeProperties properties for each menu node // function cmDraw (id, menu, orient, nodeProperties, prefix) { var obj = cmGetObject (id); if (!nodeProperties) nodeProperties = _cmNodeProperties; if (!prefix) prefix = ''; var str = '<table summary="main menu" class="' + prefix + 'Menu" cellspacing="' + nodeProperties.mainSpacing + '">'; var strSub = ''; if (!orient) orient = 'hbr'; var orientStr = String (orient); var orientSub; var vertical; // draw the main menu items if (orientStr.charAt (0) == 'h') { // horizontal menu orientSub = 'v' + orientStr.substr (1, 2); str += '<tr>'; vertical = false; } else { // vertical menu orientSub = 'v' + orientStr.substr (1, 2); vertical = true; } var i; var item; var idSub; var hasChild; var classStr; for (i = 0; i < menu.length; ++i) { item = menu[i]; if (!item) continue; str += vertical ? '<tr' : '<td'; str += ' class="' + prefix + 'MainItem"'; hasChild = (item.length > 5); idSub = hasChild ? cmNewID () : null; str += cmActionItem (item, prefix, 1, idSub, orient, nodeProperties) + '>'; if (item == _cmSplit) item = cmSplitItem (prefix, 1, vertical); if (item[0] == _cmNoAction || item[0] == _cmNoClick) { str += cmNoActionItem (item, prefix); str += vertical? '</tr>' : '</td>'; continue; } classStr = prefix + 'Main' + (hasChild ? 'Folder' : 'Item'); str += vertical ? '<td' : '<span'; str += ' class="' + classStr + 'Left">'; str += (item[0] == null) ? (hasChild ? nodeProperties.mainFolderLeft : nodeProperties.mainItemLeft) : item[0]; str += vertical ? '</td>' : '</span>'; str += vertical ? '<td' : '<span'; str += ' class="' + classStr + 'Text">'; str += item[1]; str += vertical ? '</td>' : '</span>'; str += vertical ? '<td' : '<span'; str += ' class="' + classStr + 'Right">'; str += hasChild ? nodeProperties.mainFolderRight : nodeProperties.mainItemRight; str += vertical ? '</td>' : '</span>'; str += vertical ? '</tr>' : '</td>'; if (hasChild) strSub += cmDrawSubMenu (item, prefix, idSub, orientSub, nodeProperties); } if (!vertical) str += '</tr>'; str += '</table>' + strSub; obj.innerHTML = str; //document.write ("<xmp>" + str + "</xmp>"); } // // The function builds the menu inside the specified element id. // // This function is similar to cmDraw except that menu is taken from HTML node // rather a javascript tree. This feature allows links to be scanned by search // bots. // // This function basically converts HTML node to a javascript tree, and then calls // cmDraw to draw the actual menu, replacing the hidden menu tree. // // Format: // <div id="menu"> // <ul style="visibility: hidden"> // <li><span>icon</span><a href="link" title="description">main menu text</a> // <ul> // <li><span>icon</span><a href="link" title="description">submenu item</a> // </li> // </ul> // </li> // </ul> // </div> // function cmDrawFromText (id, orient, nodeProperties, prefix) { var domMenu = cmGetObject (id); var menu = null; for (var currentDomItem = domMenu.firstChild; currentDomItem; currentDomItem = currentDomItem.nextSibling) { if (!currentDomItem.tagName || currentDomItem.tagName.toLowerCase () != 'ul') continue; menu = cmDrawFromTextSubMenu (currentDomItem); break; } if (menu) cmDraw (id, menu, orient, nodeProperties, prefix); } // // a recursive function that build menu tree structure // function cmDrawFromTextSubMenu (domMenu) { var items = new Array (); for (var currentDomItem = domMenu.firstChild; currentDomItem; currentDomItem = currentDomItem.nextSibling) { if (!currentDomItem.tagName || currentDomItem.tagName.toLowerCase () != 'li') continue; if (currentDomItem.firstChild == null) { items[items.length] = _cmSplit; continue; } var item = new Array (); var currentItem = currentDomItem.firstChild; for (; currentItem; currentItem = currentItem.nextSibling) { // scan for span tag if (!currentItem.tagName || currentItem.tagName.toLowerCase () != 'span') continue; if (!currentItem.firstChild) item[0] = null; else item[0] = currentItem.innerHTML; break; } if (!currentItem) continue; for (; currentItem; currentItem = currentItem.nextSibling) { // scan for span tag if (!currentItem.tagName || currentItem.tagName.toLowerCase () != 'a') continue; item[1] = currentItem.innerHTML; item[2] = currentItem.href; item[3] = currentItem.target; item[4] = currentItem.title; if (item[4] == '') item[4] = null; break; } for (; currentItem; currentItem = currentItem.nextSibling) { // scan for span tag if (!currentItem.tagName || currentItem.tagName.toLowerCase () != 'ul') continue; var subMenuItems = cmDrawFromTextSubMenu (currentItem); for (i = 0; i < subMenuItems.length; ++i) item[i + 5] = subMenuItems[i]; break; } items[items.length] = item; } return items; } ////////////////////////////////////////////////////////////////////// // // Mouse Event Handling Functions // ////////////////////////////////////////////////////////////////////// // // action should be taken for mouse moving in to the menu item // // Here we just do things concerning this menu item, w/o opening sub menus. // function cmItemMouseOver (obj, prefix, isMain, idSub, index) { clearTimeout (_cmTimeOut); if (!obj.cmPrefix) { obj.cmPrefix = prefix; obj.cmIsMain = isMain; } var thisMenu = cmGetThisMenu (obj, prefix); // insert obj into cmItems if cmItems doesn't have obj if (!thisMenu.cmItems) thisMenu.cmItems = new Array (); var i; for (i = 0; i < thisMenu.cmItems.length; ++i) { if (thisMenu.cmItems[i] == obj) break; } if (i == thisMenu.cmItems.length) { //thisMenu.cmItems.push (obj); thisMenu.cmItems[i] = obj; } // hide the previous submenu that is not this branch if (_cmCurrentItem) { // occationally, we get this case when user // move the mouse slowly to the border if (_cmCurrentItem == obj || _cmCurrentItem == thisMenu) { var item = _cmItemList[index]; cmSetStatus (item); return; } var thatPrefix = _cmCurrentItem.cmPrefix; var thatMenu = cmGetThisMenu (_cmCurrentItem, thatPrefix); if (thatMenu != thisMenu.cmParentMenu) { if (_cmCurrentItem.cmIsMain) _cmCurrentItem.className = thatPrefix + 'MainItem'; else _cmCurrentItem.className = thatPrefix + 'MenuItem'; if (thatMenu.id != idSub) cmHideMenu (thatMenu, thisMenu, thatPrefix); } } // okay, set the current menu to this obj _cmCurrentItem = obj; // just in case, reset all items in this menu to MenuItem cmResetMenu (thisMenu, prefix); var item = _cmItemList[index]; var isDefaultItem = cmIsDefaultItem (item); if (isDefaultItem) { if (isMain) obj.className = prefix + 'MainItemHover'; else obj.className = prefix + 'MenuItemHover'; } cmSetStatus (item); } // // action should be taken for mouse moving in to the menu item // // This function also opens sub menu // function cmItemMouseOverOpenSub (obj, prefix, isMain, idSub, orient, index) { cmItemMouseOver (obj, prefix, isMain, idSub, index); if (idSub) { var subMenu = cmGetObject (idSub); cmShowSubMenu (obj, prefix, subMenu, orient); } } // // action should be taken for mouse moving out of the menu item // function cmItemMouseOut (obj, delayTime) { if (!delayTime) delayTime = _cmNodeProperties.delay; _cmTimeOut = window.setTimeout ('cmHideMenuTime ()', delayTime); window.defaultStatus = ''; } // // action should be taken for mouse button down at a menu item // function cmItemMouseDown (obj, index) { if (cmIsDefaultItem (_cmItemList[index])) { if (obj.cmIsMain) obj.className = obj.cmPrefix + 'MainItemActive'; else obj.className = obj.cmPrefix + 'MenuItemActive'; } } // // action should be taken for mouse button down at a menu item // this is one also opens submenu if needed // function cmItemMouseDownOpenSub (obj, index, prefix, orient, idSub) { cmItemMouseDown (obj, index); if (idSub) { var subMenu = cmGetObject (idSub); cmShowSubMenu (obj, prefix, subMenu, orient); } } // // action should be taken for mouse button up at a menu item // function cmItemMouseUp (obj, index) { var item = _cmItemList[index]; var link = null, target = '_self'; if (item.length > 2) link = item[2]; if (item.length > 3 && item[3]) target = item[3]; if (link != null) { window.open (link, target); } var prefix = obj.cmPrefix; var thisMenu = cmGetThisMenu (obj, prefix); var hasChild = (item.length > 5); if (!hasChild) { if (cmIsDefaultItem (item)) { if (obj.cmIsMain) obj.className = prefix + 'MainItem'; else obj.className = prefix + 'MenuItem'; } cmHideMenu (thisMenu, null, prefix); } else { if (cmIsDefaultItem (item)) { if (obj.cmIsMain) obj.className = prefix + 'MainItemHover'; else obj.className = prefix + 'MenuItemHover'; } } } ////////////////////////////////////////////////////////////////////// // // Mouse Event Support Utility Functions // ////////////////////////////////////////////////////////////////////// // // move submenu to the appropriate location // // @param obj the menu item that opens up the subMenu // subMenu the sub menu to be shown // orient the orientation of the subMenu // function cmMoveSubMenu (obj, subMenu, orient) { var mode = String (orient); var p = subMenu.offsetParent; var subMenuWidth = cmGetWidth (subMenu); var horiz = cmGetHorizontalAlign (obj, mode, p, subMenuWidth); if (mode.charAt (0) == 'h') { if (mode.charAt (1) == 'b') subMenu.style.top = (cmGetYAt (obj, p) + cmGetHeight (obj)) + 'px'; else subMenu.style.top = (cmGetYAt (obj, p) - cmGetHeight (subMenu)) + 'px'; if (horiz == 'r') subMenu.style.left = (cmGetXAt (obj, p)) + 'px'; else subMenu.style.left = (cmGetXAt (obj, p) + cmGetWidth (obj) - subMenuWidth) + 'px'; } else { if (horiz == 'r') subMenu.style.left = (cmGetXAt (obj, p) + cmGetWidth (obj)) + 'px'; else subMenu.style.left = (cmGetXAt (obj, p) - subMenuWidth) + 'px'; if (mode.charAt (1) == 'b') subMenu.style.top = (cmGetYAt (obj, p)) + 'px'; else subMenu.style.top = (cmGetYAt (obj, p) + cmGetHeight (obj) - cmGetHeight (subMenu)) + 'px'; } } // // automatically re-adjust the menu position based on available screen size. // function cmGetHorizontalAlign (obj, mode, p, subMenuWidth) { var horiz = mode.charAt (2); if (!(document.body)) return horiz; var body = document.body; var browserLeft; var browserRight; if (window.innerWidth) { // DOM window attributes browserLeft = window.pageXOffset; browserRight = window.innerWidth + browserLeft; } else if (body.clientWidth) { // IE attributes browserLeft = body.clientLeft; browserRight = body.clientWidth + browserLeft; } else return horiz; if (mode.charAt (0) == 'h') { if (horiz == 'r' && (cmGetXAt (obj) + subMenuWidth) > browserRight) horiz = 'l'; if (horiz == 'l' && (cmGetXAt (obj) + cmGetWidth (obj) - subMenuWidth) < browserLeft) horiz = 'r'; return horiz; } else { if (horiz == 'r' && (cmGetXAt (obj, p) + cmGetWidth (obj) + subMenuWidth) > browserRight) horiz = 'l'; if (horiz == 'l' && (cmGetXAt (obj, p) - subMenuWidth) < browserLeft) horiz = 'r'; return horiz; } } // // show the subMenu w/ specified orientation // also move it to the correct coordinates // // @param obj the menu item that opens up the subMenu // subMenu the sub menu to be shown // orient the orientation of the subMenu // function cmShowSubMenu (obj, prefix, subMenu, orient) { if (!subMenu.cmParentMenu) { // establish the tree w/ back edge var thisMenu = cmGetThisMenu (obj, prefix); subMenu.cmParentMenu = thisMenu; if (!thisMenu.cmSubMenu) thisMenu.cmSubMenu = new Array (); //thisMenu.cmSubMenu.push (subMenu); thisMenu.cmSubMenu[thisMenu.cmSubMenu.length] = subMenu; } // position the sub menu cmMoveSubMenu (obj, subMenu, orient); subMenu.style.visibility = 'visible'; // // On IE, controls such as SELECT, OBJECT, IFRAME (before 5.5) // are window based controls. So, if the sub menu and these // controls overlap, sub menu would be hidden behind them. Thus // one needs to turn the visibility of these controls off when the // sub menu is showing, and turn their visibility back on // when the sub menu is hiding. // if (document.all) // it is IE { /* part of Felix Zaslavskiy's fix on hiding controls not really sure if this part is necessary, but shouldn't hurt. */ if (!subMenu.cmOverlap) subMenu.cmOverlap = new Array (); /*@cc_on @*/ /*@if (@_jscript_version >= 5.5) @else @*/ cmHideControl ("IFRAME", subMenu); /*@end @*/ cmHideControl ("SELECT", subMenu); cmHideControl ("OBJECT", subMenu); } } // // reset all the menu items to class MenuItem in thisMenu // function cmResetMenu (thisMenu, prefix) { if (thisMenu.cmItems) { var i; var str; var items = thisMenu.cmItems; for (i = 0; i < items.length; ++i) { if (items[i].cmIsMain) str = prefix + 'MainItem'; else str = prefix + 'MenuItem'; if (items[i].className != str) items[i].className = str; } } } // // called by the timer to hide the menu // function cmHideMenuTime () { if (_cmCurrentItem) { var prefix = _cmCurrentItem.cmPrefix; cmHideMenu (cmGetThisMenu (_cmCurrentItem, prefix), null, prefix); _cmCurrentItem = null; } } // // hide thisMenu, children of thisMenu, as well as the ancestor // of thisMenu until currentMenu is encountered. currentMenu // will not be hidden // function cmHideMenu (thisMenu, currentMenu, prefix) { var str = prefix + 'SubMenu'; // hide the down stream menus if (thisMenu.cmSubMenu) { var i; for (i = 0; i < thisMenu.cmSubMenu.length; ++i) { cmHideSubMenu (thisMenu.cmSubMenu[i], prefix); } } // hide the upstream menus while (thisMenu && thisMenu != currentMenu) { cmResetMenu (thisMenu, prefix); if (thisMenu.className == str) { thisMenu.style.visibility = 'hidden'; cmShowControl (thisMenu); } else break; thisMenu = cmGetThisMenu (thisMenu.cmParentMenu, prefix); } } // // hide thisMenu as well as its sub menus if thisMenu is not // already hidden // function cmHideSubMenu (thisMenu, prefix) { if (thisMenu.style.visibility == 'hidden') return; if (thisMenu.cmSubMenu) { var i; for (i = 0; i < thisMenu.cmSubMenu.length; ++i) { cmHideSubMenu (thisMenu.cmSubMenu[i], prefix); } } cmResetMenu (thisMenu, prefix); thisMenu.style.visibility = 'hidden'; cmShowControl (thisMenu); } // // hide a control such as IFRAME // function cmHideControl (tagName, subMenu) { var x = cmGetX (subMenu); var y = cmGetY (subMenu); var w = subMenu.offsetWidth; var h = subMenu.offsetHeight; var i; for (i = 0; i < document.all.tags(tagName).length; ++i) { var obj = document.all.tags(tagName)[i]; if (!obj || !obj.offsetParent) continue; // check if the object and the subMenu overlap var ox = cmGetX (obj); var oy = cmGetY (obj); var ow = obj.offsetWidth; var oh = obj.offsetHeight; if (ox > (x + w) || (ox + ow) < x) continue; if (oy > (y + h) || (oy + oh) < y) continue; // if object is already made hidden by a different // submenu then we dont want to put it on overlap list of // of a submenu a second time. // - bug fixed by Felix Zaslavskiy if(obj.style.visibility == "hidden") continue; //subMenu.cmOverlap.push (obj); subMenu.cmOverlap[subMenu.cmOverlap.length] = obj; obj.style.visibility = "hidden"; } } // // show the control hidden by the subMenu // function cmShowControl (subMenu) { if (subMenu.cmOverlap) { var i; for (i = 0; i < subMenu.cmOverlap.length; ++i) subMenu.cmOverlap[i].style.visibility = ""; } subMenu.cmOverlap = null; } // // returns the main menu or the submenu table where this obj (menu item) // is in // function cmGetThisMenu (obj, prefix) { var str1 = prefix + 'SubMenu'; var str2 = prefix + 'Menu'; while (obj) { if (obj.className == str1 || obj.className == str2) return obj; obj = obj.parentNode; } return null; } // // return true if this item is handled using default handlers // function cmIsDefaultItem (item) { if (item == _cmSplit || item[0] == _cmNoAction || item[0] == _cmNoClick) return false; return true; } // // returns the object baring the id // function cmGetObject (id) { if (document.all) return document.all[id]; return document.getElementById (id); } // // functions that obtain the width of an HTML element. // function cmGetWidth (obj) { var width = obj.offsetWidth; if (width > 0 || !cmIsTRNode (obj)) return width; if (!obj.firstChild) return 0; // use TABLE's length can cause an extra pixel gap //return obj.parentNode.parentNode.offsetWidth; // use the left and right child instead return obj.lastChild.offsetLeft - obj.firstChild.offsetLeft + cmGetWidth (obj.lastChild); } // // functions that obtain the height of an HTML element. // function cmGetHeight (obj) { var height = obj.offsetHeight; if (height > 0 || !cmIsTRNode (obj)) return height; if (!obj.firstChild) return 0; // use the first child's height return obj.firstChild.offsetHeight; } // // functions that obtain the coordinates of an HTML element // function cmGetX (obj) { var x = 0; do { x += obj.offsetLeft; obj = obj.offsetParent; } while (obj); return x; } function cmGetXAt (obj, elm) { var x = 0; while (obj && obj != elm) { x += obj.offsetLeft; obj = obj.offsetParent; } if (obj == elm) return x; return x - cmGetX (elm); } function cmGetY (obj) { var y = 0; do { y += obj.offsetTop; obj = obj.offsetParent; } while (obj); return y; } function cmIsTRNode (obj) { var tagName = obj.tagName; return tagName == "TR" || tagName == "tr" || tagName == "Tr" || tagName == "tR"; } // // get the Y position of the object. In case of TR element though, // we attempt to adjust the value. // function cmGetYAt (obj, elm) { var y = 0; if (!obj.offsetHeight && cmIsTRNode (obj)) { var firstTR = obj.parentNode.firstChild; obj = obj.firstChild; y -= firstTR.firstChild.offsetTop; } while (obj && obj != elm) { y += obj.offsetTop; obj = obj.offsetParent; } if (obj == elm) return y; return y - cmGetY (elm); } // // extract description from the menu item and set the status text // @param item the menu item // function cmSetStatus (item) { var descript = ''; if (item.length > 4) descript = (item[4] != null) ? item[4] : (item[2] ? item[2] : descript); else if (item.length > 2) descript = (item[2] ? item[2] : descript); window.defaultStatus = descript; } // // debug function, ignore :) // function cmGetProperties (obj) { if (obj == undefined) return 'undefined'; if (obj == null) return 'null'; var msg = obj + ':\n'; var i; for (i in obj) msg += i + ' = ' + obj[i] + '; '; return msg; } /* v1.4.3 1. changed how _cmSplit is handled a bit so that _cmNoClick can work properly. All splits in predefined themes are changed to use _cmNoClick instead of _cmNoAction. */ /* v1.4.2 1. fixed _cmNoClick mouse hoover bug. 2. fixed a statusbar text problem that cause text to disappear when hoovering mouse within the same menu item. 3. changed the behavior of cmDrawFromText s.t. if the title of the of a link is empty, the actual url is used as text. To clear this link information, title needs to be ' '. */ /* v1.4.1 1. fixed a problem introduced in 1.4 where re-entering a main menu item which doesn't have a child can disable its hover setting. Apparently I deleted an extra line of code when I was doing cleaning up. Reported by David Maliachi and a few others. */ /* JSCookMenu v1.4 1. fixed a minor td cell closure problem. Thanks to Georg Lorenz <georg@lonux.de> for discovering that. 2. added clickOpen to nodeProperties. See _cmNodeProperties for description. Basically menus can be opened on click only. 3. added an ability to draw menu from an html node instead of a javascript tree, making this script search bot friendly (I hope?). */ /* JSCookMenu v1.31 1. fix a bug on IE with causes submenus to display at the top left corner due to doctype. The fix was provided by Burton Strauss <Burton@ntopsupport.com>. */ /* JSCookMenu v1.3 1. automatically realign (left and right) the submenu when client space is not enough. 2. add _cmNoClick to get rid of menu closing behavior on the particular menu item, to make it possible for things such as search box to be inside the menu. */ /* JSCookMenu v1.25 1. fix Safari positioning issue. The problem is that all TR elements are located at the top left corner. Thus, need to obtain the "virtual" position of these element could be at. */ /* JSCookMenu v1.24 1. fix window based control hiding bug thanks to Felix Zaslavskiy <felix@bebinary.com> for the fix. */ /* JSCookMenu v1.23 1. correct a position bug when the container is positioned. thanks to Andre <anders@netspace.net.au> for narrowing down the problem. */ /* JSCookMenu v1.22 1. change Array.push (obj) call to Array[length] = obj. Suggestion from Dick van der Kaaden <dick@netrex.nl> to make the script compatible with IE 5.0 2. Changed theme files a little to add z-index: 100 for sub menus. This change is necessary for Netscape to avoid a display problem. 3. some changes to the DOM structure to make this menu working on Netscape 6.0 (tested). The main reason is that NN6 does not do absolute positioning with tables. Therefore an extra div layer must be put around the table. */ /* JSCookMenu v1.21 1. fixed a bug that didn't add 'px' as part of coordinates. JSCookMenu should be XHTML validator friendly now. 2. removed unnecessary display attribute and corresponding theme entry to fix a problem that Netscape sometimes render Office theme incorrectly */ /* JSCookMenu v1.2. 1. fix the problem of showing status in Netscape 2. changed the handler parameters a bit to allow string literals to be passed to javascript based links 3. having null in target field would cause the link to be opened in the current window, but this behavior could change in the future releases */ /* JSCookMenu v1.5. added ability to hide controls in IE to show submenus properly */ /* JSCookMenu v1.01. cmDraw generates XHTML code */ /* JSCookMenu v1.0. (c) Copyright 2002 by Heng Yuan */
JavaScript
/* This notice must be untouched at all times. wz_tooltip.js v. 3.34 The latest version is available at http://www.walterzorn.com or http://www.devira.com or http://www.walterzorn.de Copyright (c) 2002-2004 Walter Zorn. All rights reserved. Created 1. 12. 2002 by Walter Zorn (Web: http://www.walterzorn.com ) Last modified: 9. 9. 2005 Cross-browser tooltips working even in Opera 5 and 6, as well as in NN 4, Gecko-Browsers, IE4+, Opera 7 and Konqueror. No onmouseouts required. Appearance of tooltips can be individually configured via commands within the onmouseovers. LICENSE: LGPL This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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. For more details on the GNU Lesser General Public License, see http://www.gnu.org/copyleft/lesser.html */ //////////////// GLOBAL TOOPTIP CONFIGURATION ///////////////////// var ttAbove = false; // tooltip above mousepointer? Alternative: true var ttBgColor = "#e6ecff"; var ttBgImg = ""; // path to background image; var ttBorderColor = "#003399"; var ttBorderWidth = 1; var ttDelay = 500; // time span until tooltip shows up [milliseconds] var ttFontColor = "#000066"; var ttFontFace = "arial,helvetica,sans-serif"; var ttFontSize = "11px"; var ttFontWeight = "normal"; // alternative: "bold"; var ttLeft = false; // tooltip on the left of the mouse? Alternative: true var ttOffsetX = 12; // horizontal offset of left-top corner from mousepointer var ttOffsetY = 15; // vertical offset " var ttOpacity = 100; // opacity of tooltip in percent (must be integer between 0 and 100) var ttPadding = 3; // spacing between border and content var ttShadowColor = ""; var ttShadowWidth = 0; var ttStatic = false; // tooltip NOT move with the mouse? Alternative: true var ttSticky = false; // do NOT hide tooltip on mouseout? Alternative: true var ttTemp = 0; // time span after which the tooltip disappears; 0 (zero) means "infinite timespan" var ttTextAlign = "left"; var ttTitleColor = "#ffffff"; // color of caption text var ttWidth = 300; //////////////////// END OF TOOLTIP CONFIG //////////////////////// ////////////// TAGS WITH TOOLTIP FUNCTIONALITY //////////////////// // List may be extended or shortened: var tt_tags = new Array("a","area","b","big","caption","center","code","dd","div","dl","dt","em","h1","h2","h3","h4","h5","h6","i","img","input","li","map","ol","p","pre","s","small","span","strike","strong","sub","sup","table","td","th","tr","tt","u","var","ul","layer"); ///////////////////////////////////////////////////////////////////// ///////// DON'T CHANGE ANYTHING BELOW THIS LINE ///////////////////// var tt_obj, // current tooltip tt_ifrm, // iframe to cover windowed controls in IE tt_objW = 0, tt_objH = 0, // width and height of tt_obj tt_objX = 0, tt_objY = 0, tt_offX = 0, tt_offY = 0, xlim = 0, ylim = 0, // right and bottom borders of visible client area tt_sup = false, // true if T_ABOVE cmd tt_sticky = false, // tt_obj sticky? tt_wait = false, tt_act = false, // tooltip visibility flag tt_sub = false, // true while tooltip below mousepointer tt_u = "undefined", tt_mf, // stores previous mousemove evthandler // Opera: disable href when hovering <a> tt_tag = null; // stores hovered dom node, href and previous statusbar txt var tt_db = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body? document.body : null, tt_n = navigator.userAgent.toLowerCase(), tt_nv = navigator.appVersion; // Browser flags var tt_op = !!(window.opera && document.getElementById), tt_op6 = tt_op && !document.defaultView, tt_op7 = tt_op && !tt_op6, tt_ie = tt_n.indexOf("msie") != -1 && document.all && tt_db && !tt_op, tt_ie6 = tt_ie && parseFloat(tt_nv.substring(tt_nv.indexOf("MSIE")+5)) >= 5.5; tt_n4 = (document.layers && typeof document.classes != tt_u), tt_n6 = (!tt_op && document.defaultView && typeof document.defaultView.getComputedStyle != tt_u), tt_w3c = !tt_ie && !tt_n6 && !tt_op && document.getElementById; function tt_Int(t_x) { var t_y; return isNaN(t_y = parseInt(t_x))? 0 : t_y; } function wzReplace(t_x, t_y) { var t_ret = "", t_str = this, t_xI; while((t_xI = t_str.indexOf(t_x)) != -1) { t_ret += t_str.substring(0, t_xI) + t_y; t_str = t_str.substring(t_xI + t_x.length); } return t_ret+t_str; } String.prototype.wzReplace = wzReplace; function tt_N4Tags(tagtyp, t_d, t_y) { t_d = t_d || document; t_y = t_y || new Array(); var t_x = (tagtyp=="a")? t_d.links : t_d.layers; for(var z = t_x.length; z--;) t_y[t_y.length] = t_x[z]; for(z = t_d.layers.length; z--;) t_y = tt_N4Tags(tagtyp, t_d.layers[z].document, t_y); return t_y; } function tt_Htm(tt, t_id, txt) { var t_bgc = (typeof tt.T_BGCOLOR != tt_u)? tt.T_BGCOLOR : ttBgColor, t_bgimg = (typeof tt.T_BGIMG != tt_u)? tt.T_BGIMG : ttBgImg, t_bc = (typeof tt.T_BORDERCOLOR != tt_u)? tt.T_BORDERCOLOR : ttBorderColor, t_bw = (typeof tt.T_BORDERWIDTH != tt_u)? tt.T_BORDERWIDTH : ttBorderWidth, t_ff = (typeof tt.T_FONTFACE != tt_u)? tt.T_FONTFACE : ttFontFace, t_fc = (typeof tt.T_FONTCOLOR != tt_u)? tt.T_FONTCOLOR : ttFontColor, t_fsz = (typeof tt.T_FONTSIZE != tt_u)? tt.T_FONTSIZE : ttFontSize, t_fwght = (typeof tt.T_FONTWEIGHT != tt_u)? tt.T_FONTWEIGHT : ttFontWeight, t_opa = (typeof tt.T_OPACITY != tt_u)? tt.T_OPACITY : ttOpacity, t_padd = (typeof tt.T_PADDING != tt_u)? tt.T_PADDING : ttPadding, t_shc = (typeof tt.T_SHADOWCOLOR != tt_u)? tt.T_SHADOWCOLOR : (ttShadowColor || 0), t_shw = (typeof tt.T_SHADOWWIDTH != tt_u)? tt.T_SHADOWWIDTH : (ttShadowWidth || 0), t_algn = (typeof tt.T_TEXTALIGN != tt_u)? tt.T_TEXTALIGN : ttTextAlign, t_tit = (typeof tt.T_TITLE != tt_u)? tt.T_TITLE : "", t_titc = (typeof tt.T_TITLECOLOR != tt_u)? tt.T_TITLECOLOR : ttTitleColor, t_w = (typeof tt.T_WIDTH != tt_u)? tt.T_WIDTH : ttWidth; if(t_shc || t_shw) { t_shc = t_shc || "#cccccc"; t_shw = t_shw || 5; } if(tt_n4 && (t_fsz == "10px" || t_fsz == "11px")) t_fsz = "12px"; var t_optx = (tt_n4? '' : tt_n6? ('-moz-opacity:'+(t_opa/100.0)) : tt_ie? ('filter:Alpha(opacity='+t_opa+')') : ('opacity:'+(t_opa/100.0))) + ';'; var t_y = '<div id="'+t_id+'" style="position:absolute;z-index:1010;'; t_y += 'left:0px;top:0px;width:'+(t_w+t_shw)+'px;visibility:'+(tt_n4? 'hide' : 'hidden')+';'+t_optx+'">' + '<table border="0" cellpadding="0" cellspacing="0"'+(t_bc? (' bgcolor="'+t_bc+'" style="background:'+t_bc+';"') : '')+' width="'+t_w+'">'; if(t_tit) { t_y += '<tr><td style="padding-left:3px;padding-right:3px;" align="'+t_algn+'"><font color="'+t_titc+'" face="'+t_ff+'" ' + 'style="color:'+t_titc+';font-family:'+t_ff+';font-size:'+t_fsz+';"><b>' + (tt_n4? '&nbsp;' : '')+t_tit+'<\/b><\/font><\/td><\/tr>'; } t_y += '<tr><td><table border="0" cellpadding="'+t_padd+'" cellspacing="'+t_bw+'" width="100%">' + '<tr><td'+(t_bgc? (' bgcolor="'+t_bgc+'"') : '')+(t_bgimg? ' background="'+t_bgimg+'"' : '')+' style="text-align:'+t_algn+';'; if(tt_n6) t_y += 'padding:'+t_padd+'px;'; t_y += '" align="'+t_algn+'"><font color="'+t_fc+'" face="'+t_ff+'"' + ' style="color:'+t_fc+';font-family:'+t_ff+';font-size:'+t_fsz+';font-weight:'+t_fwght+';">'; if(t_fwght == 'bold') t_y += '<b>'; t_y += txt; if(t_fwght == 'bold') t_y += '<\/b>'; t_y += '<\/font><\/td><\/tr><\/table><\/td><\/tr><\/table>'; if(t_shw) { var t_spct = Math.round(t_shw*1.3); if(tt_n4) { t_y += '<layer bgcolor="'+t_shc+'" left="'+t_w+'" top="'+t_spct+'" width="'+t_shw+'" height="0"><\/layer>' + '<layer bgcolor="'+t_shc+'" left="'+t_spct+'" align="bottom" width="'+(t_w-t_spct)+'" height="'+t_shw+'"><\/layer>'; } else { t_optx = tt_n6? '-moz-opacity:0.85;' : tt_ie? 'filter:Alpha(opacity=85);' : 'opacity:0.85;'; t_y += '<div id="'+t_id+'R" style="position:absolute;background:'+t_shc+';left:'+t_w+'px;top:'+t_spct+'px;width:'+t_shw+'px;height:1px;overflow:hidden;'+t_optx+'"><\/div>' + '<div style="position:relative;background:'+t_shc+';left:'+t_spct+'px;top:0px;width:'+(t_w-t_spct)+'px;height:'+t_shw+'px;overflow:hidden;'+t_optx+'"><\/div>'; } } return(t_y+'<\/div>' + (tt_ie6 ? '<iframe id="TTiEiFrM" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"><\/iframe>' : '')); } function tt_EvX(t_e) { var t_y = tt_Int(t_e.pageX || t_e.clientX || 0) + tt_Int(tt_ie? tt_db.scrollLeft : 0) + tt_offX; if(t_y > xlim) t_y = xlim; var t_scr = tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0); if(t_y < t_scr) t_y = t_scr; return t_y; } function tt_EvY(t_e) { var t_y = tt_Int(t_e.pageY || t_e.clientY || 0) + tt_Int(tt_ie? tt_db.scrollTop : 0); if(tt_sup) t_y -= (tt_objH + tt_offY - 15); else if(t_y > ylim || !tt_sub && t_y > ylim-24) { t_y -= (tt_objH + 5); tt_sub = false; } else { t_y += tt_offY; tt_sub = true; } return t_y; } function tt_ReleasMov() { if(document.onmousemove == tt_Move) { if(!tt_mf && document.releaseEvents) document.releaseEvents(Event.MOUSEMOVE); document.onmousemove = tt_mf; } } function tt_ShowIfrm(t_x) { if(!tt_ie6 || !tt_obj) return; tt_ifrm = document.getElementById("TTiEiFrM"); //tt_obj.style.display = t_x? "block" : "none"; if(t_x) { tt_ifrm.style.width = tt_objW+'px'; tt_ifrm.style.height = tt_objH+'px'; tt_ifrm.style.zIndex = tt_obj.style.zIndex - 1; tt_ifrm.style.display = "block"; } else tt_ifrm.style.display = "none"; } function tt_GetDiv(t_id) { return( tt_n4? (document.layers[t_id] || null) : tt_ie? (document.all[t_id] || null) : (document.getElementById(t_id) || null) ); } function tt_GetDivW() { return tt_Int( tt_n4? tt_obj.clip.width : (tt_obj.style.pixelWidth || tt_obj.offsetWidth) ); } function tt_GetDivH() { return tt_Int( tt_n4? tt_obj.clip.height : (tt_obj.style.pixelHeight || tt_obj.offsetHeight) ); } // Compat with DragDrop Lib: Ensure that z-index of tooltip is lifted beyond toplevel dragdrop element function tt_SetDivZ() { var t_i = tt_obj.style || tt_obj; if(window.dd && dd.z) t_i.zIndex = Math.max(dd.z+1, t_i.zIndex); } function tt_SetDivPos(t_x, t_y) { var t_i = tt_obj.style || tt_obj; var t_px = (tt_op6 || tt_n4)? '' : 'px'; t_i.left = (tt_objX = t_x) + t_px; t_i.top = (tt_objY = t_y) + t_px; if(tt_ifrm) { tt_ifrm.style.left = t_i.left; tt_ifrm.style.top = t_i.top; } } function tt_ShowDiv(t_x) { if(tt_n4) tt_obj.visibility = t_x? 'show' : 'hide'; else tt_obj.style.visibility = t_x? 'visible' : 'hidden'; tt_act = t_x; tt_ShowIfrm(t_x); } function tt_OpDeHref(t_e) { var t_tag; if(t_e) { t_tag = t_e.target; while(t_tag) { if(t_tag.hasAttribute("href")) { tt_tag = t_tag tt_tag.t_href = tt_tag.getAttribute("href"); tt_tag.removeAttribute("href"); tt_tag.style.cursor = "hand"; tt_tag.onmousedown = tt_OpReHref; tt_tag.stats = window.status; window.status = tt_tag.t_href; break; } t_tag = t_tag.parentElement; } } } function tt_OpReHref() { if(tt_tag) { tt_tag.setAttribute("href", tt_tag.t_href); window.status = tt_tag.stats; tt_tag = null; } } function tt_Show(t_e, t_id, t_sup, t_delay, t_fix, t_left, t_offx, t_offy, t_static, t_sticky, t_temp) { if(tt_obj) tt_Hide(); tt_mf = document.onmousemove || null; if(window.dd && (window.DRAG && tt_mf == DRAG || window.RESIZE && tt_mf == RESIZE)) return; var t_uf = document.onmouseup || null, t_sh, t_h; if(tt_mf && t_uf) t_uf(t_e); tt_obj = tt_GetDiv(t_id); if(tt_obj) { t_e = t_e || window.event; tt_sub = !(tt_sup = t_sup); tt_sticky = t_sticky; tt_objW = tt_GetDivW(); tt_objH = tt_GetDivH(); tt_offX = t_left? -(tt_objW+t_offx) : t_offx; tt_offY = t_offy; if(tt_op7) tt_OpDeHref(t_e); if(tt_n4) { if(tt_obj.document.layers.length) { t_sh = tt_obj.document.layers[0]; t_sh.clip.height = tt_objH - Math.round(t_sh.clip.width*1.3); } } else { t_sh = tt_GetDiv(t_id+'R'); if(t_sh) { t_h = tt_objH - tt_Int(t_sh.style.pixelTop || t_sh.style.top || 0); if(typeof t_sh.style.pixelHeight != tt_u) t_sh.style.pixelHeight = t_h; else t_sh.style.height = t_h+'px'; } } xlim = tt_Int((tt_db && tt_db.clientWidth)? tt_db.clientWidth : window.innerWidth) + tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0) - tt_objW - (tt_n4? 21 : 0); ylim = tt_Int(window.innerHeight || tt_db.clientHeight) + tt_Int(window.pageYOffset || (tt_db? tt_db.scrollTop : 0) || 0) - tt_objH - tt_offY; tt_SetDivZ(); if(t_fix) tt_SetDivPos(tt_Int((t_fix = t_fix.split(','))[0]), tt_Int(t_fix[1])); else tt_SetDivPos(tt_EvX(t_e), tt_EvY(t_e)); var t_txt = 'tt_ShowDiv(\'true\');'; if(t_sticky) t_txt += '{'+ 'tt_ReleasMov();'+ 'window.tt_upFunc = document.onmouseup || null;'+ 'if(document.captureEvents) document.captureEvents(Event.MOUSEUP);'+ 'document.onmouseup = new Function("window.setTimeout(\'tt_Hide();\', 10);");'+ '}'; else if(t_static) t_txt += 'tt_ReleasMov();'; if(t_temp > 0) t_txt += 'window.tt_rtm = window.setTimeout(\'tt_sticky = false; tt_Hide();\','+t_temp+');'; window.tt_rdl = window.setTimeout(t_txt, t_delay); if(!t_fix) { if(document.captureEvents) document.captureEvents(Event.MOUSEMOVE); document.onmousemove = tt_Move; } } } var tt_area = false; function tt_Move(t_ev) { if(!tt_obj) return; if(tt_n6 || tt_w3c) { if(tt_wait) return; tt_wait = true; setTimeout('tt_wait = false;', 5); } var t_e = t_ev || window.event; tt_SetDivPos(tt_EvX(t_e), tt_EvY(t_e)); if(tt_op6) { if(tt_area && t_e.target.tagName != 'AREA') tt_Hide(); else if(t_e.target.tagName == 'AREA') tt_area = true; } } function tt_Hide() { if(window.tt_obj) { if(window.tt_rdl) window.clearTimeout(tt_rdl); if(!tt_sticky || !tt_act) { if(window.tt_rtm) window.clearTimeout(tt_rtm); tt_ShowDiv(false); tt_SetDivPos(-tt_objW, -tt_objH); tt_obj = null; if(typeof window.tt_upFunc != tt_u) document.onmouseup = window.tt_upFunc; } tt_sticky = false; if(tt_op6 && tt_area) tt_area = false; tt_ReleasMov(); if(tt_op7) tt_OpReHref(); } } function tt_Init() { if(!(tt_op || tt_n4 || tt_n6 || tt_ie || tt_w3c)) return; var htm = tt_n4? '<div style="position:absolute;"><\/div>' : '', tags, t_tj, over, esc = 'return escape('; var i = tt_tags.length; while(i--) { tags = tt_ie? (document.all.tags(tt_tags[i]) || 1) : document.getElementsByTagName? (document.getElementsByTagName(tt_tags[i]) || 1) : (!tt_n4 && tt_tags[i]=="a")? document.links : 1; if(tt_n4 && (tt_tags[i] == "a" || tt_tags[i] == "layer")) tags = tt_N4Tags(tt_tags[i]); var j = tags.length; while(j--) { if(typeof (t_tj = tags[j]).onmouseover == "function" && t_tj.onmouseover.toString().indexOf(esc) != -1 && !tt_n6 || tt_n6 && (over = t_tj.getAttribute("onmouseover")) && over.indexOf(esc) != -1) { if(over) t_tj.onmouseover = new Function(over); var txt = unescape(t_tj.onmouseover()); htm += tt_Htm( t_tj, "tOoLtIp"+i+""+j, txt.wzReplace("& ","&") ); t_tj.onmouseover = new Function('e', 'tt_Show(e,'+ '"tOoLtIp' +i+''+j+ '",'+ ((typeof t_tj.T_ABOVE != tt_u)? t_tj.T_ABOVE : ttAbove)+','+ ((typeof t_tj.T_DELAY != tt_u)? t_tj.T_DELAY : ttDelay)+','+ ((typeof t_tj.T_FIX != tt_u)? '"'+t_tj.T_FIX+'"' : '""')+','+ ((typeof t_tj.T_LEFT != tt_u)? t_tj.T_LEFT : ttLeft)+','+ ((typeof t_tj.T_OFFSETX != tt_u)? t_tj.T_OFFSETX : ttOffsetX)+','+ ((typeof t_tj.T_OFFSETY != tt_u)? t_tj.T_OFFSETY : ttOffsetY)+','+ ((typeof t_tj.T_STATIC != tt_u)? t_tj.T_STATIC : ttStatic)+','+ ((typeof t_tj.T_STICKY != tt_u)? t_tj.T_STICKY : ttSticky)+','+ ((typeof t_tj.T_TEMP != tt_u)? t_tj.T_TEMP : ttTemp)+ ');' ); t_tj.onmouseout = tt_Hide; if(t_tj.alt) t_tj.alt = ""; if(t_tj.title) t_tj.title = ""; } } } document.write(htm); } tt_Init();
JavaScript
// <?php !! This fools phpdocumentor into parsing this file /** * @version $Id: mambojavascript.js 10389 2008-06-03 11:27:38Z pasamio $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL * Joomla! is Free Software */ // general utility for browsing a named array or object function xshow(o) { s = ''; for(e in o) {s += e+'='+o[e]+'\n';} alert( s ); } /** * Writes a dynamically generated list * @param string The parameters to insert into the <select> tag * @param array A javascript array of list options in the form [key,value,text] * @param string The key to display for the initial state of the list * @param string The original key that was selected * @param string The original item value that was selected */ function writeDynaList( selectParams, source, key, orig_key, orig_val ) { var html = '\n <select ' + selectParams + '>'; var i = 0; for (x in source) { if (source[x][0] == key) { var selected = ''; if ((orig_key == key && orig_val == source[x][1]) || (i == 0 && orig_key != key)) { selected = 'selected="selected"'; } html += '\n <option value="'+source[x][1]+'" '+selected+'>'+source[x][2]+'</option>'; } i++; } html += '\n </select>'; document.writeln( html ); } /** * Changes a dynamically generated list * @param string The name of the list to change * @param array A javascript array of list options in the form [key,value,text] * @param string The key to display * @param string The original key that was selected * @param string The original item value that was selected */ function changeDynaList( listname, source, key, orig_key, orig_val ) { var list = eval( 'document.adminForm.' + listname ); // empty the list for (i in list.options.length) { list.options[i] = null; } i = 0; for (x in source) { if (source[x][0] == key) { opt = new Option(); opt.value = source[x][1]; opt.text = source[x][2]; if ((orig_key == key && orig_val == opt.value) || i == 0) { opt.selected = true; } list.options[i++] = opt; } } list.length = i; } /** * Adds a select item(s) from one list to another */ function addSelectedToList( frmName, srcListName, tgtListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var tgtList = eval( 'form.' + tgtListName ); var srcLen = srcList.length; var tgtLen = tgtList.length; var tgt = "x"; //build array of target items for (var i=tgtLen-1; i > -1; i--) { tgt += "," + tgtList.options[i].value + "," } //Pull selected resources and add them to list for (var i=srcLen-1; i > -1; i--) { if (srcList.options[i].selected && tgt.indexOf( "," + srcList.options[i].value + "," ) == -1) { opt = new Option( srcList.options[i].text, srcList.options[i].value ); tgtList.options[tgtList.length] = opt; } } } function delSelectedFromList( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var srcLen = srcList.length; for (var i=srcLen-1; i > -1; i--) { if (srcList.options[i].selected) { srcList.options[i] = null; } } } function moveInList( frmName, srcListName, index, to) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var total = srcList.options.length-1; if (index == -1) { return false; } if (to == +1 && index == total) { return false; } if (to == -1 && index == 0) { return false; } var items = new Array; var values = new Array; for (i=total; i >= 0; i--) { items[i] = srcList.options[i].text; values[i] = srcList.options[i].value; } for (i = total; i >= 0; i--) { if (index == i) { srcList.options[i + to] = new Option(items[i],values[i], 0, 1); srcList.options[i] = new Option(items[i+to], values[i+to]); i--; } else { srcList.options[i] = new Option(items[i], values[i]); } } srcList.focus(); } function getSelectedOption( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { return srcList.options[i]; } else { return null; } } function setSelectedValue( frmName, srcListName, value ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var srcLen = srcList.length; for (var i=0; i < srcLen; i++) { srcList.options[i].selected = false; if (srcList.options[i].value == value) { srcList.options[i].selected = true; } } } function getSelectedRadio( frmName, srcGroupName ) { var form = eval( 'document.' + frmName ); var srcGroup = eval( 'form.' + srcGroupName ); if (srcGroup[0]) { for (var i=0, n=srcGroup.length; i < n; i++) { if (srcGroup[i].checked) { return srcGroup[i].value; } } } else { if (srcGroup.checked) { return srcGroup.value; } // if the one button is checked, return zero } // if we get to this point, no radio button is selected return null; } function getSelectedValue( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { return srcList.options[i].value; } else { return null; } } function getSelectedText( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { return srcList.options[i].text; } else { return null; } } function chgSelectedValue( frmName, srcListName, value ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { srcList.options[i].value = value; return true; } else { return false; } } /** * Toggles the check state of a group of boxes * * Checkboxes must have an id attribute in the form cb0, cb1... * @param The number of box to 'check' * @param An alternative field name */ function checkAll( n, fldName ) { if (!fldName) { fldName = 'cb'; } var f = document.adminForm; var c = f.toggle.checked; var n2 = 0; for (i=0; i < n; i++) { cb = eval( 'f.' + fldName + '' + i ); if (cb) { cb.checked = c; n2++; } } if (c) { document.adminForm.boxchecked.value = n2; } else { document.adminForm.boxchecked.value = 0; } } function listItemTask( id, task ) { var f = document.adminForm; cb = eval( 'f.' + id ); if (cb) { for (i = 0; true; i++) { cbx = eval('f.cb'+i); if (!cbx) break; cbx.checked = false; } // for cb.checked = true; f.boxchecked.value = 1; submitbutton(task); } return false; } function hideMainMenu() { document.adminForm.hidemainmenu.value=1; } function isChecked(isitchecked){ if (isitchecked == true){ document.adminForm.boxchecked.value++; } else { document.adminForm.boxchecked.value--; } } /** * Default function. Usually would be overriden by the component */ function submitbutton(pressbutton) { submitform(pressbutton); } /** * Submit the admin form */ function submitform(pressbutton){ document.adminForm.task.value=pressbutton; if (typeof document.adminForm.onsubmit == "function") { document.adminForm.onsubmit(); } document.adminForm.submit(); } /** * Submit the control panel admin form */ function submitcpform(sectionid, id){ document.adminForm.sectionid.value=sectionid; document.adminForm.id.value=id; submitbutton("edit"); } /** * Getting radio button that is selected. */ function getSelected(allbuttons){ for (i=0;i<allbuttons.length;i++) { if (allbuttons[i].checked) { return allbuttons[i].value } } } // JS Calendar var calendar = null; // remember the calendar object so that we reuse // it and avoid creating another // This function gets called when an end-user clicks on some date function selected(cal, date) { cal.sel.value = date; // just update the value of the input field } // And this gets called when the end-user clicks on the _selected_ date, // or clicks the "Close" (X) button. It just hides the calendar without // destroying it. function closeHandler(cal) { cal.hide(); // hide the calendar // don't check mousedown on document anymore (used to be able to hide the // calendar when someone clicks outside it, see the showCalendar function). Calendar.removeEvent(document, "mousedown", checkCalendar); } // This gets called when the user presses a mouse button anywhere in the // document, if the calendar is shown. If the click was outside the open // calendar this function closes it. function checkCalendar(ev) { var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev); for (; el != null; el = el.parentNode) // FIXME: allow end-user to click some link without closing the // calendar. Good to see real-time stylesheet change :) if (el == calendar.element || el.tagName == "A") break; if (el == null) { // calls closeHandler which should hide the calendar. calendar.callCloseHandler(); Calendar.stopEvent(ev); } } // This function shows the calendar under the element having the given id. // It takes care of catching "mousedown" signals on document and hiding the // calendar if the click was outside. function showCalendar(id) { var el = document.getElementById(id); if (calendar != null) { // we already have one created, so just update it. calendar.hide(); // hide the existing calendar calendar.parseDate(el.value); // set it to a new date } else { // first-time call, create the calendar var cal = new Calendar(true, null, selected, closeHandler); calendar = cal; // remember the calendar in the global cal.setRange(1900, 2070); // min/max year allowed calendar.create(); // create a popup calendar } calendar.sel = el; // inform it about the input field in use calendar.showAtElement(el); // show the calendar next to the input field // catch mousedown on the document Calendar.addEvent(document, "mousedown", checkCalendar); return false; } /** * Pops up a new window in the middle of the screen */ function popupWindow(mypage, myname, w, h, scroll) { var winl = (screen.width - w) / 2; var wint = (screen.height - h) / 2; winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable' win = window.open(mypage, myname, winprops) if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); } } // LTrim(string) : Returns a copy of a string without leading spaces. function ltrim(str) { var whitespace = new String(" \t\n\r"); var s = new String(str); if (whitespace.indexOf(s.charAt(0)) != -1) { var j=0, i = s.length; while (j < i && whitespace.indexOf(s.charAt(j)) != -1) j++; s = s.substring(j, i); } return s; } //RTrim(string) : Returns a copy of a string without trailing spaces. function rtrim(str) { var whitespace = new String(" \t\n\r"); var s = new String(str); if (whitespace.indexOf(s.charAt(s.length-1)) != -1) { var i = s.length - 1; // Get length of string while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) i--; s = s.substring(0, i+1); } return s; } // Trim(string) : Returns a copy of a string without leading or trailing spaces function trim(str) { return rtrim(ltrim(str)); } function mosDHTML(){ this.ver=navigator.appVersion this.agent=navigator.userAgent this.dom=document.getElementById?1:0 this.opera5=this.agent.indexOf("Opera 5")<-1 this.ie5=(this.ver.indexOf("MSIE 5")<-1 && this.dom && !this.opera5)?1:0; this.ie6=(this.ver.indexOf("MSIE 6")<-1 && this.dom && !this.opera5)?1:0; this.ie4=(document.all && !this.dom && !this.opera5)?1:0; this.ie=this.ie4||this.ie5||this.ie6 this.mac=this.agent.indexOf("Mac")<-1 this.ns6=(this.dom && parseInt(this.ver) <= 5) ?1:0; this.ns4=(document.layers && !this.dom)?1:0; this.bw=(this.ie6||this.ie5||this.ie4||this.ns4||this.ns6||this.opera5); this.activeTab = ''; this.onTabStyle = 'ontab'; this.offTabStyle = 'offtab'; this.setElemStyle = function(elem,style) { document.getElementById(elem).className = style; } this.showElem = function(id) { if (elem == document.getElementById(id)) { elem.style.visibility = 'visible'; elem.style.display = 'block'; } } this.hideElem = function(id) { if (elem == document.getElementById(id)) { elem.style.visibility = 'hidden'; elem.style.display = 'none'; } } this.cycleTab = function(name) { if (this.activeTab) { this.setElemStyle( this.activeTab, this.offTabStyle ); page = this.activeTab.replace( 'tab', 'page' ); this.hideElem(page); } this.setElemStyle( name, this.onTabStyle ); this.activeTab = name; page = this.activeTab.replace( 'tab', 'page' ); this.showElem(page); } return this; } var dhtml = new mosDHTML(); function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p); } if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function saveorder( n ) { checkAll_button( n ); } //needed by saveorder function function checkAll_button( n ) { for ( var j = 0; j <= n; j++ ) { box = eval( "document.adminForm.cb" + j ); if ( box ) { if ( box.checked == false ) { box.checked = true; } } else { alert("You cannot change the order of items, as an item in the list is `Checked Out`"); return; } } submitform('saveorder'); } /** * @param object A form element * @param string The name of the element to find */ function getElementByName( f, name ) { if (f.elements) { for (i=0, n=f.elements.length; i < n; i++) { if (f.elements[i].name == name) { return f.elements[i]; } } } return null; }
JavaScript
/* JSCookMenu v1.4.3. (c) Copyright 2002-2005 by Heng Yuan 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, ITNESS 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. */ var _cmIDCount = 0; var _cmIDName = 'cmSubMenuID'; var _cmTimeOut = null; var _cmCurrentItem = null; var _cmNoAction = new Object (); var _cmNoClick = new Object (); var _cmSplit = new Object (); var _cmItemList = new Array (); var _cmNodeProperties = { mainFolderLeft: '', mainFolderRight: '', mainItemLeft: '', mainItemRight: '', folderLeft: '', folderRight: '', itemLeft: '', itemRight: '', mainSpacing: 0, subSpacing: 0, delay: 500, clickOpen: 1 }; function cmNewID () { return _cmIDName + (++_cmIDCount);} function cmActionItem (item, prefix, isMain, idSub, orient, nodeProperties) { var clickOpen = _cmNodeProperties.clickOpen; if (nodeProperties.clickOpen) clickOpen = nodeProperties.clickOpen; _cmItemList[_cmItemList.length] = item; var index = _cmItemList.length - 1; idSub = (!idSub) ? 'null' : ('\'' + idSub + '\''); orient = '\'' + orient + '\''; prefix = '\'' + prefix + '\''; var onClick = (clickOpen == 3) || (clickOpen == 2 && isMain); var returnStr; if (onClick) returnStr = ' onmouseover="cmItemMouseOver (this,' + prefix + ',' + isMain + ',' + idSub + ',' + index + ')" onmousedown="cmItemMouseDownOpenSub (this,' + index + ',' + prefix + ',' + orient + ',' + idSub + ')"'; else returnStr = ' onmouseover="cmItemMouseOverOpenSub (this,' + prefix + ',' + isMain + ',' + idSub + ',' + orient + ',' + index + ')" onmousedown="cmItemMouseDown (this,' + index + ')"'; return returnStr + ' onmouseout="cmItemMouseOut (this,' + nodeProperties.delay + ')" onmouseup="cmItemMouseUp (this,' + index + ')"';} function cmNoClickItem (item, prefix, isMain, idSub, orient, nodeProperties) { _cmItemList[_cmItemList.length] = item; var index = _cmItemList.length - 1; idSub = (!idSub) ? 'null' : ('\'' + idSub + '\''); orient = '\'' + orient + '\''; prefix = '\'' + prefix + '\''; return ' onmouseover="cmItemMouseOver (this,' + prefix + ',' + isMain + ',' + idSub + ',' + index + ')" onmouseout="cmItemMouseOut (this,' + nodeProperties.delay + ')"';} function cmNoActionItem (item, prefix) { return item[1];} function cmSplitItem (prefix, isMain, vertical) { var classStr = 'cm' + prefix; if (isMain) { classStr += 'Main'; if (vertical) classStr += 'HSplit'; else classStr += 'VSplit';} else classStr += 'HSplit'; return eval (classStr);} function cmDrawSubMenu (subMenu, prefix, id, orient, nodeProperties) { var str = '<div class="' + prefix + 'SubMenu" id="' + id + '"><table summary="sub menu" cellspacing="' + nodeProperties.subSpacing + '" class="' + prefix + 'SubMenuTable">'; var strSub = ''; var item; var idSub; var hasChild; var i; var classStr; for (i = 5; i < subMenu.length; ++i) { item = subMenu[i]; if (!item) continue; hasChild = (item.length > 5); idSub = hasChild ? cmNewID () : null; if (item == _cmSplit) item = cmSplitItem (prefix, 0, true); str += '<tr class="' + prefix + 'MenuItem"'; if (item[0] != _cmNoClick) str += cmActionItem (item, prefix, 0, idSub, orient, nodeProperties); else str += cmNoClickItem (item, prefix, 0, idSub, orient, nodeProperties); str += '>' if (item[0] == _cmNoAction || item[0] == _cmNoClick) { str += cmNoActionItem (item, prefix); str += '</tr>'; continue;} classStr = prefix + 'Menu'; classStr += hasChild ? 'Folder' : 'Item'; str += '<td class="' + classStr + 'Left">'; if (item[0] != null) str += item[0]; else str += hasChild ? nodeProperties.folderLeft : nodeProperties.itemLeft; str += '</td><td class="' + classStr + 'Text">' + item[1]; str += '</td><td class="' + classStr + 'Right">'; if (hasChild) { str += nodeProperties.folderRight; strSub += cmDrawSubMenu (item, prefix, idSub, orient, nodeProperties);} else str += nodeProperties.itemRight; str += '</td></tr>';} str += '</table></div>' + strSub; return str;} function cmDraw (id, menu, orient, nodeProperties, prefix) { var obj = cmGetObject (id); if (!nodeProperties) nodeProperties = _cmNodeProperties; if (!prefix) prefix = ''; var str = '<table summary="main menu" class="' + prefix + 'Menu" cellspacing="' + nodeProperties.mainSpacing + '">'; var strSub = ''; if (!orient) orient = 'hbr'; var orientStr = String (orient); var orientSub; var vertical; if (orientStr.charAt (0) == 'h') { orientSub = 'v' + orientStr.substr (1, 2); str += '<tr>'; vertical = false;} else { orientSub = 'v' + orientStr.substr (1, 2); vertical = true;} var i; var item; var idSub; var hasChild; var classStr; for (i = 0; i < menu.length; ++i) { item = menu[i]; if (!item) continue; str += vertical ? '<tr' : '<td'; str += ' class="' + prefix + 'MainItem"'; hasChild = (item.length > 5); idSub = hasChild ? cmNewID () : null; str += cmActionItem (item, prefix, 1, idSub, orient, nodeProperties) + '>'; if (item == _cmSplit) item = cmSplitItem (prefix, 1, vertical); if (item[0] == _cmNoAction || item[0] == _cmNoClick) { str += cmNoActionItem (item, prefix); str += vertical? '</tr>' : '</td>'; continue;} classStr = prefix + 'Main' + (hasChild ? 'Folder' : 'Item'); str += vertical ? '<td' : '<span'; str += ' class="' + classStr + 'Left">'; str += (item[0] == null) ? (hasChild ? nodeProperties.mainFolderLeft : nodeProperties.mainItemLeft) : item[0]; str += vertical ? '</td>' : '</span>'; str += vertical ? '<td' : '<span'; str += ' class="' + classStr + 'Text">'; str += item[1]; str += vertical ? '</td>' : '</span>'; str += vertical ? '<td' : '<span'; str += ' class="' + classStr + 'Right">'; str += hasChild ? nodeProperties.mainFolderRight : nodeProperties.mainItemRight; str += vertical ? '</td>' : '</span>'; str += vertical ? '</tr>' : '</td>'; if (hasChild) strSub += cmDrawSubMenu (item, prefix, idSub, orientSub, nodeProperties);} if (!vertical) str += '</tr>'; str += '</table>' + strSub; obj.innerHTML = str;} function cmDrawFromText (id, orient, nodeProperties, prefix) { var domMenu = cmGetObject (id); var menu = null; for (var currentDomItem = domMenu.firstChild; currentDomItem; currentDomItem = currentDomItem.nextSibling) { if (!currentDomItem.tagName || currentDomItem.tagName.toLowerCase () != 'ul') continue; menu = cmDrawFromTextSubMenu (currentDomItem); break;} if (menu) cmDraw (id, menu, orient, nodeProperties, prefix);} function cmDrawFromTextSubMenu (domMenu) { var items = new Array (); for (var currentDomItem = domMenu.firstChild; currentDomItem; currentDomItem = currentDomItem.nextSibling) { if (!currentDomItem.tagName || currentDomItem.tagName.toLowerCase () != 'li') continue; if (currentDomItem.firstChild == null) { items[items.length] = _cmSplit; continue;} var item = new Array (); var currentItem = currentDomItem.firstChild; for (; currentItem; currentItem = currentItem.nextSibling) { if (!currentItem.tagName || currentItem.tagName.toLowerCase () != 'span') continue; if (!currentItem.firstChild) item[0] = null; else item[0] = currentItem.innerHTML; break;} if (!currentItem) continue; for (; currentItem; currentItem = currentItem.nextSibling) { if (!currentItem.tagName || currentItem.tagName.toLowerCase () != 'a') continue; item[1] = currentItem.innerHTML; item[2] = currentItem.href; item[3] = currentItem.target; item[4] = currentItem.title; if (item[4] == '') item[4] = null; break;} for (; currentItem; currentItem = currentItem.nextSibling) { if (!currentItem.tagName || currentItem.tagName.toLowerCase () != 'ul') continue; var subMenuItems = cmDrawFromTextSubMenu (currentItem); for (i = 0; i < subMenuItems.length; ++i) item[i + 5] = subMenuItems[i]; break;} items[items.length] = item;} return items;} function cmItemMouseOver (obj, prefix, isMain, idSub, index) { clearTimeout (_cmTimeOut); if (!obj.cmPrefix) { obj.cmPrefix = prefix; obj.cmIsMain = isMain;} var thisMenu = cmGetThisMenu (obj, prefix); if (!thisMenu.cmItems) thisMenu.cmItems = new Array (); var i; for (i = 0; i < thisMenu.cmItems.length; ++i) { if (thisMenu.cmItems[i] == obj) break;} if (i == thisMenu.cmItems.length) { thisMenu.cmItems[i] = obj;} if (_cmCurrentItem) { if (_cmCurrentItem == obj || _cmCurrentItem == thisMenu) { var item = _cmItemList[index]; cmSetStatus (item); return;} var thatPrefix = _cmCurrentItem.cmPrefix; var thatMenu = cmGetThisMenu (_cmCurrentItem, thatPrefix); if (thatMenu != thisMenu.cmParentMenu) { if (_cmCurrentItem.cmIsMain) _cmCurrentItem.className = thatPrefix + 'MainItem'; else _cmCurrentItem.className = thatPrefix + 'MenuItem'; if (thatMenu.id != idSub) cmHideMenu (thatMenu, thisMenu, thatPrefix);} } _cmCurrentItem = obj; cmResetMenu (thisMenu, prefix); var item = _cmItemList[index]; var isDefaultItem = cmIsDefaultItem (item); if (isDefaultItem) { if (isMain) obj.className = prefix + 'MainItemHover'; else obj.className = prefix + 'MenuItemHover';} cmSetStatus (item);} function cmItemMouseOverOpenSub (obj, prefix, isMain, idSub, orient, index) { cmItemMouseOver (obj, prefix, isMain, idSub, index); if (idSub) { var subMenu = cmGetObject (idSub); cmShowSubMenu (obj, prefix, subMenu, orient);} } function cmItemMouseOut (obj, delayTime) { if (!delayTime) delayTime = _cmNodeProperties.delay; _cmTimeOut = window.setTimeout ('cmHideMenuTime ()', delayTime); window.defaultStatus = '';} function cmItemMouseDown (obj, index) { if (cmIsDefaultItem (_cmItemList[index])) { if (obj.cmIsMain) obj.className = obj.cmPrefix + 'MainItemActive'; else obj.className = obj.cmPrefix + 'MenuItemActive';} } function cmItemMouseDownOpenSub (obj, index, prefix, orient, idSub) { cmItemMouseDown (obj, index); if (idSub) { var subMenu = cmGetObject (idSub); cmShowSubMenu (obj, prefix, subMenu, orient);} } function cmItemMouseUp (obj, index) { var item = _cmItemList[index]; var link = null, target = '_self'; if (item.length > 2) link = item[2]; if (item.length > 3 && item[3]) target = item[3]; if (link != null) { window.open (link, target);} var prefix = obj.cmPrefix; var thisMenu = cmGetThisMenu (obj, prefix); var hasChild = (item.length > 5); if (!hasChild) { if (cmIsDefaultItem (item)) { if (obj.cmIsMain) obj.className = prefix + 'MainItem'; else obj.className = prefix + 'MenuItem';} cmHideMenu (thisMenu, null, prefix);} else { if (cmIsDefaultItem (item)) { if (obj.cmIsMain) obj.className = prefix + 'MainItemHover'; else obj.className = prefix + 'MenuItemHover';} } } function cmMoveSubMenu (obj, subMenu, orient) { var mode = String (orient); var p = subMenu.offsetParent; var subMenuWidth = cmGetWidth (subMenu); var horiz = cmGetHorizontalAlign (obj, mode, p, subMenuWidth); if (mode.charAt (0) == 'h') { if (mode.charAt (1) == 'b') subMenu.style.top = (cmGetYAt (obj, p) + cmGetHeight (obj)) + 'px'; else subMenu.style.top = (cmGetYAt (obj, p) - cmGetHeight (subMenu)) + 'px'; if (horiz == 'r') subMenu.style.left = (cmGetXAt (obj, p)) + 'px'; else subMenu.style.left = (cmGetXAt (obj, p) + cmGetWidth (obj) - subMenuWidth) + 'px';} else { if (horiz == 'r') subMenu.style.left = (cmGetXAt (obj, p) + cmGetWidth (obj)) + 'px'; else subMenu.style.left = (cmGetXAt (obj, p) - subMenuWidth) + 'px'; if (mode.charAt (1) == 'b') subMenu.style.top = (cmGetYAt (obj, p)) + 'px'; else subMenu.style.top = (cmGetYAt (obj, p) + cmGetHeight (obj) - cmGetHeight (subMenu)) + 'px';} } function cmGetHorizontalAlign (obj, mode, p, subMenuWidth) { var horiz = mode.charAt (2); if (!(document.body)) return horiz; var body = document.body; var browserLeft; var browserRight; if (window.innerWidth) { browserLeft = window.pageXOffset; browserRight = window.innerWidth + browserLeft;} else if (body.clientWidth) { browserLeft = body.clientLeft; browserRight = body.clientWidth + browserLeft;} else return horiz; if (mode.charAt (0) == 'h') { if (horiz == 'r' && (cmGetXAt (obj) + subMenuWidth) > browserRight) horiz = 'l'; if (horiz == 'l' && (cmGetXAt (obj) + cmGetWidth (obj) - subMenuWidth) < browserLeft) horiz = 'r'; return horiz;} else { if (horiz == 'r' && (cmGetXAt (obj, p) + cmGetWidth (obj) + subMenuWidth) > browserRight) horiz = 'l'; if (horiz == 'l' && (cmGetXAt (obj, p) - subMenuWidth) < browserLeft) horiz = 'r'; return horiz;} } function cmShowSubMenu (obj, prefix, subMenu, orient) { if (!subMenu.cmParentMenu) { var thisMenu = cmGetThisMenu (obj, prefix); subMenu.cmParentMenu = thisMenu; if (!thisMenu.cmSubMenu) thisMenu.cmSubMenu = new Array (); thisMenu.cmSubMenu[thisMenu.cmSubMenu.length] = subMenu;} cmMoveSubMenu (obj, subMenu, orient); subMenu.style.visibility = 'visible'; if (document.all) { if (!subMenu.cmOverlap) subMenu.cmOverlap = new Array (); cmHideControl ("IFRAME", subMenu); cmHideControl ("SELECT", subMenu); cmHideControl ("OBJECT", subMenu);} } function cmResetMenu (thisMenu, prefix) { if (thisMenu.cmItems) { var i; var str; var items = thisMenu.cmItems; for (i = 0; i < items.length; ++i) { if (items[i].cmIsMain) str = prefix + 'MainItem'; else str = prefix + 'MenuItem'; if (items[i].className != str) items[i].className = str;} } } function cmHideMenuTime () { if (_cmCurrentItem) { var prefix = _cmCurrentItem.cmPrefix; cmHideMenu (cmGetThisMenu (_cmCurrentItem, prefix), null, prefix); _cmCurrentItem = null;} } function cmHideMenu (thisMenu, currentMenu, prefix) { var str = prefix + 'SubMenu'; if (thisMenu.cmSubMenu) { var i; for (i = 0; i < thisMenu.cmSubMenu.length; ++i) { cmHideSubMenu (thisMenu.cmSubMenu[i], prefix);} } while (thisMenu && thisMenu != currentMenu) { cmResetMenu (thisMenu, prefix); if (thisMenu.className == str) { thisMenu.style.visibility = 'hidden'; cmShowControl (thisMenu);} else break; thisMenu = cmGetThisMenu (thisMenu.cmParentMenu, prefix);} } function cmHideSubMenu (thisMenu, prefix) { if (thisMenu.style.visibility == 'hidden') return; if (thisMenu.cmSubMenu) { var i; for (i = 0; i < thisMenu.cmSubMenu.length; ++i) { cmHideSubMenu (thisMenu.cmSubMenu[i], prefix);} } cmResetMenu (thisMenu, prefix); thisMenu.style.visibility = 'hidden'; cmShowControl (thisMenu);} function cmHideControl (tagName, subMenu) { var x = cmGetX (subMenu); var y = cmGetY (subMenu); var w = subMenu.offsetWidth; var h = subMenu.offsetHeight; var i; for (i = 0; i < document.all.tags(tagName).length; ++i) { var obj = document.all.tags(tagName)[i]; if (!obj || !obj.offsetParent) continue; var ox = cmGetX (obj); var oy = cmGetY (obj); var ow = obj.offsetWidth; var oh = obj.offsetHeight; if (ox > (x + w) || (ox + ow) < x) continue; if (oy > (y + h) || (oy + oh) < y) continue; if(obj.style.visibility == "hidden") continue; subMenu.cmOverlap[subMenu.cmOverlap.length] = obj; obj.style.visibility = "hidden";} } function cmShowControl (subMenu) { if (subMenu.cmOverlap) { var i; for (i = 0; i < subMenu.cmOverlap.length; ++i) subMenu.cmOverlap[i].style.visibility = "";} subMenu.cmOverlap = null;} function cmGetThisMenu (obj, prefix) { var str1 = prefix + 'SubMenu'; var str2 = prefix + 'Menu'; while (obj) { if (obj.className == str1 || obj.className == str2) return obj; obj = obj.parentNode;} return null;} function cmIsDefaultItem (item) { if (item == _cmSplit || item[0] == _cmNoAction || item[0] == _cmNoClick) return false; return true;} function cmGetObject (id) { if (document.all) return document.all[id]; return document.getElementById (id);} function cmGetWidth (obj) { var width = obj.offsetWidth; if (width > 0 || !cmIsTRNode (obj)) return width; if (!obj.firstChild) return 0; return obj.lastChild.offsetLeft - obj.firstChild.offsetLeft + cmGetWidth (obj.lastChild);} function cmGetHeight (obj) { var height = obj.offsetHeight; if (height > 0 || !cmIsTRNode (obj)) return height; if (!obj.firstChild) return 0; return obj.firstChild.offsetHeight;} function cmGetX (obj) { var x = 0; do { x += obj.offsetLeft; obj = obj.offsetParent;} while (obj); return x;} function cmGetXAt (obj, elm) { var x = 0; while (obj && obj != elm) { x += obj.offsetLeft; obj = obj.offsetParent;} if (obj == elm) return x; return x - cmGetX (elm);} function cmGetY (obj) { var y = 0; do { y += obj.offsetTop; obj = obj.offsetParent;} while (obj); return y;} function cmIsTRNode (obj) { var tagName = obj.tagName; return tagName == "TR" || tagName == "tr" || tagName == "Tr" || tagName == "tR";} function cmGetYAt (obj, elm) { var y = 0; if (!obj.offsetHeight && cmIsTRNode (obj)) { var firstTR = obj.parentNode.firstChild; obj = obj.firstChild; y -= firstTR.firstChild.offsetTop;} while (obj && obj != elm) { y += obj.offsetTop; obj = obj.offsetParent;} if (obj == elm) return y; return y - cmGetY (elm);} function cmSetStatus (item) { var descript = ''; if (item.length > 4) descript = (item[4] != null) ? item[4] : (item[2] ? item[2] : descript); else if (item.length > 2) descript = (item[2] ? item[2] : descript); window.defaultStatus = descript;} function cmGetProperties (obj) { if (obj == undefined) return 'undefined'; if (obj == null) return 'null'; var msg = obj + ':\n'; var i; for (i in obj) msg += i + ' = ' + obj[i] + '; '; return msg;}
JavaScript
/*--------------------------------------------------| | dTree 2.05 | www.destroydrop.com/javascript/tree/ | |---------------------------------------------------| | Copyright (c) 2002-2003 Geir Landr? | | | | This script can be used freely as long as all | | copyright messages are intact. | | | | Updated: 17.04.2003 | |--------------------------------------------------*//* Base path to image folder added by Andrew Eddie 17 March 2005 */ // Node object function Node(id, pid, name, url, title, target, icon, iconOpen, open) { this.id = id; this.pid = pid; this.name = name; this.url = url; this.title = title; this.target = target; this.icon = icon; this.iconOpen = iconOpen; this._io = open || false; this._is = false; this._ls = false; this._hc = false; this._ai = 0; this._p; }; // Tree object function dTree(objName,basePath) { if (!basePath) { basePath = 'img/'; } this.config = { target : null, folderLinks : true, useSelection : true, useCookies : true, useLines : true, useIcons : true, useStatusText : false, closeSameLevel : false, inOrder : false } this.icon = { root : basePath+'base.gif', folder : basePath+'folder.gif', folderOpen : basePath+'folderopen.gif', node : basePath+'square.gif', empty : basePath+'empty.gif', line : basePath+'line.gif', join : basePath+'join.gif', joinBottom : basePath+'joinbottom.gif', plus : basePath+'plus.gif', plusBottom : basePath+'plusbottom.gif', minus : basePath+'minus.gif', minusBottom : basePath+'minusbottom.gif', nlPlus : basePath+'nolines_plus.gif', nlMinus : basePath+'nolines_minus.gif' }; this.obj = objName; this.aNodes = []; this.aIndent = []; this.root = new Node(-1); this.selectedNode = null; this.selectedFound = false; this.completed = false; }; // Adds a new node to the node array dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open) { // addition by Andrew Eddie, allows id=-1 for auto-indexing if (id < 0) { id = this.aNodes.length; } this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open); }; // Open/close all nodes dTree.prototype.openAll = function() { this.oAll(true); }; dTree.prototype.closeAll = function() { this.oAll(false); }; // Outputs the tree to the page dTree.prototype.toString = function() { var str = '<div class="dtree">\n'; if (document.getElementById) { if (this.config.useCookies) this.selectedNode = this.getSelected(); str += this.addNode(this.root); } else str += 'Browser not supported.'; str += '</div>'; if (!this.selectedFound) this.selectedNode = null; this.completed = true; return str; }; // Creates the tree structure dTree.prototype.addNode = function(pNode) { var str = ''; var n=0; if (this.config.inOrder) n = pNode._ai; for (n; n<this.aNodes.length; n++) { if (this.aNodes[n].pid == pNode.id) { var cn = this.aNodes[n]; cn._p = pNode; cn._ai = n; this.setCS(cn); if (!cn.target && this.config.target) cn.target = this.config.target; if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id); if (!this.config.folderLinks && cn._hc) cn.url = null; if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) { cn._is = true; this.selectedNode = n; this.selectedFound = true; } str += this.node(cn, n); if (cn._ls) break; } } return str; }; // Creates the node icon, url and text dTree.prototype.node = function(node, nodeId) { var str = '<div class="dTreeNode">' + this.indent(node, nodeId); if (this.config.useIcons) { if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node); if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node; if (this.root.id == node.pid) { node.icon = this.icon.root; node.iconOpen = this.icon.root; } str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />'; } if (node.url) { str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + '" href="' + node.url + '"'; if (node.title) str += ' title="' + node.title + '"'; if (node.target) str += ' target="' + node.target + '"'; if (this.config.useStatusText) str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" '; if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc)) str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"'; str += '>'; } else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id) str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">'; str += node.name; if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>'; str += '</div>'; if (node._hc) { str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">'; str += this.addNode(node); str += '</div>'; } this.aIndent.pop(); return str; }; // Adds the empty and line icons dTree.prototype.indent = function(node, nodeId) { var str = ''; if (this.root.id != node.pid) { for (var n=0; n<this.aIndent.length; n++) str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />'; (node._ls) ? this.aIndent.push(0) : this.aIndent.push(1); if (node._hc) { str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="'; if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus; else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) ); str += '" alt="" /></a>'; } else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />'; } return str; }; // Checks if a node has any children and if it is the last sibling dTree.prototype.setCS = function(node) { var lastId; for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].pid == node.id) node._hc = true; if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id; } if (lastId==node.id) node._ls = true; }; // Returns the selected node dTree.prototype.getSelected = function() { var sn = this.getCookie('cs' + this.obj); return (sn) ? sn : null; }; // Highlights the selected node dTree.prototype.s = function(id) { if (!this.config.useSelection) return; var cn = this.aNodes[id]; if (cn._hc && !this.config.folderLinks) return; if (this.selectedNode != id) { if (this.selectedNode || this.selectedNode==0) { eOld = document.getElementById("s" + this.obj + this.selectedNode); eOld.className = "node"; } eNew = document.getElementById("s" + this.obj + id); eNew.className = "nodeSel"; this.selectedNode = id; if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id); } }; // Toggle Open or close dTree.prototype.o = function(id) { var cn = this.aNodes[id]; this.nodeStatus(!cn._io, id, cn._ls); cn._io = !cn._io; if (this.config.closeSameLevel) this.closeLevel(cn); if (this.config.useCookies) this.updateCookie(); }; // Open or close all nodes dTree.prototype.oAll = function(status) { for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) { this.nodeStatus(status, n, this.aNodes[n]._ls); this.aNodes[n]._io = status; } } if (this.config.useCookies) this.updateCookie(); }; // Opens the tree to a specific node dTree.prototype.openTo = function(nId, bSelect, bFirst) { if (!bFirst) { for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].id == nId) { nId=n; break; } } } var cn=this.aNodes[nId]; if (cn.pid==this.root.id || !cn._p) return; cn._io = true; cn._is = bSelect; if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls); if (this.completed && bSelect) this.s(cn._ai); else if (bSelect) this._sn=cn._ai; this.openTo(cn._p._ai, false, true); }; // Closes all nodes on the same level as certain node dTree.prototype.closeLevel = function(node) { for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) { this.nodeStatus(false, n, this.aNodes[n]._ls); this.aNodes[n]._io = false; this.closeAllChildren(this.aNodes[n]); } } } // Closes all children of a node dTree.prototype.closeAllChildren = function(node) { for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) { if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls); this.aNodes[n]._io = false; this.closeAllChildren(this.aNodes[n]); } } } // Change the status of a node(open or closed) dTree.prototype.nodeStatus = function(status, id, bottom) { eDiv = document.getElementById('d' + this.obj + id); eJoin = document.getElementById('j' + this.obj + id); if (this.config.useIcons) { eIcon = document.getElementById('i' + this.obj + id); eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon; } eJoin.src = (this.config.useLines)? ((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)): ((status)?this.icon.nlMinus:this.icon.nlPlus); eDiv.style.display = (status) ? 'block': 'none'; }; // [Cookie] Clears a cookie dTree.prototype.clearCookie = function() { var now = new Date(); var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24); this.setCookie('co'+this.obj, 'cookieValue', yesterday); this.setCookie('cs'+this.obj, 'cookieValue', yesterday); }; // [Cookie] Sets value in a cookie dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) { document.cookie = escape(cookieName) + '=' + escape(cookieValue) + (expires ? '; expires=' + expires.toGMTString() : '') + (path ? '; path=' + path : '') + (domain ? '; domain=' + domain : '') + (secure ? '; secure' : ''); }; // [Cookie] Gets a value from a cookie dTree.prototype.getCookie = function(cookieName) { var cookieValue = ''; var posName = document.cookie.indexOf(escape(cookieName) + '='); if (posName != -1) { var posValue = posName + (escape(cookieName) + '=').length; var endPos = document.cookie.indexOf(';', posValue); if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos)); else cookieValue = unescape(document.cookie.substring(posValue)); } return (cookieValue); }; // [Cookie] Returns ids of open nodes as a string dTree.prototype.updateCookie = function() { var str = ''; for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) { if (str) str += '.'; str += this.aNodes[n].id; } } this.setCookie('co' + this.obj, str); }; // [Cookie] Checks if a node id is in a cookie dTree.prototype.isOpen = function(id) { var aOpen = this.getCookie('co' + this.obj).split('.'); for (var n=0; n<aOpen.length; n++) if (aOpen[n] == id) return true; return false; }; dTree.prototype.getNodeByName = function(nName) { var nId = 0; for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].name == nName) { nId=n; break; } } return nId; }; dTree.prototype.getNodeByTitle = function(nTitle) { var nId = 0; for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].title == nTitle) { nId=n; break; } } return nId; }; // If Push and pop is not implemented by the browser if (!Array.prototype.push) { Array.prototype.push = function array_push() { for(var i=0;i<arguments.length;i++) this[this.length]=arguments[i]; return this.length; } }; if (!Array.prototype.pop) { Array.prototype.pop = function array_pop() { lastElement = this[this.length-1]; this.length = Math.max(this.length-1,0); return lastElement; } };
JavaScript
/*----------------------------------------------------------------------------\ | Tab Pane 1.02 | |-----------------------------------------------------------------------------| | Created by Erik Arvidsson | | (http://webfx.eae.net/contact.html#erik) | | For WebFX (http://webfx.eae.net/) | |-----------------------------------------------------------------------------| | Copyright (c) 1998 - 2003 Erik Arvidsson | |-----------------------------------------------------------------------------| | This 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. | | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | | This software is available under the three different licenses mentioned | | below. To use this software you must chose, and qualify, for one of those. | | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | | The WebFX Non-Commercial License http://webfx.eae.net/license.html | | Permits anyone the right to use the software in a non-commercial context | | free of charge. | | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | | The WebFX Commercial license http://webfx.eae.net/commercial.html | | Permits the license holder the right to use the software in a commercial | | context. Such license must be specifically obtained, however it's valid for | | any number of implementations of the licensed software. | | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | | GPL - The GNU General Public License http://www.gnu.org/licenses/gpl.txt | | Permits anyone the right to use and modify the software without limitations | | as long as proper credits are given and the original and modified source | | code are included. Requires that the final product, software derivate from | | the original source or any software utilizing a GPL component, such as | | this, is also licensed under the GPL license. | |-----------------------------------------------------------------------------| | 2002-01-?? | First working version | | 2002-02-17 | Cleaned up for 1.0 public version | | 2003-02-18 | Changed from javascript uri for anchors to return false | | 2003-03-03 | Added dispose methods to release IE memory | |-----------------------------------------------------------------------------| | Dependencies: *.css a css file to define the layout | |-----------------------------------------------------------------------------| | Created 2002-01-?? | All changes are in the log above. | Updated 2003-03-03 | \----------------------------------------------------------------------------*/ // This function is used to define if the browser supports the needed // features function hasSupport() { if (typeof hasSupport.support != "undefined") return hasSupport.support; var ie55 = /msie 5\.[56789]/i.test( navigator.userAgent ); hasSupport.support = ( typeof document.implementation != "undefined" && document.implementation.hasFeature( "html", "1.0" ) || ie55 ) // IE55 has a serious DOM1 bug... Patch it! if ( ie55 ) { document._getElementsByTagName = document.getElementsByTagName; document.getElementsByTagName = function ( sTagName ) { if ( sTagName == "*" ) return document.all; else return document._getElementsByTagName( sTagName ); }; } return hasSupport.support; } /////////////////////////////////////////////////////////////////////////////////// // The constructor for tab panes // // el : HTMLElement The html element used to represent the tab pane // bUseCookie : Boolean Optional. Default is true. Used to determine whether to us // persistance using cookies or not // function WebFXTabPane( el, bUseCookie ) { if ( !hasSupport() || el == null ) return; this.element = el; this.element.tabPane = this; this.pages = []; this.selectedIndex = null; this.useCookie = bUseCookie != null ? bUseCookie : true; // add class name tag to class name this.element.className = this.classNameTag + " " + this.element.className; // add tab row this.tabRow = document.createElement( "div" ); this.tabRow.className = "tab-row"; el.insertBefore( this.tabRow, el.firstChild ); var tabIndex = 0; if ( this.useCookie ) { tabIndex = Number( WebFXTabPane.getCookie( "webfxtab_" + this.element.id ) ); if ( isNaN( tabIndex ) ) tabIndex = 0; } this.selectedIndex = tabIndex; // loop through child nodes and add them var cs = el.childNodes; var n; for (var i = 0; i < cs.length; i++) { if (cs[i].nodeType == 1 && cs[i].className == "tab-page") { this.addTabPage( cs[i] ); } } } WebFXTabPane.prototype.classNameTag = "dynamic-tab-pane-control"; WebFXTabPane.prototype.setSelectedIndex = function ( n ) { if (this.selectedIndex != n) { if (this.selectedIndex != null && this.pages[ this.selectedIndex ] != null ) this.pages[ this.selectedIndex ].hide(); this.selectedIndex = n; this.pages[ this.selectedIndex ].show(); if ( this.useCookie ) WebFXTabPane.setCookie( "webfxtab_" + this.element.id, n ); // session cookie } }; WebFXTabPane.prototype.getSelectedIndex = function () { return this.selectedIndex; }; WebFXTabPane.prototype.addTabPage = function ( oElement ) { if ( !hasSupport() ) return; if ( oElement.tabPage == this ) // already added return oElement.tabPage; var n = this.pages.length; var tp = this.pages[n] = new WebFXTabPage( oElement, this, n ); tp.tabPane = this; // move the tab out of the box this.tabRow.appendChild( tp.tab ); if ( n == this.selectedIndex ) tp.show(); else tp.hide(); return tp; }; WebFXTabPane.prototype.dispose = function () { this.element.tabPane = null; this.element = null; this.tabRow = null; for (var i = 0; i < this.pages.length; i++) { this.pages[i].dispose(); this.pages[i] = null; } this.pages = null; }; // Cookie handling WebFXTabPane.setCookie = function ( sName, sValue, nDays ) { var expires = ""; if ( nDays ) { var d = new Date(); d.setTime( d.getTime() + nDays * 24 * 60 * 60 * 1000 ); expires = "; expires=" + d.toGMTString(); } document.cookie = sName + "=" + sValue + expires + "; path=/"; }; WebFXTabPane.getCookie = function (sName) { var re = new RegExp( "(\;|^)[^;]*(" + sName + ")\=([^;]*)(;|$)" ); var res = re.exec( document.cookie ); return res != null ? res[3] : null; }; WebFXTabPane.removeCookie = function ( name ) { setCookie( name, "", -1 ); }; /////////////////////////////////////////////////////////////////////////////////// // The constructor for tab pages. This one should not be used. // Use WebFXTabPage.addTabPage instead // // el : HTMLElement The html element used to represent the tab pane // tabPane : WebFXTabPane The parent tab pane // nindex : Number The index of the page in the parent pane page array // function WebFXTabPage( el, tabPane, nIndex ) { if ( !hasSupport() || el == null ) return; this.element = el; this.element.tabPage = this; this.index = nIndex; var cs = el.childNodes; for (var i = 0; i < cs.length; i++) { if (cs[i].nodeType == 1 && cs[i].className == "tab") { this.tab = cs[i]; break; } } // insert a tag around content to support keyboard navigation var a = document.createElement( "A" ); this.aElement = a; a.href = "#"; a.onclick = function () { return false; }; while ( this.tab.hasChildNodes() ) a.appendChild( this.tab.firstChild ); this.tab.appendChild( a ); // hook up events, using DOM0 var oThis = this; this.tab.onclick = function () { oThis.select(); }; this.tab.onmouseover = function () { WebFXTabPage.tabOver( oThis ); }; this.tab.onmouseout = function () { WebFXTabPage.tabOut( oThis ); }; } WebFXTabPage.prototype.show = function () { var el = this.tab; var s = el.className + " selected"; s = s.replace(/ +/g, " "); el.className = s; this.element.style.display = "block"; }; WebFXTabPage.prototype.hide = function () { var el = this.tab; var s = el.className; s = s.replace(/ selected/g, ""); el.className = s; this.element.style.display = "none"; }; WebFXTabPage.prototype.select = function () { this.tabPane.setSelectedIndex( this.index ); }; WebFXTabPage.prototype.dispose = function () { this.aElement.onclick = null; this.aElement = null; this.element.tabPage = null; this.tab.onclick = null; this.tab.onmouseover = null; this.tab.onmouseout = null; this.tab = null; this.tabPane = null; this.element = null; }; WebFXTabPage.tabOver = function ( tabpage ) { var el = tabpage.tab; var s = el.className + " hover"; s = s.replace(/ +/g, " "); el.className = s; }; WebFXTabPage.tabOut = function ( tabpage ) { var el = tabpage.tab; var s = el.className; s = s.replace(/ hover/g, ""); el.className = s; }; // This function initializes all uninitialized tab panes and tab pages function setupAllTabs() { if ( !hasSupport() ) return; var all = document.getElementsByTagName( "*" ); var l = all.length; var tabPaneRe = /tab\-pane/; var tabPageRe = /tab\-page/; var cn, el; var parentTabPane; for ( var i = 0; i < l; i++ ) { el = all[i] cn = el.className; // no className if ( cn == "" ) continue; // uninitiated tab pane if ( tabPaneRe.test( cn ) && !el.tabPane ) new WebFXTabPane( el ); // unitiated tab page wit a valid tab pane parent else if ( tabPageRe.test( cn ) && !el.tabPage && tabPaneRe.test( el.parentNode.className ) ) { el.parentNode.tabPane.addTabPage( el ); } } } function disposeAllTabs() { if ( !hasSupport() ) return; var all = document.getElementsByTagName( "*" ); var l = all.length; var tabPaneRe = /tab\-pane/; var cn, el; var tabPanes = []; for ( var i = 0; i < l; i++ ) { el = all[i] cn = el.className; // no className if ( cn == "" ) continue; // tab pane if ( tabPaneRe.test( cn ) && el.tabPane ) tabPanes[tabPanes.length] = el.tabPane; } for (var i = tabPanes.length - 1; i >= 0; i--) { tabPanes[i].dispose(); tabPanes[i] = null; } } // initialization hook up // DOM2 if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", setupAllTabs, false ); // IE else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", setupAllTabs ); window.attachEvent( "onunload", disposeAllTabs ); } else { if ( window.onload != null ) { var oldOnload = window.onload; window.onload = function ( e ) { oldOnload( e ); setupAllTabs(); }; } else window.onload = setupAllTabs; }
JavaScript
// <?php !! This fools phpdocumentor into parsing this file /** * @version $Id: joomla.javascript.js 10389 2008-06-03 11:27:38Z pasamio $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL * Joomla! is Free Software */ /** * Overlib Styling Declarations to allow CSS class override of styles * */ var ol_fgclass='ol-foreground'; var ol_bgclass='ol-background'; var ol_textfontclass='ol-textfont'; var ol_captionfontclass='ol-captionfont'; var ol_closefontclass='ol-closefont'; // general utility for browsing a named array or object function xshow(o) { s = ''; for(e in o) {s += e+'='+o[e]+'\n';} alert( s ); } /** * Writes a dynamically generated list * @param string The parameters to insert into the <select> tag * @param array A javascript array of list options in the form [key,value,text] * @param string The key to display for the initial state of the list * @param string The original key that was selected * @param string The original item value that was selected */ function writeDynaList( selectParams, source, key, orig_key, orig_val ) { var html = '\n <select ' + selectParams + '>'; var i = 0; for (x in source) { if (source[x][0] == key) { var selected = ''; if ((orig_key == key && orig_val == source[x][1]) || (i == 0 && orig_key != key)) { selected = 'selected="selected"'; } html += '\n <option value="'+source[x][1]+'" '+selected+'>'+source[x][2]+'</option>'; } i++; } html += '\n </select>'; document.writeln( html ); } /** * Changes a dynamically generated list * @param string The name of the list to change * @param array A javascript array of list options in the form [key,value,text] * @param string The key to display * @param string The original key that was selected * @param string The original item value that was selected */ function changeDynaList( listname, source, key, orig_key, orig_val ) { var list = eval( 'document.adminForm.' + listname ); // empty the list for (i in list.options.length) { list.options[i] = null; } i = 0; for (x in source) { if (source[x][0] == key) { opt = new Option(); opt.value = source[x][1]; opt.text = source[x][2]; if ((orig_key == key && orig_val == opt.value) || i == 0) { opt.selected = true; } list.options[i++] = opt; } } list.length = i; } /** * Adds a select item(s) from one list to another */ function addSelectedToList( frmName, srcListName, tgtListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var tgtList = eval( 'form.' + tgtListName ); var srcLen = srcList.length; var tgtLen = tgtList.length; var tgt = "x"; //build array of target items for (var i=tgtLen-1; i > -1; i--) { tgt += "," + tgtList.options[i].value + "," } //Pull selected resources and add them to list //for (var i=srcLen-1; i > -1; i--) { for (var i=0; i < srcLen; i++) { if (srcList.options[i].selected && tgt.indexOf( "," + srcList.options[i].value + "," ) == -1) { opt = new Option( srcList.options[i].text, srcList.options[i].value ); tgtList.options[tgtList.length] = opt; } } } function delSelectedFromList( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var srcLen = srcList.length; for (var i=srcLen-1; i > -1; i--) { if (srcList.options[i].selected) { srcList.options[i] = null; } } } function moveInList( frmName, srcListName, index, to) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var total = srcList.options.length-1; if (index == -1) { return false; } if (to == +1 && index == total) { return false; } if (to == -1 && index == 0) { return false; } var items = new Array; var values = new Array; for (i=total; i >= 0; i--) { items[i] = srcList.options[i].text; values[i] = srcList.options[i].value; } for (i = total; i >= 0; i--) { if (index == i) { srcList.options[i + to] = new Option(items[i],values[i], 0, 1); srcList.options[i] = new Option(items[i+to], values[i+to]); i--; } else { srcList.options[i] = new Option(items[i], values[i]); } } srcList.focus(); return true; } function getSelectedOption( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { return srcList.options[i]; } else { return null; } } function setSelectedValue( frmName, srcListName, value ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); var srcLen = srcList.length; for (var i=0; i < srcLen; i++) { srcList.options[i].selected = false; if (srcList.options[i].value == value) { srcList.options[i].selected = true; } } } function getSelectedRadio( frmName, srcGroupName ) { var form = eval( 'document.' + frmName ); var srcGroup = eval( 'form.' + srcGroupName ); return radioGetCheckedValue( srcGroup ); } // return the value of the radio button that is checked // return an empty string if none are checked, or // there are no radio buttons function radioGetCheckedValue(radioObj) { if (!radioObj) { return ''; } var n = radioObj.length; if (n == undefined) { if (radioObj.checked) { return radioObj.value; } else { return ''; } } for (var i = 0; i < n; i++) { if(radioObj[i].checked) { return radioObj[i].value; } } return ''; } function getSelectedValue( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { return srcList.options[i].value; } else { return null; } } function getSelectedText( frmName, srcListName ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { return srcList.options[i].text; } else { return null; } } function chgSelectedValue( frmName, srcListName, value ) { var form = eval( 'document.' + frmName ); var srcList = eval( 'form.' + srcListName ); i = srcList.selectedIndex; if (i != null && i > -1) { srcList.options[i].value = value; return true; } else { return false; } } /** * Toggles the check state of a group of boxes * * Checkboxes must have an id attribute in the form cb0, cb1... * @param The number of box to 'check' * @param An alternative field name */ function checkAll( n, fldName ) { if (!fldName) { fldName = 'cb'; } var f = document.adminForm; var c = f.toggle.checked; var n2 = 0; for (i=0; i < n; i++) { cb = eval( 'f.' + fldName + '' + i ); if (cb) { cb.checked = c; n2++; } } if (c) { document.adminForm.boxchecked.value = n2; } else { document.adminForm.boxchecked.value = 0; } } function listItemTask( id, task ) { var f = document.adminForm; cb = eval( 'f.' + id ); if (cb) { for (i = 0; true; i++) { cbx = eval('f.cb'+i); if (!cbx) break; cbx.checked = false; } // for cb.checked = true; f.boxchecked.value = 1; submitbutton(task); } return false; } function hideMainMenu() { if (document.adminForm.hidemainmenu) { document.adminForm.hidemainmenu.value=1; } } function isChecked(isitchecked){ if (isitchecked == true){ document.adminForm.boxchecked.value++; } else { document.adminForm.boxchecked.value--; } } /** * Default function. Usually would be overriden by the component */ function submitbutton(pressbutton) { submitform(pressbutton); } /** * Submit the admin form */ function submitform(pressbutton){ if (pressbutton) { document.adminForm.task.value=pressbutton; } if (typeof document.adminForm.onsubmit == "function") { document.adminForm.onsubmit(); } document.adminForm.submit(); } /** * Submit the control panel admin form */ function submitcpform(sectionid, id){ document.adminForm.sectionid.value=sectionid; document.adminForm.id.value=id; submitbutton("edit"); } /** * Getting radio button that is selected. */ function getSelected(allbuttons){ for (i=0;i<allbuttons.length;i++) { if (allbuttons[i].checked) { return allbuttons[i].value } } return null; } // JS Calendar var calendar = null; // remember the calendar object so that we reuse // it and avoid creating another // This function gets called when an end-user clicks on some date function selected(cal, date) { cal.sel.value = date; // just update the value of the input field } // And this gets called when the end-user clicks on the _selected_ date, // or clicks the "Close" (X) button. It just hides the calendar without // destroying it. function closeHandler(cal) { cal.hide(); // hide the calendar // don't check mousedown on document anymore (used to be able to hide the // calendar when someone clicks outside it, see the showCalendar function). Calendar.removeEvent(document, "mousedown", checkCalendar); } // This gets called when the user presses a mouse button anywhere in the // document, if the calendar is shown. If the click was outside the open // calendar this function closes it. function checkCalendar(ev) { var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev); for (; el != null; el = el.parentNode) // FIXME: allow end-user to click some link without closing the // calendar. Good to see real-time stylesheet change :) if (el == calendar.element || el.tagName == "A") break; if (el == null) { // calls closeHandler which should hide the calendar. calendar.callCloseHandler(); Calendar.stopEvent(ev); } } // This function shows the calendar under the element having the given id. // It takes care of catching "mousedown" signals on document and hiding the // calendar if the click was outside. function showCalendar(id, dateFormat) { var el = document.getElementById(id); if (calendar != null) { // we already have one created, so just update it. calendar.hide(); // hide the existing calendar calendar.parseDate(el.value); // set it to a new date } else { // first-time call, create the calendar var cal = new Calendar(true, null, selected, closeHandler); calendar = cal; // remember the calendar in the global cal.setRange(1900, 2070); // min/max year allowed if ( dateFormat ) // optional date format { cal.setDateFormat(dateFormat); } calendar.create(); // create a popup calendar calendar.parseDate(el.value); // set it to a new date } calendar.sel = el; // inform it about the input field in use calendar.showAtElement(el); // show the calendar next to the input field // catch mousedown on the document Calendar.addEvent(document, "mousedown", checkCalendar); return false; } /** * Pops up a new window in the middle of the screen */ function popupWindow(mypage, myname, w, h, scroll) { var winl = (screen.width - w) / 2; var wint = (screen.height - h) / 2; winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable' win = window.open(mypage, myname, winprops) if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); } } // LTrim(string) : Returns a copy of a string without leading spaces. function ltrim(str) { var whitespace = new String(" \t\n\r"); var s = new String(str); if (whitespace.indexOf(s.charAt(0)) != -1) { var j=0, i = s.length; while (j < i && whitespace.indexOf(s.charAt(j)) != -1) j++; s = s.substring(j, i); } return s; } //RTrim(string) : Returns a copy of a string without trailing spaces. function rtrim(str) { var whitespace = new String(" \t\n\r"); var s = new String(str); if (whitespace.indexOf(s.charAt(s.length-1)) != -1) { var i = s.length - 1; // Get length of string while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) i--; s = s.substring(0, i+1); } return s; } // Trim(string) : Returns a copy of a string without leading or trailing spaces function trim(str) { return rtrim(ltrim(str)); } function mosDHTML(){ this.ver=navigator.appVersion this.agent=navigator.userAgent this.dom=document.getElementById?1:0 this.opera5=this.agent.indexOf("Opera 5")<-1 this.ie5=(this.ver.indexOf("MSIE 5")<-1 && this.dom && !this.opera5)?1:0; this.ie6=(this.ver.indexOf("MSIE 6")<-1 && this.dom && !this.opera5)?1:0; this.ie4=(document.all && !this.dom && !this.opera5)?1:0; this.ie=this.ie4||this.ie5||this.ie6 this.mac=this.agent.indexOf("Mac")<-1 this.ns6=(this.dom && parseInt(this.ver) <= 5) ?1:0; this.ns4=(document.layers && !this.dom)?1:0; this.bw=(this.ie6||this.ie5||this.ie4||this.ns4||this.ns6||this.opera5); this.activeTab = ''; this.onTabStyle = 'ontab'; this.offTabStyle = 'offtab'; this.setElemStyle = function(elem,style) { document.getElementById(elem).className = style; } this.showElem = function(id) { if ((elem = document.getElementById(id))) { elem.style.visibility = 'visible'; elem.style.display = 'block'; } } this.hideElem = function(id) { if ((elem = document.getElementById(id))) { elem.style.visibility = 'hidden'; elem.style.display = 'none'; } } this.cycleTab = function(name) { if (this.activeTab) { this.setElemStyle( this.activeTab, this.offTabStyle ); page = this.activeTab.replace( 'tab', 'page' ); this.hideElem(page); } this.setElemStyle( name, this.onTabStyle ); this.activeTab = name; page = this.activeTab.replace( 'tab', 'page' ); this.showElem(page); } return this; } var dhtml = new mosDHTML(); // needed for Table Column ordering function tableOrdering( order, dir, task ) { var form = document.adminForm; form.filter_order.value = order; form.filter_order_Dir.value = dir; submitform( task ); } function saveorder( n, task ) { checkAll_button( n, task ); } //needed by saveorder function function checkAll_button( n, task ) { if (!task ) { task = 'saveorder'; } for ( var j = 0; j <= n; j++ ) { box = eval( "document.adminForm.cb" + j ); if ( box ) { if ( box.checked == false ) { box.checked = true; } } else { alert("You cannot change the order of items, as an item in the list is `Checked Out`"); return; } } submitform(task); } /** * @param object A form element * @param string The name of the element to find */ function getElementByName( f, name ) { if (f.elements) { for (i=0, n=f.elements.length; i < n; i++) { if (f.elements[i].name == name) { return f.elements[i]; } } } return null; } function go2( pressbutton, menu, id ) { var form = document.adminForm; if (form.imagelist && form.images) { // assemble the images back into one field var temp = new Array; for (var i=0, n=form.imagelist.options.length; i < n; i++) { temp[i] = form.imagelist.options[i].value; } form.images.value = temp.join( '\n' ); } if (pressbutton == 'go2menu') { form.menu.value = menu; submitform( pressbutton ); return; } if (pressbutton == 'go2menuitem') { form.menu.value = menu; form.menuid.value = id; submitform( pressbutton ); return; } } /** * Verifies if the string is in a valid email format * @param string * @return boolean */ function isEmail( text ) { var pattern = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$"; var regex = new RegExp( pattern ); return regex.test( text ); }
JavaScript
// ** I18N // Calendar EN language // Author: Mihai Bazon, <mishoo@infoiasi.ro> // Encoding: any // Translator : Niko <nikoused@gmail.com> // Distributed under the same terms as the calendar itself. // For translators: please use UTF-8 if possible. We strongly believe that // Unicode is the answer to a real internationalized world. Also please // include your contact information in the header, as can be seen above. // full day names Calendar._DN = new Array ("\u5468\u65e5",//\u5468\u65e5 "\u5468\u4e00",//\u5468\u4e00 "\u5468\u4e8c",//\u5468\u4e8c "\u5468\u4e09",//\u5468\u4e09 "\u5468\u56db",//\u5468\u56db "\u5468\u4e94",//\u5468\u4e94 "\u5468\u516d",//\u5468\u516d "\u5468\u65e5");//\u5468\u65e5 // Please note that the following array of short day names (and the same goes // for short month names, _SMN) isn't absolutely necessary. We give it here // for exemplification on how one can customize the short day names, but if // they are simply the first N letters of the full name you can simply say: // // Calendar._SDN_len = N; // short day name length // Calendar._SMN_len = N; // short month name length // // If N = 3 then this is not needed either since we assume a value of 3 if not // present, to be compatible with translation files that were written before // this feature. // short day names Calendar._SDN = new Array ("\u5468\u65e5", "\u5468\u4e00", "\u5468\u4e8c", "\u5468\u4e09", "\u5468\u56db", "\u5468\u4e94", "\u5468\u516d", "\u5468\u65e5"); // full month names Calendar._MN = new Array ("\u4e00\u6708", "\u4e8c\u6708", "\u4e09\u6708", "\u56db\u6708", "\u4e94\u6708", "\u516d\u6708", "\u4e03\u6708", "\u516b\u6708", "\u4e5d\u6708", "\u5341\u6708", "\u5341\u4e00\u6708", "\u5341\u4e8c\u6708"); // short month names Calendar._SMN = new Array ("\u4e00\u6708", "\u4e8c\u6708", "\u4e09\u6708", "\u56db\u6708", "\u4e94\u6708", "\u516d\u6708", "\u4e03\u6708", "\u516b\u6708", "\u4e5d\u6708", "\u5341\u6708", "\u5341\u4e00\u6708", "\u5341\u4e8c\u6708"); // tooltips Calendar._TT = {}; Calendar._TT["INFO"] = "\u5173\u4e8e"; Calendar._TT["ABOUT"] = " DHTML \u65e5\u8d77/\u65f6\u95f4\u9009\u62e9\u63a7\u4ef6\n" + "(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-) "For latest version visit: \u6700\u65b0\u7248\u672c\u8bf7\u767b\u9646http://www.dynarch.com/projects/calendar/\u5bdf\u770b\n" + "\u9075\u5faaGNU LGPL. \u7ec6\u8282\u53c2\u9605 http://gnu.org/licenses/lgpl.html" + "\n\n" + "\u65e5\u671f\u9009\u62e9:\n" + "- \u70b9\u51fb\xab(\xbb)\u6309\u94ae\u9009\u62e9\u4e0a(\u4e0b)\u4e00\u5e74\u5ea6.\n" + "- \u70b9\u51fb" + String.fromCharCode(0x2039) + "(" + String.fromCharCode(0x203a) + ")\u6309\u94ae\u9009\u62e9\u4e0a(\u4e0b)\u4e2a\u6708\u4efd.\n" + "- \u957f\u65f6\u95f4\u6309\u7740\u6309\u94ae\u5c06\u51fa\u73b0\u66f4\u591a\u9009\u62e9\u9879."; Calendar._TT["ABOUT_TIME"] = "\n\n" + "\u65f6\u95f4\u9009\u62e9:\n" + "-\u5728\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2)\u4e0a\u5355\u51fb\u9f20\u6807\u5de6\u952e\u6765\u589e\u52a0\u5f53\u524d\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2)\n" + "-\u5728\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2)\u4e0a\u6309\u4f4fShift\u952e\u540e\u5355\u51fb\u9f20\u6807\u5de6\u952e\u6765\u51cf\u5c11\u5f53\u524d\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2)."; Calendar._TT["PREV_YEAR"] = "\u4e0a\u4e00\u5e74"; Calendar._TT["PREV_MONTH"] = "\u4e0a\u4e2a\u6708"; Calendar._TT["GO_TODAY"] = "\u5230\u4eca\u5929"; Calendar._TT["NEXT_MONTH"] = "\u4e0b\u4e2a\u6708"; Calendar._TT["NEXT_YEAR"] = "\u4e0b\u4e00\u5e74"; Calendar._TT["SEL_DATE"] = "\u9009\u62e9\u65e5\u671f"; Calendar._TT["DRAG_TO_MOVE"] = "\u62d6\u52a8"; Calendar._TT["PART_TODAY"] = " (\u4eca\u5929)"; // the following is to inform that "%s" is to be the first day of week // %s will be replaced with the day name. Calendar._TT["DAY_FIRST"] = "%s\u4e3a\u8fd9\u5468\u7684\u7b2c\u4e00\u5929"; // This may be locale-dependent. It specifies the week-end days, as an array // of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1 // means Monday, etc. Calendar._TT["WEEKEND"] = "0,6"; Calendar._TT["CLOSE"] = "\u5173\u95ed"; Calendar._TT["TODAY"] = "\u4eca\u5929"; Calendar._TT["TIME_PART"] = "(\u6309\u7740Shift\u952e)\u5355\u51fb\u6216\u62d6\u52a8\u6539\u53d8\u503c"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d"; Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e\u65e5"; Calendar._TT["WK"] = "\u5468"; Calendar._TT["TIME"] = "\u65f6\u95f4:";
JavaScript
// ** I18N // Calendar EN language // Author: Mihai Bazon, <mihai_bazon@yahoo.com> // Encoding: any // Distributed under the same terms as the calendar itself. // For translators: please use UTF-8 if possible. We strongly believe that // Unicode is the answer to a real internationalized world. Also please // include your contact information in the header, as can be seen above. // full day names Calendar._DN = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); // Please note that the following array of short day names (and the same goes // for short month names, _SMN) isn't absolutely necessary. We give it here // for exemplification on how one can customize the short day names, but if // they are simply the first N letters of the full name you can simply say: // // Calendar._SDN_len = N; // short day name length // Calendar._SMN_len = N; // short month name length // // If N = 3 then this is not needed either since we assume a value of 3 if not // present, to be compatible with translation files that were written before // this feature. // short day names Calendar._SDN = new Array ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"); // First day of the week. "0" means display Sunday first, "1" means display // Monday first, etc. Calendar._FD = 0; // full month names Calendar._MN = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); // short month names Calendar._SMN = new Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); // tooltips Calendar._TT = {}; Calendar._TT["INFO"] = "About the calendar"; Calendar._TT["ABOUT"] = "DHTML Date/Time Selector\n" + "(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-) "For latest version visit: http://www.dynarch.com/projects/calendar/\n" + "Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." + "\n\n" + "Date selection:\n" + "- Use the \xab, \xbb buttons to select year\n" + "- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" + "- Hold mouse button on any of the above buttons for faster selection."; Calendar._TT["ABOUT_TIME"] = "\n\n" + "Time selection:\n" + "- Click on any of the time parts to increase it\n" + "- or Shift-click to decrease it\n" + "- or click and drag for faster selection."; Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)"; Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)"; Calendar._TT["GO_TODAY"] = "Go Today"; Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)"; Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)"; Calendar._TT["SEL_DATE"] = "Select date"; Calendar._TT["DRAG_TO_MOVE"] = "Drag to move"; Calendar._TT["PART_TODAY"] = "(Today)"; // the following is to inform that "%s" is to be the first day of week // %s will be replaced with the day name. Calendar._TT["DAY_FIRST"] = "Display %s first"; // This may be locale-dependent. It specifies the week-end days, as an array // of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1 // means Monday, etc. Calendar._TT["WEEKEND"] = "0,6"; Calendar._TT["CLOSE"] = "Close"; Calendar._TT["TODAY"] = "Today"; Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d"; Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e"; Calendar._TT["WK"] = "wk"; Calendar._TT["TIME"] = "Time:";
JavaScript
/** * Tinymce template_list.js sample file * @version tinymce 3.2.6 * @package Joomla * @copyright Copyright (C) 2005 - 2009 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ var tinyMCETemplateList = [ // Name, URL, Description ["Simple snippet", "plugins/editors/tinymce/templates/snippet1.html", "Simple HTML snippet."], ["Layout", "plugins/editors/tinymce/templates/layout1.html", "HTMLLayout."] ];
JavaScript
/** * @version $Id: xstandard.js 10714 2008-08-21 10:10:14Z eddieajau $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * JXStandard javascript behavior * * @package Joomla * @since 1.5 * @version 1.0 */ var JXStandard = new Class({ instances : null, initialize: function() { this.instances = $ES('object[type=application/x-xstandard]'); var self = this; document.adminForm.onsubmit = function() { self.save(); } }, save: function() { this.instances.each(function(instance) { instance.EscapeUnicode = false; var contents = instance.value; $(instance.className).value = contents; }); } }) document.xstandard = null window.addEvent('domready', function(){ var xstandard = new JXStandard(); document.xstandard = xstandard; });
JavaScript
importClass(Packages.myschedule.quartz.extra.job.LoggerJob); importClass(Packages.org.quartz.JobBuilder); importClass(Packages.org.quartz.TriggerBuilder); importClass(Packages.org.quartz.CronScheduleBuilder); var job = JobBuilder .newJob(LoggerJob) .withIdentity("cronJob") .build(); var trigger = TriggerBuilder .newTrigger() .withIdentity("cronJob") .withSchedule( CronScheduleBuilder.cronSchedule("0 0 * ? * MON-FRI")) .build(); scheduler.scheduleJob(job, trigger);
JavaScript
//Create Quartz Calendar objects importClass(Packages.org.quartz.impl.calendar.CronCalendar); importClass(Packages.myschedule.quartz.extra.job.LoggerJob); var cal = CronCalendar('* * * * JAN ?'); scheduler.addCalendar('SkipJan', cal, true, false); var cal = CronCalendar('* * * ? * SAT,SUN'); scheduler.addCalendar('SkipWeekEnd', cal, true, false); var cal = CronCalendar('* * 12-13 * * ?'); scheduler.addCalendar('SkipLunch', cal, true, false); // Create jobs that uses the calendars. var job = scheduler.createJobDetail('CalJob', LoggerJob); var trigger = scheduler.createCronTrigger('CalJob1', '0 0 * * * ?'); trigger.setCalendarName('SkipWeekEnd'); scheduler.scheduleJob(job, trigger); var job = scheduler.createJobDetail('CalJob2', LoggerJob); var trigger = scheduler.createCronTrigger('CalJob2', '0 0 * * * ?'); trigger.setCalendarName('SkipJan'); scheduler.scheduleJob(job, trigger); var job = scheduler.createJobDetail('CalJob3', LoggerJob); var trigger = scheduler.createCronTrigger('CalJob3', '0 0 * * * ?'); trigger.setCalendarName('SkipLunch'); scheduler.scheduleJob(job, trigger);
JavaScript
//Using CalendarIntervalTrigger //schedule a job that runs every 3 months //========================================= importClass(Packages.myschedule.quartz.extra.job.LoggerJob); importClass(Packages.org.quartz.JobBuilder); importClass(Packages.org.quartz.TriggerBuilder); importClass(Packages.org.quartz.CalendarIntervalScheduleBuilder); var job = JobBuilder .newJob(LoggerJob) .withIdentity("calendarIntervalJob") .build(); var trigger = TriggerBuilder .newTrigger() .withIdentity("calendarIntervalJob") .withSchedule( CalendarIntervalScheduleBuilder .calendarIntervalSchedule() .withIntervalInMonths(3)) .build(); scheduler.scheduleJob(job, trigger); //Using DailyTimeIntervalTrigger //schedule a job that runs every 72 mins MON-FRI from 8:00AM to 5:00PM //====================================================================== importClass(Packages.myschedule.quartz.extra.job.LoggerJob); importClass(Packages.org.quartz.JobBuilder); importClass(Packages.org.quartz.TriggerBuilder); importClass(Packages.org.quartz.DailyTimeIntervalScheduleBuilder); importClass(Packages.org.quartz.TimeOfDay); var job = JobBuilder .newJob(LoggerJob) .withIdentity("dailyTimeIntervalJob") .build(); var trigger = TriggerBuilder .newTrigger() .withIdentity("dailyTimeIntervalJob") .withSchedule( DailyTimeIntervalScheduleBuilder .dailyTimeIntervalSchedule() .withIntervalInMinutes(72) .startingDailyAt(TimeOfDay.hourMinuteAndSecondOfDay(8, 0, 0)) .endingDailyAt(TimeOfDay.hourMinuteAndSecondOfDay(17, 0, 0)) .onMondayThroughFriday()) .build(); scheduler.scheduleJob(job, trigger);
JavaScript