Actionsfile feedback item #2975895 2010-03-24
[privoxy.git] / w32log.c
1 const char w32log_rcs[] = "$Id: w32log.c,v 1.35 2009/07/21 16:29:57 ler762 Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/w32log.c,v $
5  *
6  * Purpose     :  Functions for creating and destroying the log window,
7  *                ouputting strings, processing messages and so on.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2009 members of
10  *                the Privoxy team.  http://www.privoxy.org/
11  *
12  *                Written by and Copyright (C) 1999 Adam Lock
13  *                <locka@iol.ie>
14  *
15  *                This program is free software; you can redistribute it 
16  *                and/or modify it under the terms of the GNU General
17  *                Public License as published by the Free Software
18  *                Foundation; either version 2 of the License, or (at
19  *                your option) any later version.
20  *
21  *                This program is distributed in the hope that it will
22  *                be useful, but WITHOUT ANY WARRANTY; without even the
23  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
24  *                PARTICULAR PURPOSE.  See the GNU General Public
25  *                License for more details.
26  *
27  *                The GNU General Public License should be included with
28  *                this file.  If not, you can view it at
29  *                http://www.gnu.org/copyleft/gpl.html
30  *                or write to the Free Software Foundation, Inc., 59
31  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32  *
33  *********************************************************************/
34
35
36 #include "config.h"
37
38 #include <assert.h>
39 #include <stdio.h>
40
41 #ifndef STRICT
42 #define STRICT
43 #endif
44 #include <windows.h>
45 #include <richedit.h>
46
47 #include "project.h"
48 #include "w32log.h"
49 #include "w32taskbar.h"
50 #include "win32.h"
51 #include "w32res.h"
52 #include "jcc.h"
53 #include "miscutil.h"
54 #include "errlog.h"
55 #include "loadcfg.h"
56
57 const char w32res_h_rcs[] = W32RES_H_VERSION;
58
59 #ifdef __MINGW32__
60 #include "cygwin.h"
61 const char cygwin_h_rcs[] = CYGWIN_H_VERSION;
62 #endif
63
64 const char w32log_h_rcs[] = W32LOG_H_VERSION;
65
66 #ifndef _WIN_CONSOLE /* entire file */
67
68 /*
69  * Timers and the various durations
70  */
71 #define TIMER_ANIM_ID               1
72 #define TIMER_ANIM_TIME             100
73 #define TIMER_ANIMSTOP_ID           2
74 #define TIMER_ANIMSTOP_TIME         1000
75 #define TIMER_CLIPBUFFER_ID         3
76 #define TIMER_CLIPBUFFER_TIME       1000
77 #define TIMER_CLIPBUFFER_FORCE_ID   4
78 #define TIMER_CLIPBUFFER_FORCE_TIME 5000
79
80 /*
81  * Styles of text that can be output
82  */
83 #define STYLE_NONE      0
84 #define STYLE_HIGHLIGHT 1
85 #define STYLE_LINK      2
86 #define STYLE_HEADER    3
87
88 /*
89  * Number of frames of animation in tray activity sequence
90  */
91 #define ANIM_FRAMES 8
92
93 #define DEFAULT_MAX_BUFFER_LINES    200
94 #define DEFAULT_LOG_FONT_NAME       "MS Sans Serif"
95 #define DEFAULT_LOG_FONT_SIZE       8
96
97 /*
98  * These values affect the way the log window behaves, they should be read
99  * from a file but for the moment, they are hardcoded here. Some options are
100  * configurable through the UI.
101  */
102
103 /* Indicates whether task bar shows activity animation */
104 BOOL g_bShowActivityAnimation = 1;
105
106 /* Indicates whether the log window is shown */
107 BOOL g_bShowLogWindow = 1;
108
109 /* Indicates if the log window appears on the task bar */
110 BOOL g_bShowOnTaskBar = 0;
111
112 /* Indicates whether closing the log window really just hides it */
113 BOOL g_bCloseHidesWindow = 1;
114
115 /* Indicates if messages are logged at all */
116 BOOL g_bLogMessages = 1;
117
118 /* Indicates whether log messages are highlighted */
119 BOOL g_bHighlightMessages = 1;
120
121 /* Indicates if buffer is limited in size */
122 BOOL g_bLimitBufferSize = 1;
123
124 /* Maximum number of lines allowed in buffer when limited */
125 int g_nMaxBufferLines = DEFAULT_MAX_BUFFER_LINES;
126
127 /* Font to use */
128 char g_szFontFaceName[32] = DEFAULT_LOG_FONT_NAME;
129
130 /* Size of font to use */
131 int g_nFontSize = DEFAULT_LOG_FONT_SIZE;
132
133
134 /* FIXME: this is a kludge */
135
136 const char * g_default_actions_file = NULL;
137 const char * g_user_actions_file = NULL;
138 const char * g_re_filterfile = NULL;
139 #ifdef FEATURE_TRUST
140 const char * g_trustfile = NULL;
141 #endif /* def FEATURE_TRUST */
142
143 /* FIXME: end kludge */
144
145 /* Regular expression for detected URLs */
146 #define RE_URL "http:[^ \n\r]*"
147
148 /*
149  * Regular expressions that are used to perform highlight in the log window
150  */
151 static struct _Pattern
152 {
153    const char *str;
154    int style;
155    regex_t buffer;
156 } patterns_to_highlight[] =
157 {
158    /* url headers */
159    { RE_URL,                STYLE_LINK },
160 /* { "[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[^ \n\r]*", STYLE_LINK }, */
161    /* interesting text to highlight */
162    /*   see jcc.c crunch_reason for the full list */
163    { "Crunch: Blocked:",            STYLE_HIGHLIGHT },
164    { "Crunch: Untrusted",           STYLE_HIGHLIGHT },
165    { "Crunch: Redirected:",         STYLE_HIGHLIGHT },
166    { "Crunch: DNS failure",         STYLE_HIGHLIGHT },
167    { "Crunch: Forwarding failed",   STYLE_HIGHLIGHT },
168    { "Crunch: Connection failure",  STYLE_HIGHLIGHT },
169    { "Crunch: Out of memory",       STYLE_HIGHLIGHT },
170    { "Connect: Found reusable socket",     STYLE_HIGHLIGHT },
171    { "Connect: Reusing server socket",     STYLE_HIGHLIGHT },
172    { "Connect: Created new connection to", STYLE_HIGHLIGHT },
173    { "hung up on us",               STYLE_HIGHLIGHT },
174    { "Crunching Referer:",          STYLE_HIGHLIGHT },
175    /* what are all the possible error strings?? */
176    { "Error:",                      STYLE_HIGHLIGHT },
177    /* http headers */
178    { "referer:",            STYLE_HEADER },
179    { "proxy-connection:",   STYLE_HEADER },
180    { "proxy-agent:",        STYLE_HEADER },
181    { "user-agent:",         STYLE_HEADER },
182    { "host:",               STYLE_HEADER },
183    { "accept:",             STYLE_HEADER },
184    { "accept-encoding:",    STYLE_HEADER },
185    { "accept-language:",    STYLE_HEADER },
186    { "accept-charset:",     STYLE_HEADER },
187    { "accept-ranges:",      STYLE_HEADER },
188    { "date:",               STYLE_HEADER },
189    { "cache-control:",      STYLE_HEADER },
190    { "cache-last-checked:", STYLE_HEADER },
191    { "connection:",         STYLE_HEADER },
192    { "content-type",        STYLE_HEADER },
193    { "content-length",      STYLE_HEADER },
194    { "cookie",              STYLE_HEADER },
195    { "last-modified:",      STYLE_HEADER },
196    { "pragma:",             STYLE_HEADER },
197    { "server:",             STYLE_HEADER },
198    { "etag:",               STYLE_HEADER },
199    { "expires:",            STYLE_HEADER },
200    { "warning:",            STYLE_HEADER },
201    /* this is the terminator statement - do not delete! */
202    { NULL,                  STYLE_NONE }
203 };
204
205 /*
206  * Public variables
207  */
208 HWND g_hwndLogFrame;
209 HICON g_hiconApp;
210
211 /*
212  * Private variables
213  */
214 static CRITICAL_SECTION g_criticalsection;
215 static HWND g_hwndTray;
216 static HWND g_hwndLogBox;
217 static WNDPROC g_fnLogBox;
218 static HICON g_hiconAnim[ANIM_FRAMES];
219 static HICON g_hiconIdle;
220 static HICON g_hiconOff;
221 static int g_nAnimFrame;
222 static BOOL g_bClipPending = FALSE;
223 static int g_nRichEditVersion = 0;
224
225 /*
226  * Private functions
227  */
228 static HWND CreateLogWindow(HINSTANCE hInstance, int nCmdShow);
229 static HWND CreateHiddenLogOwnerWindow(HINSTANCE hInstance);
230 static LRESULT CALLBACK LogWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
231 static LRESULT CALLBACK LogOwnerWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
232 static LRESULT CALLBACK LogRichEditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
233 static BOOL InitRichEdit(void);
234 static void LogClipBuffer(void);
235 static void LogCreatePatternMatchingBuffers(void);
236 static void LogDestroyPatternMatchingBuffers(void);
237 static int LogPutStringNoMatch(const char *pszText, int style);
238 static void SetIdleIcon(void);
239
240
241 /*********************************************************************
242  *
243  * Function    :  InitLogWindow
244  *
245  * Description :  Initialise the log window.
246  *
247  * Parameters  :  None
248  *
249  * Returns     :  Always TRUE (there should be error checking on the resources).
250  *
251  *********************************************************************/
252 BOOL InitLogWindow(void)
253 {
254    int i;
255
256    /* Load the icons */
257    g_hiconIdle = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_IDLE));
258    g_hiconOff  = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_OFF));
259    for (i = 0; i < ANIM_FRAMES; i++)
260    {
261       g_hiconAnim[i] = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ANIMATED1 + i));
262    }
263    g_hiconApp = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_MAINICON));
264
265    /* Create the user interface */
266    g_hwndLogFrame = CreateLogWindow(g_hInstance, g_nCmdShow);
267    g_hwndTray = CreateTrayWindow(g_hInstance);
268    TrayAddIcon(g_hwndTray, 1, g_hiconApp, "Privoxy");
269
270    /* Create pattern matching buffers (for highlighting */
271    LogCreatePatternMatchingBuffers();
272
273    /* Create a critical section to protect multi-threaded access to certain things */
274    InitializeCriticalSection(&g_criticalsection);
275
276    return TRUE;
277
278 }
279
280
281 /*********************************************************************
282  *
283  * Function    :  TermLogWindow
284  *
285  * Description :  Cleanup the logwindow.
286  *
287  * Parameters  :  None
288  *
289  * Returns     :  N/A
290  *
291  *********************************************************************/
292 void TermLogWindow(void)
293 {
294    int i;
295
296    LogDestroyPatternMatchingBuffers();
297
298    TrayDeleteIcon(g_hwndTray, 1);
299    DeleteObject(g_hiconApp);
300    DeleteObject(g_hiconIdle);
301    DeleteObject(g_hiconOff);
302    for (i = 0; i < ANIM_FRAMES; i++)
303    {
304       DeleteObject(g_hiconAnim[i]);
305    }
306
307 }
308
309
310 /*********************************************************************
311  *
312  * Function    :  LogCreatePatternMatchingBuffers
313  *
314  * Description :  Compile the pattern matching buffers.
315  *
316  * Parameters  :  None
317  *
318  * Returns     :  N/A
319  *
320  *********************************************************************/
321 void LogCreatePatternMatchingBuffers(void)
322 {
323    int i;
324    for (i = 0; patterns_to_highlight[i].str != NULL; i++)
325    {
326       regcomp(&patterns_to_highlight[i].buffer, patterns_to_highlight[i].str, REG_ICASE);
327    }
328 }
329
330
331 /*********************************************************************
332  *
333  * Function    :  LogDestroyPatternMatchingBuffers
334  *
335  * Description :  Free up the pattern matching buffers.
336  *
337  * Parameters  :  None
338  *
339  * Returns     :  N/A
340  *
341  *********************************************************************/
342 void LogDestroyPatternMatchingBuffers(void)
343 {
344    int i;
345    for (i = 0; patterns_to_highlight[i].str != NULL; i++)
346    {
347       regfree(&patterns_to_highlight[i].buffer);
348    }
349 }
350
351
352 /*********************************************************************
353  *
354  * Function    :  LogGetURLUnderCursor
355  *
356  * Description :  Returns the URL from under the cursor (remember to free it!).
357  *
358  * Parameters  :  None
359  *
360  * Returns     :  NULL or a pointer to an URL string.
361  *
362  *********************************************************************/
363 char *LogGetURLUnderCursor(void)
364 {
365    char *szResult = NULL;
366    regex_t re;
367    POINT ptCursor;
368    POINTL ptl;
369    DWORD nPos;
370    DWORD nWordStart = 0;
371    DWORD nWordEnd = 0;
372
373    regcomp(&re, RE_URL, REG_ICASE);
374
375    /* Get the position of the cursor over the text window */
376    GetCursorPos(&ptCursor);
377    ScreenToClient(g_hwndLogBox, &ptCursor);
378    ptl.x = ptCursor.x;
379    ptl.y = ptCursor.y;
380
381    /* Search backwards and fowards to obtain the word that is highlighted */
382    nPos = LOWORD(SendMessage(g_hwndLogBox, EM_CHARFROMPOS, 0, (LPARAM) &ptl));
383    nWordStart = SendMessage(g_hwndLogBox, EM_FINDWORDBREAK, WB_LEFT, nPos);
384    nWordEnd = SendMessage(g_hwndLogBox, EM_FINDWORDBREAK, WB_RIGHTBREAK, nPos);
385
386    /* Compare the string to the pattern */
387    if (nWordEnd > nWordStart)
388    {
389       TEXTRANGE range;
390       regmatch_t match;
391
392       range.chrg.cpMin = nWordStart;
393       range.chrg.cpMax = nWordEnd;
394       range.lpstrText = (LPSTR)zalloc(nWordEnd - nWordStart + 1);
395       SendMessage(g_hwndLogBox, EM_GETTEXTRANGE, 0, (LPARAM) &range);
396
397       if (regexec(&re, range.lpstrText, 1, &match, 0) == 0)
398       {
399          szResult = range.lpstrText;
400       }
401       else
402       {
403          free(range.lpstrText);
404       }
405
406       regfree(&re);
407    }
408    return szResult;
409
410 }
411
412
413 /*********************************************************************
414  *
415  * Function    :  LogPutString
416  *
417  * Description :  Inserts text into the logging window.  This is really
418  *                a regexp aware wrapper function to `LogPutStringNoMatch'.
419  *
420  * Parameters  :
421  *          1  :  pszText = pointer to string going to the log window
422  *
423  * Returns     :  1 => success, else the return code from `LogPutStringNoMatch'.
424  *                FIXME: this is backwards to the rest of IJB and to common
425  *                programming practice.  Please use 0 => success instead.
426  *
427  *********************************************************************/
428 int LogPutString(const char *pszText)
429 {
430    int i;
431    int result = 0;
432
433    if (pszText == NULL || strlen(pszText) == 0)
434    {
435       return 1;
436    }
437
438    if (!g_bLogMessages)
439    {
440       return 1;
441    }
442
443    /* Critical section stops multiple threads doing nasty interactions that
444     * foul up the highlighting and output.
445     */
446    EnterCriticalSection(&g_criticalsection);
447
448    if (g_bHighlightMessages)
449    {
450       regmatch_t match;
451
452       /* First things first, regexp scan for various things that we would like highlighted */
453       for (i = 0; patterns_to_highlight[i].str != NULL; i++)
454       {
455          if (regexec(&patterns_to_highlight[i].buffer, pszText, 1, &match, 0) == 0)
456          {
457             char *pszBefore = NULL;
458             char *pszMatch = NULL;
459             char *pszAfter = NULL;
460             int nMatchSize;
461
462             /* Split the string up into pieces representing the strings, before
463                at and after the matching pattern
464              */
465             if (match.rm_so > 0)
466             {
467                pszBefore = (char *)malloc((match.rm_so + 1) * sizeof(char));
468                memset(pszBefore, 0, (match.rm_so + 1) * sizeof(char));
469                strncpy(pszBefore, pszText, match.rm_so);
470             }
471             if (match.rm_eo < (regoff_t)strlen(pszText))
472             {
473                pszAfter = strdup(&pszText[match.rm_eo]);
474             }
475             nMatchSize = match.rm_eo - match.rm_so;
476             pszMatch = (char *)malloc(nMatchSize + 1);
477             strncpy(pszMatch, &pszText[match.rm_so], nMatchSize);
478             pszMatch[nMatchSize] = '\0';
479
480             /* Recursively call LogPutString */
481             if (pszBefore)
482             {
483                LogPutString(pszBefore);
484                free(pszBefore);
485             }
486             if (pszMatch)
487             {
488                LogPutStringNoMatch(pszMatch, patterns_to_highlight[i].style);
489                free(pszMatch);
490             }
491             if (pszAfter)
492             {
493                LogPutString(pszAfter);
494                free(pszAfter);
495             }
496
497             result = 1;
498             goto end;
499          }
500       }
501    }
502
503    result = LogPutStringNoMatch(pszText, STYLE_NONE);
504
505 end:
506    LeaveCriticalSection(&g_criticalsection);
507
508    return result;
509
510 }
511
512
513 /*********************************************************************
514  *
515  * Function    :  LogPutStringNoMatch
516  *
517  * Description :  Puts a string into the logging window.
518  *
519  * Parameters  :
520  *          1  :  pszText = pointer to string going to the log window
521  *          2  :  style = STYLE_NONE, STYLE_HEADER, STYLE_HIGHLIGHT, or STYLE_LINK
522  *
523  * Returns     :  Always 1 => success.
524  *                FIXME: this is backwards to the rest of IJB and to common
525  *                programming practice.  Please use 0 => success instead.
526  *
527  *********************************************************************/
528 int LogPutStringNoMatch(const char *pszText, int style)
529 {
530    CHARRANGE range;
531    CHARFORMAT format;
532    int nTextLength;
533
534    assert(g_hwndLogBox);
535    if (g_hwndLogBox == NULL)
536    {
537       return 1;
538    }
539
540    /* TODO preserve existing selection */
541
542    /* Go to the end of the text */
543    nTextLength = GetWindowTextLength(g_hwndLogBox);
544    range.cpMin = nTextLength;
545    range.cpMax = nTextLength;
546    SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
547
548    /* Apply a formatting style */
549    memset(&format, 0, sizeof(format));
550    format.cbSize = sizeof(format);
551    format.dwMask = CFM_BOLD | CFM_UNDERLINE | CFM_STRIKEOUT |
552       CFM_ITALIC | CFM_COLOR | CFM_FACE | CFM_SIZE | CFM_CHARSET;
553    format.bCharSet = DEFAULT_CHARSET;
554    format.yHeight = (g_nFontSize * 1440) / 72;
555    strlcpy(format.szFaceName, g_szFontFaceName, sizeof(format.szFaceName));
556    if (style == STYLE_NONE)
557    {
558       /* DO NOTHING */
559       format.dwEffects |= CFE_AUTOCOLOR;
560    }
561    else if (style == STYLE_HEADER)
562    {
563       format.dwEffects |= CFE_AUTOCOLOR | CFE_ITALIC;
564    }
565    else if (style == STYLE_HIGHLIGHT)
566    {
567       format.dwEffects |= CFE_AUTOCOLOR | CFE_BOLD;
568    }
569    else if (style == STYLE_LINK)
570    {
571       format.dwEffects |= CFE_UNDERLINE;
572       format.crTextColor = RGB(0, 0, 255);
573    }
574    SendMessage(g_hwndLogBox, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &format);
575
576    /* Append text to the end */
577    SendMessage(g_hwndLogBox, EM_REPLACESEL, FALSE, (LPARAM) pszText);
578
579    /* TODO Restore the old selection */
580
581    /* Purge buffer */
582    if (strchr(pszText, '\n') != NULL)
583    {
584       SetTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_ID, TIMER_CLIPBUFFER_TIME, NULL);
585       if (!g_bClipPending)
586       {
587          /* Set the force clip timer going. This timer ensures clipping is done
588             intermittently even when there is a sustained burst of logging
589          */
590          SetTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_FORCE_ID, TIMER_CLIPBUFFER_FORCE_TIME, NULL);
591       }
592       g_bClipPending = TRUE;
593    }
594
595    return 1;
596
597 }
598
599
600 /*********************************************************************
601  *
602  * Function    :  LogShowActivity
603  *
604  * Description :  Start the spinner.
605  *
606  * Parameters  :  None
607  *
608  * Returns     :  N/A
609  *
610  *********************************************************************/
611 void LogShowActivity(void)
612 {
613    /* Start some activity timers */
614    if (g_bShowActivityAnimation)
615    {
616       SetTimer(g_hwndLogFrame, TIMER_ANIM_ID, TIMER_ANIM_TIME, NULL);
617       SetTimer(g_hwndLogFrame, TIMER_ANIMSTOP_ID, TIMER_ANIMSTOP_TIME, NULL);
618    }
619
620 }
621
622
623 /*********************************************************************
624  *
625  * Function    :  LogClipBuffer
626  *
627  * Description :  Prunes old lines from the log.
628  *
629  * Parameters  :  None
630  *
631  * Returns     :  N/A
632  *
633  *********************************************************************/
634 void LogClipBuffer(void)
635 {
636    int nLines = SendMessage(g_hwndLogBox, EM_GETLINECOUNT, 0, 0);
637    if (g_bLimitBufferSize && nLines > g_nMaxBufferLines)
638    {
639       /* Compute the range representing the lines to be deleted */
640       LONG nLastLineToDelete = nLines - g_nMaxBufferLines;
641       LONG nLastChar = SendMessage(g_hwndLogBox, EM_LINEINDEX, nLastLineToDelete, 0);
642       CHARRANGE range;
643       range.cpMin = 0;
644       range.cpMax = nLastChar;
645
646       /* TODO get current selection */
647
648       /* TODO adjust and clip old selection against range to be deleted */
649
650       /* Select range and erase it (turning off autoscroll to prevent
651          nasty scrolling) */
652       SendMessage(g_hwndLogBox, EM_SETOPTIONS, ECOOP_XOR, ECO_AUTOVSCROLL);
653       SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
654       SendMessage(g_hwndLogBox, EM_REPLACESEL, FALSE, (LPARAM) "");
655       SendMessage(g_hwndLogBox, EM_SETOPTIONS, ECOOP_XOR, ECO_AUTOVSCROLL);
656
657       /* reposition (back to) the end of the log content */
658       range.cpMin = SendMessage (g_hwndLogBox, WM_GETTEXTLENGTH, 0, 0);
659       range.cpMax = -1;
660       SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
661  
662       /* restore vertical ScrollBar stuff (messed up by AUTOVSCROLL) */
663       SendMessage (g_hwndLogBox, EM_SCROLL, SB_LINEDOWN, 0);
664  
665    }
666
667 }                                        
668
669
670 /*********************************************************************
671  *
672  * Function    :  CreateHiddenLogOwnerWindow
673  *
674  * Description :  Creates a hidden owner window that stops the log
675  *                window appearing in the task bar.
676  *
677  * Parameters  :
678  *          1  :  hInstance = application's instance handle
679  *
680  * Returns     :  Handle to newly created window.
681  *
682  *********************************************************************/
683 HWND CreateHiddenLogOwnerWindow(HINSTANCE hInstance)
684 {
685    static const char *szWndName = "PrivoxyLogOwner";
686    WNDCLASS wc;
687    HWND hwnd;
688
689    wc.style          = 0;
690    wc.lpfnWndProc    = LogOwnerWindowProc;
691    wc.cbClsExtra     = 0;
692    wc.cbWndExtra     = 0;
693    wc.hInstance      = hInstance;
694    wc.hIcon          = g_hiconApp;
695    wc.hCursor        = 0;
696    wc.hbrBackground  = 0;
697    wc.lpszMenuName   = 0;
698    wc.lpszClassName  = szWndName;
699
700    RegisterClass(&wc);
701
702    hwnd = CreateWindow(szWndName, szWndName,
703       WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
704       CW_USEDEFAULT, NULL, NULL, hInstance, NULL );
705
706    return hwnd;
707
708 }
709
710
711 /*********************************************************************
712  *
713  * Function    :  LogOwnerWindowProc
714  *
715  * Description :  Dummy procedure that does nothing special.
716  *
717  * Parameters  :
718  *          1  :  hwnd = window handle
719  *          2  :  uMsg = message number
720  *          3  :  wParam = first param for this message
721  *          4  :  lParam = next param for this message
722  *
723  * Returns     :  Same as `DefWindowProc'.
724  *
725  *********************************************************************/
726 LRESULT CALLBACK LogOwnerWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
727 {
728    return DefWindowProc(hwnd, uMsg, wParam, lParam);
729
730 }
731
732
733 /*********************************************************************
734  *
735  * Function    :  CreateLogWindow
736  *
737  * Description :  Create the logging window.
738  *
739  * Parameters  :
740  *          1  :  hInstance = application's instance handle
741  *          2  :  nCmdShow = window show value (MIN, MAX, NORMAL, etc...)
742  *
743  * Returns     :  Handle to newly created window.
744  *
745  *********************************************************************/
746 HWND CreateLogWindow(HINSTANCE hInstance, int nCmdShow)
747 {
748    static const char *szWndName = "PrivoxyLogWindow";
749    static const char *szWndTitle = "Privoxy";
750
751    HWND hwnd = NULL;
752    HWND hwndOwner = (g_bShowOnTaskBar) ? NULL : CreateHiddenLogOwnerWindow(hInstance);
753    RECT rcClient;
754    WNDCLASSEX wc;
755
756    memset(&wc, 0, sizeof(wc));
757    wc.cbSize         = sizeof(wc);
758    wc.style          = CS_DBLCLKS;
759    wc.lpfnWndProc    = LogWindowProc;
760    wc.cbClsExtra     = 0;
761    wc.cbWndExtra     = 0;
762    wc.hInstance      = hInstance;
763    wc.hIcon          = g_hiconApp;
764    wc.hCursor        = 0;
765    wc.hbrBackground  = 0;
766    wc.lpszMenuName   = MAKEINTRESOURCE(IDR_LOGVIEW);
767    wc.lpszClassName  = szWndName;
768    wc.hbrBackground  = GetStockObject(WHITE_BRUSH);
769    RegisterClassEx(&wc);
770
771    hwnd = CreateWindowEx(WS_EX_APPWINDOW, szWndName, szWndTitle,
772       WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
773       CW_USEDEFAULT, hwndOwner, NULL, hInstance, NULL);
774
775    /* Now create a child list box */
776    GetClientRect(hwnd, &rcClient);
777
778    /* Create a rich edit control */
779    InitRichEdit();
780    g_hwndLogBox = CreateWindowEx(0, (g_nRichEditVersion == 0x0100) ? "RichEdit" : RICHEDIT_CLASS, "",
781       ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY | ES_NOHIDESEL | WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_VISIBLE,
782       rcClient.left, rcClient.top, rcClient.right, rcClient.bottom,
783       hwnd, NULL, hInstance, NULL);
784 /* SendMessage(g_hwndLogBox, EM_SETWORDWRAPMODE, 0, 0); */
785
786    /* Subclass the control to catch certain messages */
787    g_fnLogBox = (WNDPROC) GetWindowLong(g_hwndLogBox, GWL_WNDPROC);
788    SetWindowLong(g_hwndLogBox, GWL_WNDPROC, (LONG) LogRichEditProc);
789
790    /* Minimizing looks stupid when the log window is not on the task bar, so hide instead */
791    if (!g_bShowOnTaskBar &&
792          (nCmdShow == SW_SHOWMINIMIZED ||
793           nCmdShow == SW_MINIMIZE ||
794           nCmdShow == SW_SHOWMINNOACTIVE))
795    {
796       g_bShowLogWindow = FALSE;
797       nCmdShow = SW_HIDE;
798    }
799
800    ShowWindow(hwnd, nCmdShow);
801    UpdateWindow(hwnd);
802
803
804    GetClientRect(g_hwndLogFrame, &rcClient);
805    SetWindowPos(g_hwndLogBox, NULL, rcClient.left, rcClient.top, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, SWP_NOZORDER);
806
807    return hwnd;
808
809 }
810
811
812 /*********************************************************************
813  *
814  * Function    :  InitRichEdit
815  *
816  * Description :  Initialise the rich edit control library.
817  *
818  * Parameters  :  None
819  *
820  * Returns     :  TRUE => success, FALSE => failure.
821  *                FIXME: this is backwards to the rest of IJB and to common
822  *                programming practice.  Please use 0 => success instead.
823  *
824  *********************************************************************/
825 BOOL InitRichEdit(void)
826 {
827    static HINSTANCE hInstRichEdit;
828    if (hInstRichEdit == NULL)
829    {
830       g_nRichEditVersion = 0;
831       hInstRichEdit = LoadLibraryA("RICHED20.DLL");
832       if (hInstRichEdit)
833       {
834          g_nRichEditVersion = _RICHEDIT_VER;
835       }
836       else
837       {
838          hInstRichEdit = LoadLibraryA("RICHED32.DLL");
839          if (hInstRichEdit)
840          {
841             g_nRichEditVersion = 0x0100;
842          }
843       }
844    }
845    return (hInstRichEdit != NULL) ? TRUE : FALSE;
846
847 }
848
849
850 /*********************************************************************
851  *
852  * Function    :  ShowLogWindow
853  *
854  * Description :  Shows or hides the log window.  We will also raise the
855  *                window on a show command in case it is buried.
856  *
857  * Parameters  :
858  *          1  :  bShow = TRUE to show, FALSE to mimize/hide
859  *
860  * Returns     :  N/A
861  *
862  *********************************************************************/
863 void ShowLogWindow(BOOL bShow)
864 {
865    if (bShow)
866    {
867       SetForegroundWindow(g_hwndLogFrame);
868       SetWindowPos(g_hwndLogFrame, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
869       
870    }
871    else if (g_bShowOnTaskBar)
872    {
873       ShowWindow(g_hwndLogFrame, SW_MINIMIZE);
874    }
875    else
876    {
877       ShowWindow(g_hwndLogFrame, SW_HIDE);
878    }
879 }
880
881
882 /*********************************************************************
883  *
884  * Function    :  EditFile
885  *
886  * Description :  Opens the specified setting file for editing.
887  * FIXME: What if the file has no associated application. Check for return values
888 *        from ShellExecute??
889  *
890  * Parameters  :
891  *          1  :  filename = filename from the config (aka config.txt) file.
892  *
893  * Returns     :  N/A
894  *
895  *********************************************************************/
896 void EditFile(const char *filename)
897 {
898    if (filename)
899    {
900       ShellExecute(g_hwndLogFrame, "open", filename, NULL, NULL, SW_SHOWNORMAL);
901    }
902
903 }
904
905
906 /*--------------------------------------------------------------------------*/
907 /* Windows message handlers                                                 */
908 /*--------------------------------------------------------------------------*/
909
910
911 /*********************************************************************
912  *
913  * Function    :  OnLogRButtonUp
914  *
915  * Description :  Handler for WM_RBUTTONUP messages.
916  *
917  * Parameters  :
918  *          1  :  nModifier = wParam from mouse message (unused)
919  *          2  :  x = x coordinate of the mouse event
920  *          3  :  y = y coordinate of the mouse event
921  *
922  * Returns     :  N/A
923  *
924  *********************************************************************/
925 void OnLogRButtonUp(int nModifier, int x, int y)
926 {
927    HMENU hMenu = LoadMenu(g_hInstance, MAKEINTRESOURCE(IDR_POPUP_SELECTION));
928    if (hMenu != NULL)
929    {
930       HMENU hMenuPopup = GetSubMenu(hMenu, 0);
931
932       /* Check if there is a selection */
933       CHARRANGE range;
934       SendMessage(g_hwndLogBox, EM_EXGETSEL, 0, (LPARAM) &range);
935       if (range.cpMin == range.cpMax)
936       {
937          EnableMenuItem(hMenuPopup, ID_EDIT_COPY, MF_BYCOMMAND | MF_GRAYED);
938       }
939       else
940       {
941          EnableMenuItem(hMenuPopup, ID_EDIT_COPY, MF_BYCOMMAND | MF_ENABLED);
942       }
943
944       /* Display the popup */
945       TrackPopupMenu(hMenuPopup, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, x, y, 0, g_hwndLogFrame, NULL);
946       DestroyMenu(hMenu);
947    }
948
949 }
950
951
952 /*********************************************************************
953  *
954  * Function    :  OnLogCommand
955  *
956  * Description :  Handler for WM_COMMAND messages.
957  *
958  * Parameters  :
959  *          1  :  nCommand = the command portion of the menu selection event
960  *
961  * Returns     :  N/A
962  *
963  *********************************************************************/
964 void OnLogCommand(int nCommand)
965 {
966    switch (nCommand)
967    {
968       case ID_TOGGLE_SHOWWINDOW:
969          g_bShowLogWindow = !g_bShowLogWindow;
970
971          ShowLogWindow(g_bShowLogWindow);
972          break;
973
974       case ID_FILE_EXIT:
975          PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
976          break;
977
978       case ID_EDIT_COPY:
979          SendMessage(g_hwndLogBox, WM_COPY, 0, 0);
980          break;
981
982       case ID_VIEW_CLEARLOG:
983          SendMessage(g_hwndLogBox, WM_SETTEXT, 0, (LPARAM) "");
984          break;
985
986       case ID_VIEW_LOGMESSAGES:
987          g_bLogMessages = !g_bLogMessages;
988          /* SaveLogSettings(); */
989          break;
990
991       case ID_VIEW_MESSAGEHIGHLIGHTING:
992          g_bHighlightMessages = !g_bHighlightMessages;
993          /* SaveLogSettings(); */
994          break;
995
996       case ID_VIEW_LIMITBUFFERSIZE:
997          g_bLimitBufferSize = !g_bLimitBufferSize;
998          /* SaveLogSettings(); */
999          break;
1000
1001       case ID_VIEW_ACTIVITYANIMATION:
1002          g_bShowActivityAnimation = !g_bShowActivityAnimation;
1003          /* SaveLogSettings(); */
1004          break;
1005
1006 #ifdef FEATURE_TOGGLE
1007       /* by haroon - change toggle to its opposite value */
1008       case ID_TOGGLE_ENABLED:
1009          global_toggle_state = !global_toggle_state;
1010          if (global_toggle_state)
1011          {
1012             log_error(LOG_LEVEL_INFO, "Now toggled ON.");
1013          }
1014          else
1015          {
1016             log_error(LOG_LEVEL_INFO, "Now toggled OFF.");
1017          }
1018          SetIdleIcon();
1019          break;
1020 #endif /* def FEATURE_TOGGLE */
1021
1022       case ID_TOOLS_EDITCONFIG:
1023          EditFile(configfile);
1024          break;
1025
1026       case ID_TOOLS_EDITDEFAULTACTIONS:
1027          EditFile(g_default_actions_file);
1028          break;
1029
1030       case ID_TOOLS_EDITUSERACTIONS:
1031          EditFile(g_user_actions_file);
1032          break;
1033
1034       case ID_TOOLS_EDITFILTERS:
1035          EditFile(g_re_filterfile);
1036          break;
1037
1038 #ifdef FEATURE_TRUST
1039       case ID_TOOLS_EDITTRUST:
1040          EditFile(g_trustfile);
1041          break;
1042 #endif /* def FEATURE_TRUST */
1043
1044       case ID_HELP_GPL:
1045          ShellExecute(g_hwndLogFrame, "open", "LICENSE.txt", NULL, NULL, SW_SHOWNORMAL);
1046          break;
1047
1048       case ID_HELP_FAQ:
1049          ShellExecute(g_hwndLogFrame, "open", "doc\\faq\\index.html", NULL, NULL, SW_SHOWNORMAL);
1050          break;
1051
1052       case ID_HELP_MANUAL:
1053          ShellExecute(g_hwndLogFrame, "open", "doc\\user-manual\\index.html", NULL, NULL, SW_SHOWNORMAL);
1054          break;
1055
1056       case ID_HELP_STATUS:
1057          ShellExecute(g_hwndLogFrame, "open", CGI_PREFIX "show-status", NULL, NULL, SW_SHOWNORMAL);
1058          break;
1059
1060       case ID_HELP_ABOUT:
1061          MessageBox(g_hwndLogFrame, win32_blurb, "About Privoxy", MB_OK);
1062          break;
1063
1064       default:
1065          /* DO NOTHING */
1066          break;
1067    }
1068
1069 }
1070
1071
1072 /*********************************************************************
1073  *
1074  * Function    :  OnLogInitMenu
1075  *
1076  * Description :  Handler for WM_INITMENU messages.  Enable, disable,
1077  *                check, and/or uncheck menu options as apropos.
1078  *
1079  * Parameters  :
1080  *          1  :  hmenu = handle to menu to "make current"
1081  *
1082  * Returns     :  N/A
1083  *
1084  *********************************************************************/
1085 void OnLogInitMenu(HMENU hmenu)
1086 {
1087    /* Only enable editors if there is a file to edit */
1088    EnableMenuItem(hmenu, ID_TOOLS_EDITDEFAULTACTIONS, MF_BYCOMMAND | (g_default_actions_file ? MF_ENABLED : MF_GRAYED));
1089    EnableMenuItem(hmenu, ID_TOOLS_EDITUSERACTIONS, MF_BYCOMMAND | (g_user_actions_file ? MF_ENABLED : MF_GRAYED));
1090    EnableMenuItem(hmenu, ID_TOOLS_EDITFILTERS, MF_BYCOMMAND | (g_re_filterfile ? MF_ENABLED : MF_GRAYED));
1091 #ifdef FEATURE_TRUST
1092    EnableMenuItem(hmenu, ID_TOOLS_EDITTRUST, MF_BYCOMMAND | (g_trustfile ? MF_ENABLED : MF_GRAYED));
1093 #endif /* def FEATURE_TRUST */
1094
1095    /* Check/uncheck options */
1096    CheckMenuItem(hmenu, ID_VIEW_LOGMESSAGES, MF_BYCOMMAND | (g_bLogMessages ? MF_CHECKED : MF_UNCHECKED));
1097    CheckMenuItem(hmenu, ID_VIEW_MESSAGEHIGHLIGHTING, MF_BYCOMMAND | (g_bHighlightMessages ? MF_CHECKED : MF_UNCHECKED));
1098    CheckMenuItem(hmenu, ID_VIEW_LIMITBUFFERSIZE, MF_BYCOMMAND | (g_bLimitBufferSize ? MF_CHECKED : MF_UNCHECKED));
1099    CheckMenuItem(hmenu, ID_VIEW_ACTIVITYANIMATION, MF_BYCOMMAND | (g_bShowActivityAnimation ? MF_CHECKED : MF_UNCHECKED));
1100 #ifdef FEATURE_TOGGLE
1101    /* by haroon - menu item for Enable toggle on/off */
1102    CheckMenuItem(hmenu, ID_TOGGLE_ENABLED, MF_BYCOMMAND | (global_toggle_state ? MF_CHECKED : MF_UNCHECKED));
1103 #endif /* def FEATURE_TOGGLE */
1104    CheckMenuItem(hmenu, ID_TOGGLE_SHOWWINDOW, MF_BYCOMMAND | (g_bShowLogWindow ? MF_CHECKED : MF_UNCHECKED));
1105
1106 }
1107
1108
1109 /*********************************************************************
1110  *
1111  * Function    :  OnLogTimer
1112  *
1113  * Description :  Handler for WM_TIMER messages.
1114  *
1115  * Parameters  :
1116  *          1  :  nTimer = timer id (animation start/stop or clip buffer)
1117  *
1118  * Returns     :  N/A
1119  *
1120  *********************************************************************/
1121 void OnLogTimer(int nTimer)
1122 {
1123    switch (nTimer)
1124    {
1125       case TIMER_ANIM_ID:
1126          TraySetIcon(g_hwndTray, 1, g_hiconAnim[g_nAnimFrame++ % ANIM_FRAMES]);
1127          break;
1128
1129       case TIMER_ANIMSTOP_ID:
1130          g_nAnimFrame = 0;
1131          SetIdleIcon();
1132          KillTimer(g_hwndLogFrame, TIMER_ANIM_ID);
1133          KillTimer(g_hwndLogFrame, TIMER_ANIMSTOP_ID);
1134          break;
1135
1136       case TIMER_CLIPBUFFER_ID:
1137       case TIMER_CLIPBUFFER_FORCE_ID:
1138          LogClipBuffer();
1139          g_bClipPending = FALSE;
1140          KillTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_ID);
1141          KillTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_FORCE_ID);
1142          break;
1143
1144       default:
1145          /* DO NOTHING */
1146          break;
1147    }
1148
1149 }
1150
1151
1152 /*********************************************************************
1153  *
1154  * Function    :  SetIdleIcon
1155  *
1156  * Description :  Sets the tray icon to either idle or off
1157  *
1158  * Parameters  :  none
1159  *
1160  * Returns     :  N/A
1161  *
1162  *********************************************************************/
1163 void SetIdleIcon()
1164 {
1165 #ifdef FEATURE_TOGGLE
1166          if (!global_toggle_state)
1167          {
1168             TraySetIcon(g_hwndTray, 1, g_hiconOff);
1169             /* log_error(LOG_LEVEL_INFO, "Privoxy OFF icon selected."); */
1170          }
1171          else
1172 #endif /* def FEATURE_TOGGLE */
1173          TraySetIcon(g_hwndTray, 1, g_hiconIdle);
1174 }
1175
1176
1177 /*********************************************************************
1178  *
1179  * Function    :  LogRichEditProc
1180  *
1181  * Description :  Window subclass routine handles some events for the rich edit control.
1182  *
1183  * Parameters  :
1184  *          1  :  hwnd = window handle of the rich edit control
1185  *          2  :  uMsg = message number
1186  *          3  :  wParam = first param for this message
1187  *          4  :  lParam = next param for this message
1188  *
1189  * Returns     :  Appropriate M$ window message handler codes.
1190  *
1191  *********************************************************************/
1192 LRESULT CALLBACK LogRichEditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1193 {
1194    switch (uMsg)
1195    {
1196       case WM_RBUTTONUP:
1197       {
1198          POINT pt;
1199          pt.x = LOWORD(lParam);
1200          pt.y = HIWORD(lParam);
1201          ClientToScreen(hwnd, &pt);
1202          OnLogRButtonUp(wParam, pt.x, pt.y);
1203          return 0;
1204       }
1205       case WM_CHAR:
1206       {
1207          if ((GetKeyState(VK_CONTROL) != 0) && (wParam == 4)) /* ctrl+d */
1208          {
1209              OnLogCommand(ID_VIEW_CLEARLOG);
1210              return 0;
1211          }
1212       }
1213    }
1214    return CallWindowProc(g_fnLogBox, hwnd, uMsg, wParam, lParam);
1215
1216 }
1217
1218
1219 /*********************************************************************
1220  *
1221  * Function    :  LogWindowProc
1222  *
1223  * Description :  Windows call back routine handles events on the log window.
1224  *
1225  * Parameters  :
1226  *          1  :  hwnd = handle of the logging window
1227  *          2  :  uMsg = message number
1228  *          3  :  wParam = first param for this message
1229  *          4  :  lParam = next param for this message
1230  *
1231  * Returns     :  Appropriate M$ window message handler codes.
1232  *
1233  *********************************************************************/
1234 LRESULT CALLBACK LogWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1235 {
1236    switch (uMsg)
1237    {
1238       case WM_CREATE:
1239          return 0;
1240
1241       case WM_CLOSE:
1242          /* This is the end - beautiful friend - the end */
1243          DestroyWindow(g_hwndLogBox);
1244          DestroyWindow(g_hwndLogFrame);
1245          return 0;
1246
1247       case WM_DESTROY:
1248          PostQuitMessage(0);
1249          return 0;
1250
1251       case WM_SHOWWINDOW:
1252          g_bShowLogWindow = wParam;
1253       case WM_SIZE:
1254          /* Resize the logging window to fit the new frame */
1255          if (g_hwndLogBox)
1256          {
1257             RECT rc;
1258             GetClientRect(g_hwndLogFrame, &rc);
1259             SetWindowPos(g_hwndLogBox, NULL, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SWP_NOZORDER);
1260          }
1261          return 0;
1262
1263       case WM_INITMENU:
1264          OnLogInitMenu((HMENU) wParam);
1265          return 0;
1266
1267       case WM_TIMER:
1268          OnLogTimer(wParam);
1269          return 0;
1270
1271       case WM_COMMAND:
1272          OnLogCommand(LOWORD(wParam));
1273          return 0;
1274
1275       case WM_SYSCOMMAND:
1276          switch (wParam)
1277          {
1278             case SC_CLOSE:
1279                if (g_bCloseHidesWindow)
1280                {
1281                   ShowLogWindow(FALSE);
1282                   return 0;
1283                }
1284                break;
1285             case SC_MINIMIZE:
1286                ShowLogWindow(FALSE);
1287                return 0;
1288          }
1289          break;
1290
1291       case WM_CHAR:
1292          if ((GetKeyState(VK_CONTROL) != 0) && (wParam == 4)) /* ctrl+d */
1293          {
1294              OnLogCommand(ID_VIEW_CLEARLOG);
1295              return 0;
1296          }
1297          break;
1298    }
1299
1300    return DefWindowProc(hwnd, uMsg, wParam, lParam);
1301
1302 }
1303
1304 #endif /* ndef _WIN_CONSOLE - entire file */
1305
1306 /*
1307   Local Variables:
1308   tab-width: 3
1309   end:
1310 */