home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / sunbird / js / calWcapUtils.js < prev    next >
Encoding:
JavaScript  |  2007-05-23  |  12.5 KB  |  380 lines

  1. /* -*- Mode: javascript; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: NPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Mozilla Public
  6.  * License Version 1.1 (the "License"); you may not use this file
  7.  * except in compliance with the License. You may obtain a copy of
  8.  * the License at http://www.mozilla.org/MPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS
  11.  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  12.  * implied. See the License for the specific language governing
  13.  * rights and limitations under the License.
  14.  *
  15.  * The Original Code is mozilla.org code.
  16.  *
  17.  * The Initial Developer of the Original Code is Sun Microsystems, Inc.
  18.  * Portions created by Sun Microsystems are Copyright (C) 2006 Sun
  19.  * Microsystems, Inc. All Rights Reserved.
  20.  *
  21.  * Original Author: Daniel Boelzle (daniel.boelzle@sun.com)
  22.  *
  23.  * Contributor(s):
  24.  *
  25.  *
  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.
  37.  *
  38.  * ***** END LICENSE BLOCK ***** */
  39.  
  40. var g_bShutdown = false;
  41. var g_logTimezone = null;
  42. var g_logFilestream = null;
  43. var g_logPrefObserver = null;
  44.  
  45. function initLogging()
  46. {
  47.     g_logTimezone = getPref("calendar.timezone.local", null);
  48.     
  49.     if (g_logFilestream) {
  50.         try {
  51.             g_logFilestream.close();
  52.         }
  53.         catch (exc) {
  54.         }
  55.         g_logFilestream = null;
  56.     }
  57.     
  58.     LOG_LEVEL = getPref("calendar.wcap.log_level", 0);
  59.     if (LOG_LEVEL < 1 && getPref("calendar.debug.log", false))
  60.         LOG_LEVEL = 1; // at least basic logging when calendar.debug.log is set
  61.     
  62.     if (LOG_LEVEL > 0) {
  63.         var logFileName = getPref("calendar.wcap.log_file", null);
  64.         if (logFileName) {
  65.             try {
  66.                 // set up file:
  67.                 var logFile = Components.classes["@mozilla.org/file/local;1"]
  68.                                         .createInstance(Components.interfaces.nsILocalFile);
  69.                 logFile.initWithPath(logFileName);
  70.                 // create output stream:
  71.                 var logFileStream =
  72.                     Components.classes["@mozilla.org/network/file-output-stream;1"]
  73.                               .createInstance(Components.interfaces.nsIFileOutputStream);
  74.                 logFileStream.init(
  75.                     logFile,
  76.                     0x02 /* PR_WRONLY */ |
  77.                     0x08 /* PR_CREATE_FILE */ |
  78.                     0x10 /* PR_APPEND */,
  79.                     0700 /* read, write, execute/search by owner */,
  80.                     0 /* unused */);
  81.                 g_logFilestream = logFileStream;
  82.             }
  83.             catch (exc) {
  84.                 logError(exc, "init logging");
  85.             }
  86.         }
  87.         log("################################# NEW LOG #################################",
  88.             "init logging");
  89.     }
  90.     if (!g_logPrefObserver) {
  91.         g_logPrefObserver = { // nsIObserver:
  92.             observe: function logPrefObserver_observe(subject, topic, data) {
  93.                 if (topic == "nsPref:changed") {
  94.                     switch (data) {
  95.                     case "calendar.wcap.log_level":
  96.                     case "calendar.wcap.log_file":
  97.                     case "calendar.debug.log":
  98.                         initLogging();
  99.                         break;
  100.                     }
  101.                 }
  102.             }
  103.         };
  104.         var prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
  105.                                    .getService(Components.interfaces.nsIPrefBranch2);
  106.         prefBranch.addObserver("calendar.wcap.log_level", g_logPrefObserver, false);
  107.         prefBranch.addObserver("calendar.wcap.log_file", g_logPrefObserver, false);
  108.         prefBranch.addObserver("calendar.debug.log", g_logPrefObserver, false);
  109.         
  110.         var observerService = Components.classes["@mozilla.org/observer-service;1"]
  111.                                         .getService(Components.interfaces.nsIObserverService);
  112.         var appObserver = { // nsIObserver:
  113.             observe: function app_observe(subject, topic, data) {
  114.                 if (topic == "quit-application")
  115.                     prefBranch.removeObserver("calendar.", g_logPrefObserver);
  116.             }
  117.         };
  118.         observerService.addObserver(appObserver, "quit-application", false);
  119.     }
  120. }
  121.  
  122. function log(msg, context, bForce)
  123. {
  124.     if (bForce || LOG_LEVEL > 0) {
  125.         var ret = "";
  126.         if (context)
  127.             ret += ("[" + context + "]");
  128.         if (msg) {
  129.             if (ret.length > 0)
  130.                 ret += "\n";
  131.             ret += msg;
  132.         }
  133.         var now = getTime();
  134.         if (now && g_logTimezone)
  135.             now = now.getInTimezone(g_logTimezone);
  136.         var str = ("### WCAP log entry: " + now + "\n" + ret);
  137.         getConsoleService().logStringMessage(str);
  138.         str = ("\n" + str + "\n");
  139.         dump(str);
  140.         if (g_logFilestream) {
  141.             try {
  142.                 // xxx todo?
  143.                 // assuming ANSI chars here, for logging sufficient:
  144.                 g_logFilestream.write(str, str.length);
  145.             }
  146.             catch (exc) { // catching any io errors here:
  147.                 var err = ("error writing log file: " + errorToString(exc));
  148.                 Components.utils.reportError(exc);
  149.                 getConsoleService().logStringMessage(err);
  150.                 dump(err  + "\n\n");
  151.             }
  152.         }
  153.         return ret;
  154.     }
  155.     else
  156.         return msg;
  157. }
  158.  
  159. function logError(err, context)
  160. {
  161.     var msg = errorToString(err);
  162.     Components.utils.reportError( log("error: " + msg, context, true) );
  163.     return msg;
  164. }
  165.  
  166. // late-inited service accessors:
  167.  
  168. var g_consoleService = null;
  169. function getConsoleService() {
  170.     if (!g_consoleService) {
  171.         g_consoleService =
  172.             Components.classes["@mozilla.org/consoleservice;1"]
  173.                       .getService(Components.interfaces.nsIConsoleService);
  174.     }
  175.     return g_consoleService;
  176. }
  177.  
  178. var g_windowWatcher = null;
  179. function getWindowWatcher() {
  180.     if (!g_windowWatcher) {
  181.         g_windowWatcher =
  182.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  183.                       .getService(Components.interfaces.nsIWindowWatcher);
  184.     }
  185.     return g_windowWatcher;
  186. }
  187.  
  188. var g_icsService = null;
  189. function getIcsService() {
  190.     if (!g_icsService) {
  191.         g_icsService =
  192.             Components.classes["@mozilla.org/calendar/ics-service;1"]
  193.                       .getService(Components.interfaces.calIICSService);
  194.     }
  195.     return g_icsService;
  196. }
  197.  
  198. var g_domParser = null;
  199. function getDomParser() {
  200.     if (!g_domParser) {
  201.         g_domParser =
  202.             Components.classes["@mozilla.org/xmlextras/domparser;1"]
  203.                       .getService(Components.interfaces.nsIDOMParser);
  204.     }
  205.     return g_domParser;
  206. }
  207.  
  208. var g_calendarManager = null;
  209. function getCalendarManager() {
  210.     if (!g_calendarManager) {
  211.         g_calendarManager =
  212.             Components.classes["@mozilla.org/calendar/manager;1"]
  213.                       .getService(Components.interfaces.calICalendarManager);
  214.     }
  215.     return g_calendarManager;
  216. };
  217.  
  218. var g_wcapBundle = null;
  219. function getWcapBundle() {
  220.     if (!g_wcapBundle) {
  221.         var stringBundleService =
  222.             Components.classes["@mozilla.org/intl/stringbundle;1"]
  223.                       .getService(Components.interfaces.nsIStringBundleService);
  224.         g_wcapBundle = stringBundleService.createBundle(
  225.             "chrome://calendar/locale/wcap.properties");
  226.     }
  227.     return g_wcapBundle;
  228. }
  229.  
  230. function subClass(subCtor, baseCtor) {
  231.     subCtor.prototype = new baseCtor();
  232.     subCtor.prototype.constructor = subCtor;
  233.     subCtor.prototype.superClass = baseCtor;
  234. }
  235.  
  236. function qiface(list, iid) {
  237.     if (!list.some( function(i) { return i.equals(iid); } ))
  238.         throw Components.results.NS_ERROR_NO_INTERFACE;
  239. }
  240.  
  241. function isEvent(item) {
  242.     return (item instanceof Components.interfaces.calIEvent);
  243. }
  244.  
  245. function isParent(item) {
  246.     if (item.id != item.parentItem.id) {
  247.         throw new Components.Exception("proxy has different id than its parent!");
  248.     }
  249.     return (!item.recurrenceId);
  250. }
  251.  
  252. function forEachIcalComponent(icalRootComp, componentType, func, maxResults)
  253. {
  254.     var itemCount = 0;
  255.     // libical returns the vcalendar component if there is just
  256.     // one vcalendar. If there are multiple vcalendars, it returns
  257.     // an xroot component, with those vcalendar childs. We need to
  258.     // handle both.
  259.     for ( var calComp = (icalRootComp.componentType == "VCALENDAR"
  260.                          ? icalRootComp
  261.                          : icalRootComp.getFirstSubcomponent("VCALENDAR"));
  262.           calComp != null && (!maxResults || itemCount < maxResults);
  263.           calComp = icalRootComp.getNextSubcomponent("VCALENDAR") )
  264.     {
  265.         for ( var subComp = calComp.getFirstSubcomponent(componentType);
  266.               subComp != null && (!maxResults || itemCount < maxResults);
  267.               subComp = calComp.getNextSubcomponent(componentType) )
  268.         {
  269.             func( subComp );
  270.             ++itemCount;
  271.         }
  272.     }
  273. }
  274.  
  275. function filterXmlNodes(name, rootNode)
  276. {
  277.     var ret = [];
  278.     if (rootNode) {
  279.         var nodeList = rootNode.getElementsByTagName(name);
  280.         for (var i = 0; i < nodeList.length; ++i) {
  281.             var node = nodeList.item(i);
  282.             ret.push( trimString(node.textContent) );
  283.         }
  284.     }
  285.     return ret;
  286. }
  287.  
  288. function trimString(str) {
  289.     return str.replace(/(^\s+|\s+$)/g, "");
  290. }
  291.  
  292. function getTime() {
  293.     if (g_bShutdown)
  294.         return null;
  295.     var ret = new CalDateTime();
  296.     ret.jsDate = new Date();
  297.     return ret;
  298. }
  299.  
  300. function getIcalUTC(dt) {
  301.     if (!dt)
  302.         return "0";
  303.     else {
  304.         var dtz = dt.timezone;
  305.         if (dtz == "UTC" || dtz == "floating")
  306.             return dt.icalString;
  307.         else
  308.             return dt.getInTimezone("UTC").icalString;
  309.     }
  310. }
  311.  
  312. function getDatetimeFromIcalString(val) {
  313.     if (!val || val.length == 0 || val == "0")
  314.         return null;
  315.     // assuming timezone is known:
  316.     var dt = new CalDateTime();
  317.     dt.icalString = val;
  318.     if (LOG_LEVEL > 1) {
  319.         var dt_ = dt.clone();
  320.         dt_.normalize();
  321.         if (dt.icalString != val || dt_.icalString != val) {
  322.             logError(dt.icalString + " vs. " + val, "date-time error");
  323.             logError(dt_.icalString + " vs. " + val, "date-time error");
  324.             debugger;
  325.         }
  326.     }
  327.     return dt;
  328. }
  329.  
  330. function getDatetimeFromIcalProp(prop) {
  331.     if (!prop)
  332.         return null;
  333.     return getDatetimeFromIcalString(prop.valueAsIcalString);
  334. }
  335.  
  336. function getPref(prefName, defaultValue) {
  337.     const nsIPrefBranch = Components.interfaces.nsIPrefBranch;
  338.     var prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
  339.                                .getService(nsIPrefBranch);
  340.     var ret;
  341.     switch (prefBranch.getPrefType(prefName)) {
  342.     case nsIPrefBranch.PREF_BOOL:
  343.         ret = prefBranch.getBoolPref(prefName);
  344.         break;
  345.     case nsIPrefBranch.PREF_INT:
  346.         ret = prefBranch.getIntPref(prefName);
  347.         break;
  348.     case nsIPrefBranch.PREF_STRING:
  349.         ret = prefBranch.getCharPref(prefName);
  350.         break;
  351.     default:
  352.         ret = defaultValue;
  353.         break;
  354.     }
  355.     log(ret, "getPref(): prefName=" + prefName);
  356.     return ret;
  357. }
  358.  
  359. function setPref(prefName, value) {
  360.     log(value, "setPref(): prefName=" + prefName);
  361.     const nsIPrefBranch = Components.interfaces.nsIPrefBranch;
  362.     var prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
  363.                                .getService(nsIPrefBranch);
  364.     switch (typeof(value)) {
  365.     case "boolean":
  366.         prefBranch.setBoolPref(prefName, value);
  367.         break;
  368.     case "number":
  369.         prefBranch.setIntPref(prefName, value);
  370.         break;
  371.     case "string":
  372.         prefBranch.setCharPref(prefName, value);
  373.         break;
  374.     default:
  375.         throw new Components.Exception("unsupported pref value: " +
  376.                                        typeof(value));
  377.     }
  378. }
  379.  
  380.