f-spot r3962 - in trunk: . src src/Imaging src/Utils



Author: sdelcroix
Date: Wed May 21 08:17:28 2008
New Revision: 3962
URL: http://svn.gnome.org/viewvc/f-spot?rev=3962&view=rev

Log:
2008-05-21  Stephane Delcroix  <sdelcroix novell com>

	* src/Utils/ConsoleCrayon.cs:
	* src/Utils/Log.cs:
	* src/Makefile.am:
	* src/main.cs: new ConsoleCrayon and Log classes, stolen from banshee.
	Toggle debugging output on --debug parameter. Replace some s.c.wl by
	Log calls.


Added:
   trunk/src/Utils/ConsoleCrayon.cs
   trunk/src/Utils/Log.cs
Modified:
   trunk/ChangeLog
   trunk/src/GroupAdaptor.cs
   trunk/src/Imaging/ImageFile.cs
   trunk/src/Makefile.am
   trunk/src/PhotoImageView.cs
   trunk/src/PhotoStore.cs
   trunk/src/main.cs

Modified: trunk/src/GroupAdaptor.cs
==============================================================================
--- trunk/src/GroupAdaptor.cs	(original)
+++ trunk/src/GroupAdaptor.cs	Wed May 21 08:17:28 2008
@@ -45,7 +45,7 @@
 
 		protected void HandleQueryChanged (IBrowsableCollection sender)
 		{
-			System.Console.WriteLine ("Reloading" );
+			Log.Debug ("GroupAdaptor::Reloading" );
 			Reload ();
 		}
 

Modified: trunk/src/Imaging/ImageFile.cs
==============================================================================
--- trunk/src/Imaging/ImageFile.cs	(original)
+++ trunk/src/Imaging/ImageFile.cs	Wed May 21 08:17:28 2008
@@ -33,7 +33,7 @@
 			//if (vfs.IsLocal)
 			//	return File.OpenRead (uri.LocalPath);
 
-			System.Console.WriteLine ("open uri = {0}", uri.ToString ());
+			Log.DebugFormat ("open uri = {0}", uri.ToString ());
 			return new Gnome.Vfs.VfsStream (uri.ToString (), FileMode.Open);
 		}
 

Modified: trunk/src/Makefile.am
==============================================================================
--- trunk/src/Makefile.am	(original)
+++ trunk/src/Makefile.am	Wed May 21 08:17:28 2008
@@ -39,9 +39,11 @@
 	$(srcdir)/Query/UntaggedCondition.cs
 
 UTILS_CSDISTFILES =				\
+	$(srcdir)/Utils/ConsoleCrayon.cs	\
 	$(srcdir)/Utils/DbUtils.cs		\
 	$(srcdir)/Utils/GnomeUtil.cs		\
 	$(srcdir)/Utils/GtkUtil.cs		\
+	$(srcdir)/Utils/Log.cs			\
 	$(srcdir)/Utils/Unix.cs			\
 	$(srcdir)/Utils/UriUtils.cs		\
 	$(srcdir)/Utils/ScreenSaver.cs

Modified: trunk/src/PhotoImageView.cs
==============================================================================
--- trunk/src/PhotoImageView.cs	(original)
+++ trunk/src/PhotoImageView.cs	Wed May 21 08:17:28 2008
@@ -305,7 +305,7 @@
 
 		private void PhotoItemChanged (BrowsablePointer item, BrowsablePointerChangedArgs args) 
 		{
-			System.Console.WriteLine ("item changed");
+			Log.Debug ("PhotoImageView::item changed");
 			// If it is just the position that changed fall out
 			if (args != null && 
 			    args.PreviousItem != null &&

Modified: trunk/src/PhotoStore.cs
==============================================================================
--- trunk/src/PhotoStore.cs	(original)
+++ trunk/src/PhotoStore.cs	Wed May 21 08:17:28 2008
@@ -661,7 +661,7 @@
 			query_builder.Append (String.Join (" AND ", ((String []) where_clauses.ToArray (typeof(String)))));
 		}
 		query_builder.Append (" ORDER BY photos.time");
-		Console.WriteLine ("Query: {0}", query_builder.ToString());
+		Log.DebugFormat ("Query: {0}", query_builder.ToString());
 		return Query (query_builder.ToString ());
 	}
 }

Added: trunk/src/Utils/ConsoleCrayon.cs
==============================================================================
--- (empty file)
+++ trunk/src/Utils/ConsoleCrayon.cs	Wed May 21 08:17:28 2008
@@ -0,0 +1,251 @@
+//
+// ConsoleCrayon.cs
+//
+// Author:
+//   Aaron Bockover <abockover novell com>
+//
+// Copyright (C) 2008 Novell, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace FSpot
+{
+    public static class ConsoleCrayon
+    {
+
+#region Public API
+
+        private static ConsoleColor foreground_color;
+        public static ConsoleColor ForegroundColor {
+            get { return foreground_color; }
+            set {
+                foreground_color = value;
+                SetColor (foreground_color, true);
+            }
+        }
+
+        private static ConsoleColor background_color;
+        public static ConsoleColor BackgroundColor {
+            get { return background_color; }
+            set {
+                background_color = value;
+                SetColor (background_color, false);
+            }
+        }
+
+        public static void ResetColor ()
+        {
+            if (XtermColors) {
+                Console.Write (GetAnsiResetControlCode ());
+            } else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) {
+                Console.ResetColor ();
+            }
+        }
+
+        private static void SetColor (ConsoleColor color, bool isForeground)
+        {
+            if (color < ConsoleColor.Black || color > ConsoleColor.White) {
+                throw new ArgumentOutOfRangeException ("color", "Not a ConsoleColor value.");
+            }
+
+            if (XtermColors) {
+                Console.Write (GetAnsiColorControlCode (color, isForeground));
+            } else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) {
+                if (isForeground) {
+                    Console.ForegroundColor = color;
+                } else {
+                    Console.BackgroundColor = color;
+                }
+            }
+        }
+
+#endregion
+
+#region Ansi/VT Code Calculation
+
+        // Modified from Mono's System.TermInfoDriver
+        // License: MIT/X11
+        // Authors: Gonzalo Paniagua Javier <gonzalo ximian com>
+        // (C) 2005-2006 Novell, Inc <http://www.novell.com>
+        
+        private static int TranslateColor (ConsoleColor desired, out bool light)
+        {
+            light = false;
+            switch (desired) {
+                // Dark colors
+                case ConsoleColor.Black: return 0;
+                case ConsoleColor.DarkRed: return 1;
+                case ConsoleColor.DarkGreen: return 2;
+                case ConsoleColor.DarkYellow: return 3;
+                case ConsoleColor.DarkBlue: return 4;
+                case ConsoleColor.DarkMagenta: return 5;
+                case ConsoleColor.DarkCyan: return 6;
+                case ConsoleColor.Gray: return 7;
+
+                // Light colors
+                case ConsoleColor.DarkGray: light = true; return 0;
+                case ConsoleColor.Red: light = true; return 1;
+                case ConsoleColor.Green: light = true; return 2;
+                case ConsoleColor.Yellow: light = true; return 3;
+                case ConsoleColor.Blue: light = true; return 4;
+                case ConsoleColor.Magenta: light = true; return 5;
+                case ConsoleColor.Cyan: light = true; return 6;
+                case ConsoleColor.White: default: light = true; return 7;
+            }
+        }
+        
+        private static string GetAnsiColorControlCode (ConsoleColor color, bool isForeground)
+        {
+            // lighter fg colours are 90 -> 97 rather than 30 -> 37
+            // lighter bg colours are 100 -> 107 rather than 40 -> 47
+            bool light;
+            int code = TranslateColor (color, out light) + (isForeground ? 30 : 40) + (light ? 60 : 0);
+            return String.Format ("\x001b[{0}m", code);
+        }
+
+        private static string GetAnsiResetControlCode ()
+        {
+            return "\x001b[0m";
+        }
+
+#endregion
+
+#region xterm Detection
+
+        private static bool? xterm_colors = null;
+        public static bool XtermColors { 
+            get {
+                if (xterm_colors == null) {
+                    DetectXtermColors ();
+                }
+
+                return xterm_colors.Value;
+            }
+        }
+
+        [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
+        private extern static int _isatty (int fd);
+            
+        private static bool isatty (int fd)
+        {
+            try {
+                return _isatty (fd) == 1;
+            } catch {
+                return false;
+            }
+        }
+
+        private static void DetectXtermColors ()
+        {
+            bool _xterm_colors = false;
+                
+            switch (Environment.GetEnvironmentVariable ("TERM")) {
+                case "xterm":
+                case "rxvt":
+                case "rxvt-unicode": 
+                    if (Environment.GetEnvironmentVariable ("COLORTERM") != null) {
+                        _xterm_colors = true;
+                    }
+                    break;
+                case "xterm-color":
+                    _xterm_colors = true;
+                    break;
+            }
+
+            xterm_colors = _xterm_colors && isatty (1) && isatty (2);
+        }
+
+#endregion
+
+#region Runtime Detection
+
+        private static bool? runtime_is_mono;
+        public static bool RuntimeIsMono {
+            get { 
+                if (runtime_is_mono == null) {
+                    runtime_is_mono = Type.GetType ("System.MonoType") != null;
+                }
+
+                return runtime_is_mono.Value;
+            }
+        }
+
+#endregion
+
+#region Tests
+
+        public static void Test ()
+        {
+            TestSelf ();
+            Console.WriteLine ();
+            TestAnsi ();
+            Console.WriteLine ();
+            TestRuntime ();
+        }
+
+        private static void TestSelf ()
+        {
+            Console.WriteLine ("==SELF TEST==");
+            foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) {
+                ForegroundColor = color;
+                Console.Write (color);
+                ResetColor ();
+                Console.Write (" :: ");
+                BackgroundColor = color;
+                Console.Write (color);
+                ResetColor ();
+                Console.WriteLine ();
+            }
+        }
+
+        private static void TestAnsi ()
+        {
+            Console.WriteLine ("==ANSI TEST==");
+            foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) {
+                string color_code_fg = GetAnsiColorControlCode (color, true);
+                string color_code_bg = GetAnsiColorControlCode (color, false);
+                Console.Write ("{0}{1}: {2}{3} :: {4}{1}: {5}{3}", color_code_fg, color, color_code_fg.Substring (2),
+                    GetAnsiResetControlCode (), color_code_bg, color_code_bg.Substring (2));
+                Console.WriteLine ();
+            }
+        }
+
+        private static void TestRuntime ()
+        {
+            Console.WriteLine ("==RUNTIME TEST==");
+            foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) {
+                Console.ForegroundColor = color;
+                Console.Write (color);
+                Console.ResetColor ();
+                Console.Write (" :: ");
+                Console.BackgroundColor = color;
+                Console.Write (color);
+                Console.ResetColor ();
+                Console.WriteLine ();
+            }
+        }
+
+#endregion
+
+    }
+}

Added: trunk/src/Utils/Log.cs
==============================================================================
--- (empty file)
+++ trunk/src/Utils/Log.cs	Wed May 21 08:17:28 2008
@@ -0,0 +1,403 @@
+//
+// Log.cs
+//
+// Author:
+//   Aaron Bockover <abockover novell com>
+//
+// Copyright (C) 2005-2007 Novell, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+using System.Collections.Generic;
+
+namespace FSpot
+{
+    public delegate void LogNotifyHandler (LogNotifyArgs args);
+
+    public class LogNotifyArgs : EventArgs
+    {
+        private LogEntry entry;
+        
+        public LogNotifyArgs (LogEntry entry)
+        {
+            this.entry = entry;
+        }
+        
+        public LogEntry Entry {
+            get { return entry; }
+        }
+    }
+        
+    public enum LogEntryType
+    {
+        Debug,
+        Warning,
+        Error,
+        Information
+    }
+    
+    public class LogEntry
+    {
+        private LogEntryType type;
+        private string message;
+        private string details;
+        private DateTime timestamp;
+        
+        internal LogEntry (LogEntryType type, string message, string details)
+        {
+            this.type = type;
+            this.message = message;
+            this.details = details;
+            this.timestamp = DateTime.Now;
+        }
+
+        public LogEntryType Type { 
+            get { return type; }
+        }
+        
+        public string Message { 
+            get { return message; } 
+        }
+        
+        public string Details { 
+            get { return details; } 
+        }
+
+        public DateTime TimeStamp { 
+            get { return timestamp; } 
+        }
+    }
+    
+    public static class Log
+    {
+        public static event LogNotifyHandler Notify;
+        
+        private static Dictionary<uint, DateTime> timers = new Dictionary<uint, DateTime> ();
+        private static uint next_timer_id = 1;
+
+        private static bool debugging = false;
+        public static bool Debugging {
+            get { return debugging; }
+            set { debugging = value; }
+        }
+        
+        public static void Commit (LogEntryType type, string message, string details, bool showUser)
+        {
+            if (type == LogEntryType.Debug && !Debugging) {
+                return;
+            }
+        
+            if (type != LogEntryType.Information || (type == LogEntryType.Information && !showUser)) {
+                switch (type) {
+                    case LogEntryType.Error: ConsoleCrayon.ForegroundColor = ConsoleColor.Red; break;
+                    case LogEntryType.Warning: ConsoleCrayon.ForegroundColor = ConsoleColor.Yellow; break;
+                    case LogEntryType.Information: ConsoleCrayon.ForegroundColor = ConsoleColor.Green; break;
+                    case LogEntryType.Debug: ConsoleCrayon.ForegroundColor = ConsoleColor.Blue; break;
+                }
+                
+                Console.Write ("[{0} {1:00}:{2:00}:{3:00}.{4:000}]", TypeString (type), DateTime.Now.Hour,
+                    DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
+                
+                ConsoleCrayon.ResetColor ();
+                               
+                if (details != null) {
+                    Console.WriteLine (" {0} - {1}", message, details);
+                } else {
+                    Console.WriteLine (" {0}", message);
+                }
+            }
+            
+            if (showUser) {
+                OnNotify (new LogEntry (type, message, details));
+            }
+        }
+
+        private static string TypeString (LogEntryType type)
+        {
+            switch (type) {
+                case LogEntryType.Debug:         return "Debug";
+                case LogEntryType.Warning:       return "Warn ";
+                case LogEntryType.Error:         return "Error";
+                case LogEntryType.Information:   return "Info ";
+            }
+            return null;
+        }
+        
+        private static void OnNotify (LogEntry entry)
+        {
+            LogNotifyHandler handler = Notify;
+            if (handler != null) {
+                handler (new LogNotifyArgs (entry));
+            }
+        }
+        
+        #region Timer Methods
+        
+        public static uint DebugTimerStart (string message)
+        {
+            return TimerStart (message, false);
+        }
+        
+        public static uint InformationTimerStart (string message)
+        {
+            return TimerStart (message, true);
+        }
+        
+        private static uint TimerStart (string message, bool isInfo)
+        {
+            if (!Debugging && !isInfo) {
+                return 0;
+            }
+            
+            if (isInfo) {
+                Information (message);
+            } else {
+                Debug (message);
+            }
+            
+            return TimerStart (isInfo);
+        }
+        
+        public static uint DebugTimerStart ()
+        {
+            return TimerStart (false);
+        }
+        
+        public static uint InformationTimerStart ()
+        {
+            return TimerStart (true);
+        }
+            
+        private static uint TimerStart (bool isInfo)
+        {
+            if (!Debugging && !isInfo) {
+                return 0;
+            }
+            
+            uint timer_id = next_timer_id++;
+            timers.Add (timer_id, DateTime.Now);
+            return timer_id;
+        }
+        
+        public static void DebugTimerPrint (uint id)
+        {
+            if (!Debugging) {
+                return;
+            }
+            
+            TimerPrint (id, "Operation duration: {0}", false);
+        }
+        
+        public static void DebugTimerPrint (uint id, string message)
+        {
+            if (!Debugging) {
+                return;
+            }
+            
+            TimerPrint (id, message, false);
+        }
+        
+        public static void InformationTimerPrint (uint id)
+        {
+            TimerPrint (id, "Operation duration: {0}", true);
+        }
+        
+        public static void InformationTimerPrint (uint id, string message)
+        {
+            TimerPrint (id, message, true);
+        }
+        
+        private static void TimerPrint (uint id, string message, bool isInfo)
+        {
+            if (!Debugging && !isInfo) {
+                return;
+            }
+            
+            DateTime finish = DateTime.Now;
+            
+            if (!timers.ContainsKey (id)) {
+                return;
+            }
+            
+            TimeSpan duration = finish - timers[id];
+            string d_message;
+            if (duration.TotalSeconds < 60) {
+                d_message = String.Format ("{0}s", duration.TotalSeconds);
+            } else {
+                d_message = duration.ToString ();
+            }
+            
+            if (isInfo) {
+                InformationFormat (message, d_message);
+            } else {
+                DebugFormat (message, d_message);
+            }
+        }
+        
+        #endregion
+        
+        #region Public Debug Methods
+                                    
+        public static void Debug (string message, string details)
+        {
+            if (Debugging) {
+                Commit (LogEntryType.Debug, message, details, false);
+            }
+        }
+        
+        public static void Debug (string message)
+        {
+            if (Debugging) {
+                Debug (message, null);
+            }
+        }
+        
+        public static void DebugFormat (string format, params object [] args)
+        {
+            if (Debugging) {
+                Debug (String.Format (format, args));
+            }
+        }
+                
+        #endregion
+        
+        #region Public Information Methods
+            
+        public static void Information (string message)
+        {
+            Information (message, null);
+        }
+        
+        public static void Information (string message, string details)
+        {
+            Information (message, details, false);
+        }
+        
+        public static void Information (string message, string details, bool showUser)
+        {
+            Commit (LogEntryType.Information, message, details, showUser);
+        }
+        
+        public static void Information (string message, bool showUser)
+        {
+            Information (message, null, showUser);
+        }
+        
+        public static void InformationFormat (string format, params object [] args)
+        {
+            Information (String.Format (format, args));
+        }
+        
+        #endregion
+        
+        #region Public Warning Methods
+        
+        public static void Warning (string message)
+        {
+            Warning (message, null);
+        }
+        
+        public static void Warning (string message, string details)
+        {
+            Warning (message, details, false);
+        }
+        
+        public static void Warning (string message, string details, bool showUser)
+        {
+            Commit (LogEntryType.Warning, message, details, showUser);
+        }
+        
+        public static void Warning (string message, bool showUser)
+        {
+            Warning (message, null, showUser);
+        }
+        
+        public static void WarningFormat (string format, params object [] args)
+        {
+            Warning (String.Format (format, args));
+        }
+        
+        #endregion
+        
+        #region Public Error Methods
+        
+        public static void Error (string message)
+        {
+            Error (message, null);
+        }
+        
+        public static void Error (string message, string details)
+        {
+            Error (message, details, false);
+        }
+        
+        public static void Error (string message, string details, bool showUser)
+        {
+            Commit (LogEntryType.Error, message, details, showUser);
+        }
+        
+        public static void Error (string message, bool showUser)
+        {
+            Error (message, null, showUser);
+        }
+
+        public static void ErrorFormat (string format, params object [] args)
+        {
+            Error (String.Format (format, args));
+        }
+        
+        #endregion
+        
+        #region Public Exception Methods
+        
+        public static void Exception (Exception e)
+        {
+            Exception (null, e);
+        }
+        
+        public static void Exception (string message, Exception e)
+        {
+            Stack<Exception> exception_chain = new Stack<Exception> ();
+            StringBuilder builder = new StringBuilder ();
+            
+            while (e != null) {
+                exception_chain.Push (e);
+                e = e.InnerException;
+            }
+            
+            while (exception_chain.Count > 0) {
+                e = exception_chain.Pop ();
+                builder.AppendFormat ("{0} (in `{1}')", e.Message, e.Source).AppendLine ();
+                builder.Append (e.StackTrace);
+                if (exception_chain.Count > 0) {
+                    builder.AppendLine ();
+                }
+            }
+        
+            // FIXME: We should save these to an actual log file
+            Log.Warning (message ?? "Caught an exception", builder.ToString (), false);
+        }
+        
+        #endregion
+    }
+}

Modified: trunk/src/main.cs
==============================================================================
--- trunk/src/main.cs	(original)
+++ trunk/src/main.cs	Wed May 21 08:17:28 2008
@@ -142,7 +142,10 @@
 				Version ();
 				return 0;
 			
-			case "--debug": case "--trace": case "--profile": case "--uninstalled": case "--gdb":
+			case "--debug":
+				Log.Debugging = true;
+				break;
+			case "--trace": case "--profile": case "--uninstalled": case "--gdb":
 				break;
 
 			default:
@@ -176,7 +179,7 @@
 			} catch (Exception e) {
 				throw new ApplicationException ("F-Spot cannot find the Dbus session bus.  Make sure dbus is configured properly or start a new session for f-spot using \"dbus-launch f-spot\"", e);
 			}
-			Console.WriteLine ("Initializing Mono.Addins");
+			Log.Information ("Initializing Mono.Addins");
 			AddinManager.Initialize (FSpot.Global.BaseDirectory);
 			AddinManager.Registry.Update (null);
 			SetupService setupService = new SetupService (AddinManager.Registry);
@@ -193,11 +196,11 @@
 			while (control == null) {
 				try {
 					control = Core.FindInstance ();
-					System.Console.WriteLine ("Found active FSpot server: {0}", control);
+					Log.InformationFormat ("Found active FSpot server: {0}", control);
 					program = null;
 				} catch (System.Exception) { 
 					if (!shutdown)
-						System.Console.WriteLine ("Starting new FSpot server");
+						Log.Information ("Starting new FSpot server");
 				}
 				
 				Core core = null;



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]