1
/* ***** BEGIN LICENSE BLOCK *****
2
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
4
* The contents of this file are subject to the Mozilla Public License Version
5
* 1.1 (the "License"); you may not use this file except in compliance with
6
* the License. You may obtain a copy of the License at
7
* http://www.mozilla.org/MPL/
9
* Software distributed under the License is distributed on an "AS IS" basis,
10
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11
* for the specific language governing rights and limitations under the
14
* The Original Code is Mozilla Communicator client code.
16
* The Initial Developer of the Original Code is
17
* Netscape Communications Corporation.
18
* Portions created by the Initial Developer are Copyright (C) 1998
19
* the Initial Developer. All Rights Reserved.
24
* Daniel Glazman (glazman@disruptive-innovations.com), on behalf of Linspire Inc.
26
* Alternatively, the contents of this file may be used under the terms of
27
* either the GNU General Public License Version 2 or later (the "GPL"), or
28
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29
* in which case the provisions of the GPL or the LGPL are applicable instead
30
* of those above. If you wish to allow use of your version of this file only
31
* under the terms of either the GPL or the LGPL, and not to allow others to
32
* use your version of this file under the terms of the NPL, indicate your
33
* decision by deleting the provisions above and replace them with the notice
34
* and other provisions required by the GPL or the LGPL. If you do not delete
35
* the provisions above, a recipient may use your version of this file under
36
* the terms of any one of the NPL, the GPL or the LGPL.
38
* ***** END LICENSE BLOCK ***** */
40
/**** NAMESPACES ****/
41
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
42
const NVU_NS = "http://disruptive-innovations.com/zoo/nvu";
44
// Each editor window must include this file
45
// Variables shared by all dialogs:
47
// Object to attach commonly-used widgets (all dialogs should use this)
50
// Bummer! Can't get at enums from nsIDocumentEncoder.h
51
// http://lxr.mozilla.org/seamonkey/source/content/base/public/nsIDocumentEncoder.h#111
56
var gFilePickerDirectory;
63
const kWebComposerWindowID = "editorWindow";
64
const kMailComposerWindowID = "msgcomposeWindow";
67
/************* Message dialogs ***************/
69
function AlertWithTitle(title, message, parentWindow)
72
parentWindow = window;
74
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService();
75
promptService = promptService.QueryInterface(Components.interfaces.nsIPromptService);
80
title = GetString("Alert");
82
// "window" is the calling dialog window
83
promptService.alert(parentWindow, title, message);
87
// Optional: Caller may supply text to substitue for "Ok" and/or "Cancel"
88
function ConfirmWithTitle(title, message, okButtonText, cancelButtonText)
90
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService();
91
promptService = promptService.QueryInterface(Components.interfaces.nsIPromptService);
95
var okFlag = okButtonText ? promptService.BUTTON_TITLE_IS_STRING : promptService.BUTTON_TITLE_OK;
96
var cancelFlag = cancelButtonText ? promptService.BUTTON_TITLE_IS_STRING : promptService.BUTTON_TITLE_CANCEL;
98
return promptService.confirmEx(window, title, message,
99
(okFlag * promptService.BUTTON_POS_0) +
100
(cancelFlag * promptService.BUTTON_POS_1),
101
okButtonText, cancelButtonText, null, null, {value:0}) == 0;
106
/************* String Utilities ***************/
108
function GetString(name)
113
var strBundleService =
114
Components.classes["@mozilla.org/intl/stringbundle;1"].getService();
116
strBundleService.QueryInterface(Components.interfaces.nsIStringBundleService);
118
gStringBundle = strBundleService.createBundle("chrome://editor/locale/editor.properties");
125
return gStringBundle.GetStringFromName(name);
131
function TrimStringLeft(string)
133
if(!string) return "";
134
return string.replace(/^\s+/, "");
137
function TrimStringRight(string)
139
if (!string) return "";
140
return string.replace(/\s+$/, '');
143
// Remove whitespace from both ends of a string
144
function TrimString(string)
146
if (!string) return "";
147
return string.replace(/(^\s+)|(\s+$)/g, '')
150
function IsWhitespace(string)
152
return /^\s/.test(string);
155
function TruncateStringAtWordEnd(string, maxLength, addEllipses)
157
// Return empty if string is null, undefined, or the empty string
161
// We assume they probably don't want whitespace at the beginning
162
string = string.replace(/^\s+/, '');
163
if (string.length <= maxLength)
166
// We need to truncate the string to maxLength or fewer chars
169
string = string.replace(RegExp("(.{0," + maxLength + "})\\s.*"), "$1")
171
if (string.length > maxLength)
172
string = string.slice(0, maxLength);
179
// Replace all whitespace characters with supplied character
180
// E.g.: Use charReplace = " ", to "unwrap" the string by removing line-end chars
181
// Use charReplace = "_" when you don't want spaces (like in a URL)
182
function ReplaceWhitespace(string, charReplace)
184
return string.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,charReplace)
187
// Replace whitespace with "_" and allow only HTML CDATA
188
// characters: "a"-"z","A"-"Z","0"-"9", "_", ":", "-", ".",
189
// and characters above ASCII 127
190
function ConvertToCDATAString(string)
192
return string.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_\.\-\:\u0080-\uFFFF]+/g,'');
195
function GetSelectionAsText()
198
return GetCurrentEditor().outputToString("text/plain", 1); // OutputSelectionOnly
205
/************* Get Current Editor and associated interfaces or info ***************/
206
const nsIPlaintextEditor = Components.interfaces.nsIPlaintextEditor;
207
const nsIHTMLEditor = Components.interfaces.nsIHTMLEditor;
208
const nsITableEditor = Components.interfaces.nsITableEditor;
209
const nsIEditorStyleSheets = Components.interfaces.nsIEditorStyleSheets;
210
const nsIEditingSession = Components.interfaces.nsIEditingSession;
212
function GetCurrentEditor()
214
// Get the active editor from the <editor> tag
215
// XXX This will probably change if we support > 1 editor in main Composer window
216
// (e.g. a plaintext editor for HTMLSource)
218
// For dialogs: Search up parent chain to find top window with editor
221
var editorElement = GetCurrentEditorElement();
222
editor = editorElement.getEditor(editorElement.contentWindow);
224
// Do QIs now so editor users won't have to figure out which interface to use
225
// Using "instanceof" does the QI for us.
226
editor instanceof Components.interfaces.nsIPlaintextEditor;
227
editor instanceof Components.interfaces.nsIHTMLEditor;
228
} catch (e) { dump (e)+"\n"; }
233
function GetCurrentTableEditor()
235
var editor = GetCurrentEditor();
236
return (editor && (editor instanceof nsITableEditor)) ? editor : null;
239
function GetCurrentEditorElement()
241
var tmpWindow = window;
244
// Get the <editor> element(s)
245
var tabeditor = tmpWindow.document.getElementById("tabeditor");
247
// This will change if we support > 1 editor element
249
return tabeditor.getCurrentEditorElement() ;
251
tmpWindow = tmpWindow.opener;
258
function GetCurrentEditingSession()
261
return GetCurrentEditorElement().editingSession;
262
} catch (e) { dump (e)+"\n"; }
267
function GetCurrentCommandManager()
270
return GetCurrentEditorElement().commandManager;
271
} catch (e) { dump (e)+"\n"; }
276
function GetCurrentEditorType()
279
return GetCurrentEditorElement().editortype;
280
} catch (e) { dump (e)+"\n"; }
285
function IsHTMLEditor()
287
// We don't have an editorElement, just return false
288
if (!GetCurrentEditorElement())
291
var editortype = GetCurrentEditorType();
303
dump("INVALID EDITOR TYPE: " + editortype + "\n");
309
function PageIsEmptyAndUntouched()
311
return IsDocumentEmpty() && !IsDocumentModified() && !IsHTMLSourceChanged();
314
function IsInHTMLSourceMode()
316
return (gEditorDisplayMode == kDisplayModeSource);
319
// are we editing HTML (i.e. neither in HTML source mode, nor editing a text file)
320
function IsEditingRenderedHTML()
322
return IsHTMLEditor() && !IsInHTMLSourceMode();
325
function IsWebComposer()
327
return document.documentElement.id == "editorWindow";
330
function IsDocumentEditable()
333
return GetCurrentEditor().isDocumentEditable;
338
function IsDocumentEmpty()
341
return GetCurrentEditor().documentIsEmpty;
346
function IsDocumentModified()
349
return GetCurrentEditor().documentModified;
354
function IsHTMLSourceChanged()
356
return gSourceTextEditor.documentModified;
359
function newCommandParams()
362
return Components.classes["@mozilla.org/embedcomp/command-params;1"].createInstance(Components.interfaces.nsICommandParams);
364
catch(e) { dump("error thrown in newCommandParams: "+e+"\n"); }
368
/************* General editing command utilities ***************/
370
function GetDocumentTitle()
373
return GetCurrentEditor().document.title;
374
// return new XPCNativeWrapper(GetCurrentEditor().document, "title").title;
380
function SetDocumentTitle(title)
384
GetCurrentEditor().setDocumentTitle(title);
386
// Update window title (doesn't work if called from a dialog)
387
if ("UpdateWindowTitle" in window)
388
window.UpdateWindowTitle();
393
function GetAtomService()
395
gAtomService = Components.classes["@mozilla.org/atom-service;1"].getService(Components.interfaces.nsIAtomService);
398
function EditorGetTextProperty(property, attribute, value, firstHas, anyHas, allHas)
401
if (!gAtomService) GetAtomService();
402
var propAtom = gAtomService.getAtom(property);
404
GetCurrentEditor().getInlineProperty(propAtom, attribute, value,
405
firstHas, anyHas, allHas);
410
function EditorSetTextProperty(property, attribute, value)
413
if (!gAtomService) GetAtomService();
414
var propAtom = gAtomService.getAtom(property);
416
GetCurrentEditor().setInlineProperty(propAtom, attribute, value);
417
if ("gContentWindow" in window)
418
window.gContentWindow.focus();
423
function EditorRemoveTextProperty(property, attribute)
426
if (!gAtomService) GetAtomService();
427
var propAtom = gAtomService.getAtom(property);
429
GetCurrentEditor().removeInlineProperty(propAtom, attribute);
430
if ("gContentWindow" in window)
431
window.gContentWindow.focus();
436
/************* Element enbabling/disabling ***************/
438
// this function takes an elementID and a flag
439
// if the element can be found by ID, then it is either enabled (by removing "disabled" attr)
440
// or disabled (setAttribute) as specified in the "doEnable" parameter
441
function SetElementEnabledById(elementID, doEnable)
443
SetElementEnabled(document.getElementById(elementID), doEnable);
446
function SetElementEnabled(element, doEnable)
450
// <Kaze> looks like the first try was the best one...
451
//~ /* if ( doEnable )
452
//~ element.removeAttribute("disabled");
454
//~ element.setAttribute("disabled", "true"); */
455
//~ element.disabled = !doEnable;
457
element.removeAttribute("disabled");
459
element.setAttribute("disabled", "true");
464
dump("Element not found in SetElementEnabled\n");
468
function SetElementVisible(element, isVisible)
473
element.style.visibility = "visible";
475
element.style.visibility = "hidden";
479
dump("Element not found in SetElementEnabled\n");
483
/************* Services / Prefs ***************/
485
function GetIOService()
490
gIOService = Components.classes["@mozilla.org/network/io-service;1"]
491
.getService(Components.interfaces.nsIIOService);
496
function GetFileProtocolHandler()
498
var ios = GetIOService();
499
var handler = ios.getProtocolHandler("file");
500
return handler.QueryInterface(Components.interfaces.nsIFileProtocolHandler);
503
function GetPrefsService()
506
return gPrefsService;
509
gPrefsService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
512
dump("failed to get prefs service!\n");
515
return gPrefsService;
524
var prefService = GetPrefsService();
526
gPrefsBranch = prefService.getBranch(null);
531
dump("failed to get root prefs!\n");
534
dump("failed to get root prefs!\n");
539
function GetStringPref(name)
542
return GetPrefs().getComplexValue(name, Components.interfaces.nsISupportsString).data;
547
function GetBoolPref(name)
550
return GetPrefs().getBoolPref(name);
555
function SetUnicharPref(aPrefName, aPrefValue)
557
var prefs = GetPrefs();
561
var str = Components.classes["@mozilla.org/supports-string;1"]
562
.createInstance(Components.interfaces.nsISupportsString);
563
str.data = aPrefValue;
564
prefs.setComplexValue(aPrefName, Components.interfaces.nsISupportsString, str);
570
function GetUnicharPref(aPrefName, aDefVal)
572
var prefs = GetPrefs();
576
return prefs.getComplexValue(aPrefName, Components.interfaces.nsISupportsString).data;
583
// Set initial directory for a filepicker from URLs saved in prefs
584
function SetFilePickerDirectory(filePicker, fileType)
589
var prefBranch = GetPrefs();
592
// Save current directory so we can reset it in SaveFilePickerDirectory
593
gFilePickerDirectory = filePicker.displayDirectory;
595
var location = prefBranch.getComplexValue("editor.lastFileLocation."+fileType, Components.interfaces.nsILocalFile);
597
filePicker.displayDirectory = location;
604
// Save the directory of the selected file to prefs
605
function SaveFilePickerDirectory(filePicker, fileType)
607
if (filePicker && filePicker.file)
610
var prefBranch = GetPrefs();
613
if (filePicker.file.parent)
614
fileDir = filePicker.file.parent.QueryInterface(Components.interfaces.nsILocalFile);
617
prefBranch.setComplexValue("editor.lastFileLocation."+fileType, Components.interfaces.nsILocalFile, fileDir);
619
var prefsService = GetPrefsService();
620
prefsService.savePrefFile(null);
624
// Restore the directory used before SetFilePickerDirectory was called;
625
// This reduces interference with Browser and other module directory defaults
626
if (gFilePickerDirectory)
627
filePicker.displayDirectory = gFilePickerDirectory;
629
gFilePickerDirectory = null;
632
function GetDefaultBrowserColors()
634
var prefs = GetPrefs();
635
var colors = { TextColor:0, BackgroundColor:0, LinkColor:0, ActiveLinkColor:0 , VisitedLinkColor:0 };
636
var useSysColors = false;
637
try { useSysColors = prefs.getBoolPref("browser.display.use_system_colors"); } catch (e) {}
641
try { colors.TextColor = prefs.getCharPref("browser.display.foreground_color"); } catch (e) {}
643
try { colors.BackgroundColor = prefs.getCharPref("browser.display.background_color"); } catch (e) {}
645
// Use OS colors for text and background if explicitly asked or pref is not set
646
if (!colors.TextColor)
647
colors.TextColor = "windowtext";
649
if (!colors.BackgroundColor)
650
colors.BackgroundColor = "window";
652
colors.LinkColor = prefs.getCharPref("browser.anchor_color");
653
colors.ActiveLinkColor = prefs.getCharPref("browser.active_color");
654
colors.VisitedLinkColor = prefs.getCharPref("browser.visited_color");
659
/************* URL handling ***************/
661
function TextIsURI(selectedText)
663
return selectedText && /^http:\/\/|^https:\/\/|^file:\/\/|\
664
^ftp:\/\/|^about:|^mailto:|^news:|^snews:|^telnet:|^ldap:|\
665
^ldaps:|^gopher:|^finger:|^javascript:/i.test(selectedText);
668
function IsUrlAboutBlank(urlString)
670
return (urlString == "about:blank" || urlString == "about:xblank" ||
671
urlString == "about:strictblank" || urlString == "about:xstrictblank");
674
//~ function MakeRelativeUrl(url)
675
function MakeRelativeUrl(url, base) { // modified
676
// Added: optional "base" param (default = document URL)
678
var inputUrl = TrimString(url);
682
// Get the filespec relative to current document's location
683
// NOTE: Can't do this if file isn't saved yet!
684
var docUrl = base ? base : GetDocumentBaseUrl(); // Kaze
685
var docScheme = GetScheme(docUrl);
687
// Can't relativize if no doc scheme (page hasn't been saved)
691
var urlScheme = GetScheme(inputUrl);
693
// Do nothing if not the same scheme or url is already relativized
694
if (docScheme != urlScheme)
697
var IOService = GetIOService();
701
// Host must be the same
702
var docHost = GetHost(docUrl);
703
var urlHost = GetHost(inputUrl);
704
if (docHost != urlHost)
708
// Get just the file path part of the urls
709
// XXX Should we use GetCurrentEditor().documentCharacterSet for 2nd param ?
710
var docPath = IOService.newURI(docUrl, GetCurrentEditor().documentCharacterSet, null).path;
711
var urlPath = IOService.newURI(inputUrl, GetCurrentEditor().documentCharacterSet, null).path;
713
// We only return "urlPath", so we can convert
714
// the entire docPath for case-insensitive comparisons
716
var doCaseInsensitive = (docScheme == "file" && os == gWin);
717
if (doCaseInsensitive)
718
docPath = docPath.toLowerCase();
720
// Get document filename before we start chopping up the docPath
721
var docFilename = GetFilename(docPath);
723
// Both url and doc paths now begin with "/"
724
// Look for shared dirs starting after that
725
urlPath = urlPath.slice(1);
726
docPath = docPath.slice(1);
728
var firstDirTest = true;
729
var nextDocSlash = 0;
732
// Remove all matching subdirs common to both doc and input urls
734
nextDocSlash = docPath.indexOf("\/");
735
var nextUrlSlash = urlPath.indexOf("\/");
737
if (nextUrlSlash == -1)
739
// We're done matching and all dirs in url
740
// what's left is the filename
743
// Remove filename for named anchors in the same file
744
if (nextDocSlash == -1 && docFilename)
746
var anchorIndex = urlPath.indexOf("#");
749
var urlFilename = doCaseInsensitive ? urlPath.toLowerCase() : urlPath;
751
if (urlFilename.indexOf(docFilename) == 0)
752
urlPath = urlPath.slice(anchorIndex);
756
else if (nextDocSlash >= 0)
758
// Test for matching subdir
759
var docDir = docPath.slice(0, nextDocSlash);
760
var urlDir = urlPath.slice(0, nextUrlSlash);
761
if (doCaseInsensitive)
762
urlDir = urlDir.toLowerCase();
764
if (urlDir == docDir)
767
// Remove matching dir+"/" from each path
768
// and continue to next dir
769
docPath = docPath.slice(nextDocSlash+1);
770
urlPath = urlPath.slice(nextUrlSlash+1);
774
// No match, we're done
777
// Be sure we are on the same local drive or volume
778
// (the first "dir" in the path) because we can't
779
// relativize to different drives/volumes.
780
// UNIX doesn't have volumes, so we must not do this else
781
// the first directory will be misinterpreted as a volume name
782
if (firstDirTest && docScheme == "file" && os != gUNIX)
786
else // No more doc dirs left, we're done
789
firstDirTest = false;
793
// Add "../" for each dir left in docPath
794
while (nextDocSlash > 0)
796
urlPath = "../" + urlPath;
797
nextDocSlash = docPath.indexOf("\/", nextDocSlash+1);
802
function MakeAbsoluteUrl(url)
804
var resultUrl = TrimString(url);
808
// Check if URL is already absolute, i.e., it has a scheme
809
var urlScheme = GetScheme(resultUrl);
814
var docUrl = GetDocumentBaseUrl();
815
var docScheme = GetScheme(docUrl);
817
// Can't relativize if no doc scheme (page hasn't been saved)
821
var IOService = GetIOService();
825
// Make a URI object to use its "resolve" method
826
var absoluteUrl = resultUrl;
827
var docUri = IOService.newURI(docUrl, GetCurrentEditor().documentCharacterSet, null);
830
absoluteUrl = docUri.resolve(resultUrl);
831
// This is deprecated and buggy!
832
// If used, we must make it a path for the parent directory (remove filename)
833
//absoluteUrl = IOService.resolveRelativePath(resultUrl, docUrl);
839
// Get the HREF of the page's <base> tag or the document location
840
// returns empty string if no base href and document hasn't been saved yet
841
function GetDocumentBaseUrl()
846
// if document supplies a <base> tag, use that URL instead
847
var baseList = GetCurrentEditor().document.getElementsByTagName("base");
850
var base = baseList.item(0);
852
docUrl = base.getAttribute("href");
855
docUrl = GetDocumentUrl();
857
if (!IsUrlAboutBlank(docUrl))
863
function GetDocumentUrl()
866
var aDOMHTMLDoc = GetCurrentEditor().document.QueryInterface(Components.interfaces.nsIDOMHTMLDocument);
867
return aDOMHTMLDoc.URL;
873
// Extract the scheme (e.g., 'file', 'http') from a URL string
874
function GetScheme(urlspec)
876
var resultUrl = TrimString(urlspec);
877
// Unsaved document URL has no acceptable scheme yet
878
if (!resultUrl || IsUrlAboutBlank(resultUrl))
881
var IOService = GetIOService();
887
// This fails if there's no scheme
888
scheme = IOService.extractScheme(resultUrl);
891
return scheme ? scheme.toLowerCase() : "";
894
function GetHost(urlspec)
899
var IOService = GetIOService();
905
host = IOService.newURI(urlspec, null, null).host;
911
function GetUsername(urlspec)
916
var IOService = GetIOService();
922
username = IOService.newURI(urlspec, null, null).username;
928
function GetFilename(urlspec)
930
if (!urlspec || IsUrlAboutBlank(urlspec))
933
var IOService = GetIOService();
940
var uri = IOService.newURI(urlspec, null, null);
943
var url = uri.QueryInterface(Components.interfaces.nsIURL);
945
filename = url.fileName;
949
return filename ? filename : "";
952
// Return the url without username and password
953
// Optional output objects return extracted username and password strings
954
// This uses just string routines via nsIIOServices
955
function StripUsernamePassword(urlspec, usernameObj, passwordObj)
957
urlspec = TrimString(urlspec);
958
if (!urlspec || IsUrlAboutBlank(urlspec))
962
usernameObj.value = "";
964
passwordObj.value = "";
966
// "@" must exist else we will never detect username or password
967
var atIndex = urlspec.indexOf("@");
971
var IOService = GetIOService();
975
var uri = IOService.newURI(urlspec, null, null);
976
var username = uri.username;
977
var password = uri.password;
979
if (usernameObj && username)
980
usernameObj.value = username;
981
if (passwordObj && password)
982
passwordObj.value = password;
985
var usernameStart = urlspec.indexOf(username);
986
if (usernameStart != -1)
987
return urlspec.slice(0, usernameStart) + urlspec.slice(atIndex+1);
994
function StripPassword(urlspec, passwordObj)
996
urlspec = TrimString(urlspec);
997
if (!urlspec || IsUrlAboutBlank(urlspec))
1001
passwordObj.value = "";
1003
// "@" must exist else we will never detect password
1004
var atIndex = urlspec.indexOf("@");
1008
var IOService = GetIOService();
1012
var password = IOService.newURI(urlspec, null, null).password;
1014
if (passwordObj && password)
1015
passwordObj.value = password;
1018
// Find last ":" before "@"
1019
var colon = urlspec.lastIndexOf(":", atIndex);
1023
return urlspec.slice(0, colon) + urlspec.slice(atIndex);
1031
// Version to use when you have an nsIURI object
1032
function StripUsernamePasswordFromURI(uri)
1039
var userPass = uri.userPass;
1042
start = urlspec.indexOf(userPass);
1043
urlspec = urlspec.slice(0, start) + urlspec.slice(start+userPass.length+1);
1050
function InsertUsernameIntoUrl(urlspec, username)
1052
if (!urlspec || !username)
1056
var ioService = GetIOService();
1057
var URI = ioService.newURI(urlspec, GetCurrentEditor().documentCharacterSet, null);
1058
URI.username = username;
1070
var platform = navigator.platform.toLowerCase();
1072
if (platform.indexOf("win") != -1)
1074
else if (platform.indexOf("mac") != -1)
1076
else if (platform.indexOf("unix") != -1 || platform.indexOf("linux") != -1 || platform.indexOf("sun") != -1)
1085
function ConvertRGBColorIntoHEXColor(color)
1087
if ( /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.test(color) ) {
1088
var r = Number(RegExp.$1).toString(16);
1089
if (r.length == 1) r = "0"+r;
1090
var g = Number(RegExp.$2).toString(16);
1091
if (g.length == 1) g = "0"+g;
1092
var b = Number(RegExp.$3).toString(16);
1093
if (b.length == 1) b = "0"+b;
1102
/************* CSS ***************/
1104
function GetHTMLOrCSSStyleValue(element, attrName, cssPropertyName)
1106
var prefs = GetPrefs();
1107
var IsCSSPrefChecked = prefs.getBoolPref("editor.use_css");
1109
if (IsCSSPrefChecked && IsHTMLEditor())
1110
value = element.style.getPropertyValue(cssPropertyName);
1113
value = element.getAttribute(attrName);
1121
/************* Miscellaneous ***************/
1122
// Clone simple JS objects
1128
if( typeof obj[i] == 'object')
1129
clone[i] = Clone(obj[i]);
1136
function GetCSSPropertyValueForSelection(property)
1140
if (!gAtomService) GetAtomService();
1141
var propAtom = gAtomService.getAtom(property);
1143
value = GetCurrentEditor().getCSSPropertyValueForSelection(propAtom);
1150
function ListAvailableCharSets()
1153
var availCharsetDict = [];
1154
var rdf = Components.classes["@mozilla.org/rdf/rdf-service;1"].getService(Components.interfaces.nsIRDFService);
1155
var kNC_Root = rdf.GetResource("NC:DecodersRoot");
1156
var kNC_name = rdf.GetResource("http://home.netscape.com/NC-rdf#Name");
1157
var rdfDataSource = rdf.GetDataSource("rdf:charset-menu");
1158
var rdfContainer = Components.classes["@mozilla.org/rdf/container;1"].getService(Components.interfaces.nsIRDFContainer);
1160
rdfContainer.Init(rdfDataSource, kNC_Root);
1161
var availableCharsets = rdfContainer.GetElements();
1164
for (var i = 0; i < rdfContainer.GetCount(); i++) {
1165
charset = availableCharsets.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
1166
availCharsetDict[i] = new Array(2);
1167
availCharsetDict[i][0] = readRDFString(rdfDataSource, charset, kNC_name);
1168
availCharsetDict[i][1] = charset.Value;
1170
return availCharsetDict;
1172
catch (e) { return null; }
1175
function ExplodeElement(node)
1177
var child = node.firstChild;
1178
var parent = node.parentNode;
1183
var tmp = child.nextSibling;
1184
parent.insertBefore(child, node);
1187
var brNode = document.createElement("br");
1188
parent.insertBefore(brNode, node);
1189
parent.removeChild(node);
1192
function NormalizeURL(url)
1194
if (!GetScheme(url) && !IsUrlAboutBlank(url))
1196
var k = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
1198
var noBackSlashUrl = url.replace(/\\\"/g, "\"");
1199
var c0 = noBackSlashUrl[0];
1200
var c1 = noBackSlashUrl[1]
1202
( ((c0 >= 'a' && c0 <= 'z') || (c0 >= 'A' && c0 <= 'Z')) && c1 == ":"))
1204
// this is an absolute path
1205
k.initWithPath(url);
1209
// First, get the current dir for the process...
1210
var dirServiceProvider = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIDirectoryServiceProvider);
1211
var p = new Object();
1212
var currentProcessDir = dirServiceProvider.getFile("CurWorkD", p).path;
1213
k.initWithPath(currentProcessDir);
1215
// then try to append the relative path
1217
k.appendRelativePath(url);
1220
dump("### Can't understand the filepath\n");
1221
return "about:blank";
1223
var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
1224
var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
1225
url = fileHandler.getURLSpecFromFile(k);
1231
function IsXHTMLDocument()
1233
var doctype = GetCurrentEditor().document.doctype;
1234
return (doctype.publicId == "-//W3C//DTD XHTML 1.0 Transitional//EN" ||
1235
doctype.publicId == "-//W3C//DTD XHTML 1.0 Strict//EN");
1238
function IsStrictDTD()
1240
var doctype = GetCurrentEditor().document.doctype;
1241
return (doctype.publicId.lastIndexOf("Strict") != -1);
1244
function IsCSSDisabledAndStrictDTD()
1246
var prefs = GetPrefs();
1247
var IsCSSPrefChecked = prefs.getBoolPref("editor.use_css");
1248
return !IsCSSPrefChecked && IsStrictDTD();